-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
155 lines (135 loc) · 4.97 KB
/
Copy pathserver.ts
File metadata and controls
155 lines (135 loc) · 4.97 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
#!/usr/bin/env node
import { createServer } from 'node:http';
import '#src/env';
import { app } from '#src/app';
import { state } from '#src/state';
import { checkDatabaseHealth, checkDatabaseMigrations, runMigrations, runSeeds, shutdownDatabase } from '#src/db/index';
import { getJwksClient } from '#src/middlewares/helpers/index';
import { getLogger } from '#src/utils/index';
const automigrate = process.env.APP_AUTOMIGRATE?.toLowerCase() === 'true';
const log = getLogger(import.meta.filename);
const port = normalizePort(process.env.APP_PORT ?? '3000');
const server = createServer(app);
// Prevent unhandled rejections from crashing application
process.on('unhandledRejection', (err: Error): void => {
if (err?.stack) log.error(err);
});
// Graceful shutdown support
const signals: readonly NodeJS.Signals[] = ['SIGHUP', 'SIGINT', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'];
signals.forEach((signal) => process.on(signal, () => shutdown(signal)));
// Perform preliminary system and database checks
try {
await validateConfig();
await startup();
} catch (error) {
log.fatal(`Startup failure: ${error instanceof Error ? error.message : String(error)}`);
shutdown('SIGABRT');
}
// Create HTTP server and listen on provided port, on all network interfaces.
server.listen(port, () => {
const url = `http://localhost:${port}`;
const modeText = {
none: ' in no authentication mode',
authn: ' in authentication only mode',
authz: ' in scoped authorization mode'
}[state.authMode!];
if (state.ready) log.info({ authMode: state.authMode, url: url }, `Server listening at ${url}${modeText}`);
});
server.on('error', onError);
/**
* Normalize a port into a number, string, or false.
* @param val - Port string value
* @returns A number, string or false
*/
function normalizePort(val: string): string | number | boolean {
const port = Number.parseInt(val, 10);
if (Number.isNaN(port)) return val; // named pipe
if (port >= 0) return port; // port number
return false;
}
/**
* Event listener for HTTP server "error" event.
* @param error - Error event
* - syscall - The name of the system call that failed.
* - code - The specific error code (such as EADDRINUSE).
*/
function onError(error: Error & { syscall?: string; code: string }): void {
if (error.syscall !== 'listen') throw error;
// Handle specific listen errors with friendly messages
const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
switch (error.code) {
case 'EACCES':
log.fatal(`${bind} requires elevated privileges`);
shutdown('SIGABRT');
break;
case 'EADDRINUSE':
log.fatal(`${bind} is already in use`);
shutdown('SIGABRT');
break;
default:
throw error;
}
}
/**
* Gracefully shuts down the server and exits the process.
*/
function cleanup(): void {
state.ready = false;
log.debug('Closing HTTP server');
server.close(() => {
log.debug('Closing database pool');
void shutdownDatabase(() => {
log.debug('Terminating active connections');
server.closeAllConnections();
log.info('Shutdown complete: exiting');
log.flush(() => process.exit(0));
});
});
}
/**
* Handles shutting down the server and exits the process.
* @see https://nodejs.org/api/http.html#servercloseallconnections
* @param signal - Received termination signal (such as, 'SIGINT', 'SIGTERM').
*/
function shutdown(signal: NodeJS.Signals): void {
if (state.shutdown) return;
state.shutdown = true;
log.fatal(`Shutdown initiated [${signal}]`);
cleanup();
setTimeout(() => {
log.fatal('Shutdown timed out: forcing exit');
log.flush(() => process.exit(1));
}, 8000); // 8 seconds - slightly less than default 10s in Docker
}
/**
* Initializes the server by checking database health and migration maintenance
* @throws If database health or migrations fail.
*/
async function startup(): Promise<void> {
if (state.authMode) {
if (!(await checkDatabaseHealth())) throw new Error('Database health check failed');
if (!(await checkDatabaseMigrations())) {
if (automigrate) {
if (!(await runMigrations())) throw new Error('Database auto-migrations failed');
else if (!(await runSeeds())) throw new Error('Database auto-seeding failed');
} else throw new Error('Database migration check failed');
}
state.ready = true;
}
}
/**
* Validates the configuration settings and sets the server's auth mode
* @throws If configuration settings are invalid or missing.
*/
async function validateConfig(): Promise<void> {
const authMode = process.env.AUTH_MODE?.trim().toLowerCase();
if (!authMode) throw new Error('AUTH_MODE must be explicitly set');
if (authMode !== 'authn' && authMode !== 'authz' && authMode !== 'none') {
throw new Error(`Invalid AUTH_MODE value: '${authMode}'`);
}
state.authMode = authMode;
if (authMode !== 'none' && !process.env.AUTH_ISSUER) {
throw new Error(`AUTH_MODE=${authMode} requires AUTH_ISSUER to be set`);
}
if (authMode !== 'none') await getJwksClient();
}