File size: 1,793 Bytes
6e13570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const { env, assertProductionSafety } = require("./config/env");
const { connectDB, disconnectDB } = require("./config/db");
const logger = require("./utils/logger");
const app = require("./app");

assertProductionSafety();

let server;

async function start() {
  try {
    await connectDB();
    server = app.listen(env.port, () => {
      logger.info(`Aynwerd API listening on port ${env.port} [${env.nodeEnv}]`);
      // Logged deliberately at startup: this is the #1 source of CORS
      // support confusion (a typo'd env var name, stray quotes, a
      // trailing slash, or the value falling back to its localhost
      // default because it was never actually set). Seeing the parsed
      // array here removes all guesswork versus staring at the raw
      // dashboard value.
      logger.info(`CORS allow-list (CLIENT_ORIGINS parsed as): ${JSON.stringify(env.clientOrigins)}`);
    });
  } catch (err) {
    logger.error("Failed to start server", { error: err.message });
    process.exit(1);
  }
}

async function shutdown(signal) {
  logger.info(`Received ${signal}, shutting down gracefully...`);
  if (server) {
    server.close(async () => {
      await disconnectDB();
      process.exit(0);
    });
    // Force-exit if something hangs
    setTimeout(() => process.exit(1), 10000).unref();
  } else {
    process.exit(0);
  }
}

process.on("SIGINT", () => shutdown("SIGINT"));
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("unhandledRejection", (reason) => {
  logger.error("Unhandled promise rejection", { reason: reason?.message || reason });
});
process.on("uncaughtException", (err) => {
  logger.error("Uncaught exception", { error: err.message, stack: err.stack });
  process.exit(1);
});

start();