Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·270 lines (235 loc) · 7.04 KB
/
Copy pathserver.js
File metadata and controls
executable file
·270 lines (235 loc) · 7.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
require("dotenv/config");
const http = require("http");
const https = require("https");
const os = require("os");
const fs = require("fs");
const ip = require("ip");
const path = require("path");
const debug = require("debug")("NUKU-API");
const app = require("./app");
const Env = require("./config/env");
const websocket = require("./routes/ws");
const logger = require("./libs/logger").winstonLogger;
const redis = require("./libs/redis").createRedisIoClient;
const cluster = require("cluster");
const { createGraphQLServer } = require("./graphql-server");
/**
* Nuku HTTP Server
*/
class Server {
/**
*
*/
server;
/**
*
*/
#hostname;
/**
*
*/
#port;
#app;
#apps;
/**
*
* @param {Express.Application} app
*/
constructor(app) {
logger.debug("Starting NUKU API server...");
// if (Env.NODE_ENV === "dev") {
this.#app = app;
this.#apps = new Map();
this.server = http.createServer(this.#app);
// } else {
// // stream data
// const options = {
// key: fs.readFileSync(path.join(__dirname, "certs", "nuku-key.pem")),
// cert: fs.readFileSync(path.join(__dirname, "certs", "nuku.pem")),
// };
// server = https.createServer(options, app);
// }
this.#hostname = Env.HOST;
this.#port = Env.PORT;
// this.listenForEvents();
this.setupSignalListeners();
}
onListen = () => {
const details = ip.address();
let localAddress = null;
let networkAddress = null;
const interfaces = os.networkInterfaces();
const getNetworkAddress = () => {
for (const name of Object.keys(interfaces)) {
for (const internetInterface of interfaces[name]) {
const { address, family, internal } = internetInterface;
if (family === "IPv4" && !internal) {
return address;
}
}
}
};
if (typeof details === "string") {
localAddress = details;
} else if (typeof details === "object" && details.port) {
const address = details.address === "::" ? "localhost" : details.address;
const ip = getNetworkAddress();
localAddress = `http://${address}:${details.port}`;
networkAddress = `http://${ip}:${details.port}`;
}
let log = "\n--------------------------------------------------\n";
if (localAddress) {
log += `Server running on port ${localAddress}\n`;
}
if (networkAddress) {
log += `Server running on port ${networkAddress}`;
}
log += "\n--------------------------------------------------\n";
// console.debug(log);
// console.debug(boxen(`Server running on ${localAddress}`));
logger.debug(`Server running at ${localAddress}`);
logger.debug(`REST API v1 ready at http://localhost:${this.#port}/api/v1`);
logger.debug(`REST API v2 ready at http://localhost:${this.#port}/api/v2`);
logger.debug(`API docs ready at http://localhost:${this.#port}/api/docs`);
logger.debug(
`GraphQL endpoint ready at http://localhost:${this.#port}/graphql`,
);
logger.debug(
`Server-Sent Events (SSE) endpoint ready at http://localhost:${
this.#port
}/events`,
);
logger.debug(`WebSocket server ready at ws://localhost:${this.#port}/ws`);
logger.debug(`Webhook ready at http://localhost:${this.#port}/webhook`);
};
onError = (error) => {
debug("Error occurred: " + error);
};
onStop = () => {
debug("Stopping server");
this.#app.end();
this.#app.destroy();
};
onClose = () => {
debug("SIGINT signal received: closing HTTP server");
if (this.server) {
this.server.close(() => {
debug("HTTP server closed");
process.exit(0);
});
}
};
/**
*
* @param {app.Application} app
*/
attachApp(app) {
if (!this.#apps.has(app.name, app)) {
this.#apps.set(app.name, app);
}
}
attachServerEvents = (serverEvents) => {
// attach sse to the http server
serverEvents(this.server);
};
attachWebSocket = (ws) => {
// attach websocket to the http server
ws(this.server);
};
attachGraphql = (gql) => {
// attach graphql server to the http server
console.log("attachGraphql", gql);
this.#app.use(gql(this.server));
};
start = () => {
// listen on the port
this.server.listen(this.#port, this.#hostname, this.onListen);
this.server.on("error", this.onError);
this.server.on("end", this.onStop);
};
listenForEvents() {
this.server.on("connection", (stream) => {
console.log("someone connected!");
});
// Listen to the request event
this.server.on("request", async (req, res) => {
if (req.url === "/" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Welcome to the Home Page!");
} else if (req.url === "/health" && req.method === "GET") {
// optional: add further things to check (e.g. connecting to dababase)
const healthcheck = {
uptime: process.uptime(),
message: "OK",
timestamp: Date.now(),
environment: Env.NODE_ENV,
status: "healthy",
};
try {
await redis.ping();
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
...healthcheck,
redis: "healthy",
}),
);
} catch (e) {
healthcheck.message = e;
logger.error("Error creating user", {
error: e.message,
stack: e.stack,
body: req.body,
});
res.writeHead(503, { "Content-Type": "application/json" });
res.end(JSON.stringify(healthcheck));
}
} else {
// Fallback for routes that do not exist
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("404 Not Found");
}
});
}
setupSignalListeners = () => {
process.on("message", (message) => {
debug("Message: " + message);
});
process.on("uncaughtException", (err) => {
logger.error("There was an uncaught error", err);
process.exit(1); // exit application
});
process.on("unhandledRejection", (ex) => {
logger.error(`Unhandled Rejection: ${ex.message}`, ex);
process.exit(1);
});
process.on("SIGTERM", this.onClose);
process.on("SIGINT", this.onClose);
};
}
const numCPUs = os.cpus().length;
// if (cluster.isMaster) {
// for (let i = 0; i < numCPUs; i++) {
// cluster.fork();
// }
// cluster.on('exit', (worker, code, signal) => {
// console.log(`Worker ${worker.process.pid} died.`);
// });
// } else {
// Initialize server (e.g., with express)
const server = new Server(app);
server.attachWebSocket(websocket);
// server.attachServerEvents();
// server.attachGraphql(createGraphQLServer(server));
// server.attachApp([
// graphql
// ]);
// Handle startup errors gracefully
createGraphQLServer(app, server.server).catch((error) => {
console.error("Failed to start server:", error);
process.exit(1);
});
server.start();
// Worker processes share the server
// require('./server');
// }