@contember/engine-http 2.1.0-rc.3 → 2.1.0-rc.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/development/src/application/application.cjs +101 -19
- package/dist/development/src/application/application.cjs.map +1 -1
- package/dist/development/src/application/application.js +98 -16
- package/dist/development/src/application/application.js.map +1 -1
- package/dist/development/src/config/configSchema.cjs +3 -1
- package/dist/development/src/config/configSchema.cjs.map +1 -1
- package/dist/development/src/config/configSchema.js +3 -1
- package/dist/development/src/config/configSchema.js.map +1 -1
- package/dist/development/src/config/configTemplate.cjs +1 -0
- package/dist/development/src/config/configTemplate.cjs.map +1 -1
- package/dist/development/src/config/configTemplate.js +1 -0
- package/dist/development/src/config/configTemplate.js.map +1 -1
- package/dist/development/src/project/ProjectContainer.cjs +12 -8
- package/dist/development/src/project/ProjectContainer.cjs.map +1 -1
- package/dist/development/src/project/ProjectContainer.js +12 -8
- package/dist/development/src/project/ProjectContainer.js.map +1 -1
- package/dist/development/src/projectGroup/ProjectGroupContainer.cjs +12 -8
- package/dist/development/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
- package/dist/development/src/projectGroup/ProjectGroupContainer.js +12 -8
- package/dist/development/src/projectGroup/ProjectGroupContainer.js.map +1 -1
- package/dist/development/src/utils/serverTermination.cjs +5 -1
- package/dist/development/src/utils/serverTermination.cjs.map +1 -1
- package/dist/development/src/utils/serverTermination.js +5 -1
- package/dist/development/src/utils/serverTermination.js.map +1 -1
- package/dist/production/src/application/application.cjs +101 -19
- package/dist/production/src/application/application.cjs.map +1 -1
- package/dist/production/src/application/application.js +98 -16
- package/dist/production/src/application/application.js.map +1 -1
- package/dist/production/src/config/configSchema.cjs +3 -1
- package/dist/production/src/config/configSchema.cjs.map +1 -1
- package/dist/production/src/config/configSchema.js +3 -1
- package/dist/production/src/config/configSchema.js.map +1 -1
- package/dist/production/src/config/configTemplate.cjs +1 -0
- package/dist/production/src/config/configTemplate.cjs.map +1 -1
- package/dist/production/src/config/configTemplate.js +1 -0
- package/dist/production/src/config/configTemplate.js.map +1 -1
- package/dist/production/src/project/ProjectContainer.cjs +12 -8
- package/dist/production/src/project/ProjectContainer.cjs.map +1 -1
- package/dist/production/src/project/ProjectContainer.js +12 -8
- package/dist/production/src/project/ProjectContainer.js.map +1 -1
- package/dist/production/src/projectGroup/ProjectGroupContainer.cjs +12 -8
- package/dist/production/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
- package/dist/production/src/projectGroup/ProjectGroupContainer.js +12 -8
- package/dist/production/src/projectGroup/ProjectGroupContainer.js.map +1 -1
- package/dist/production/src/utils/serverTermination.cjs +5 -1
- package/dist/production/src/utils/serverTermination.cjs.map +1 -1
- package/dist/production/src/utils/serverTermination.js +5 -1
- package/dist/production/src/utils/serverTermination.js.map +1 -1
- package/dist/tests/cases/unit/applicationShutdown.test.d.ts +2 -0
- package/dist/tests/cases/unit/applicationShutdown.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/serverConfig.test.d.ts +2 -0
- package/dist/tests/cases/unit/serverConfig.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/serverTermination.fixture.d.ts +2 -0
- package/dist/tests/cases/unit/serverTermination.fixture.d.ts.map +1 -0
- package/dist/tests/cases/unit/serverTermination.test.d.ts +2 -0
- package/dist/tests/cases/unit/serverTermination.test.d.ts.map +1 -0
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/MasterContainer.d.ts +1 -0
- package/dist/types/MasterContainer.d.ts.map +1 -1
- package/dist/types/application/application.d.ts +2 -0
- package/dist/types/application/application.d.ts.map +1 -1
- package/dist/types/config/configSchema.d.ts +2 -0
- package/dist/types/config/configSchema.d.ts.map +1 -1
- package/dist/types/config/configTemplate.d.ts.map +1 -1
- package/dist/types/project/ProjectContainer.d.ts.map +1 -1
- package/dist/types/projectGroup/ProjectGroupContainer.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/dist/types/utils/serverTermination.d.ts +9 -1
- package/dist/types/utils/serverTermination.d.ts.map +1 -1
- package/package.json +15 -15
- package/src/application/application.ts +100 -14
- package/src/config/configSchema.ts +2 -0
- package/src/config/configTemplate.ts +1 -0
- package/src/project/ProjectContainer.ts +11 -7
- package/src/projectGroup/ProjectGroupContainer.ts +11 -7
- package/src/utils/serverTermination.ts +19 -1
- package/tests/cases/unit/applicationShutdown.test.ts +149 -0
- package/tests/cases/unit/serverConfig.test.ts +17 -0
- package/tests/cases/unit/serverTermination.fixture.ts +13 -0
- package/tests/cases/unit/serverTermination.test.ts +49 -0
|
@@ -8,6 +8,14 @@ export type TerminationJob = (args: {
|
|
|
8
8
|
signal: keyof typeof signals;
|
|
9
9
|
code: number;
|
|
10
10
|
}) => Promise<void>;
|
|
11
|
-
export
|
|
11
|
+
export interface ProcessTerminationOptions {
|
|
12
|
+
/**
|
|
13
|
+
* How long the process keeps serving after SIGTERM before the jobs run. An orchestrator stops routing to
|
|
14
|
+
* a process only some time after signalling it, so draining at once refuses what is still on its way.
|
|
15
|
+
* SIGINT and SIGHUP never wait.
|
|
16
|
+
*/
|
|
17
|
+
readonly sigtermDelayMs?: number;
|
|
18
|
+
}
|
|
19
|
+
export declare const listenOnProcessTermination: (jobs: TerminationJob[], logger: Logger, { sigtermDelayMs }?: ProcessTerminationOptions) => void;
|
|
12
20
|
export {};
|
|
13
21
|
//# sourceMappingURL=serverTermination.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serverTermination.d.ts","sourceRoot":"","sources":["../../../src/utils/serverTermination.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAA;AAE1C,QAAA,MAAM,OAAO;;;;CAIZ,CAAA;AACD,MAAM,MAAM,cAAc,GAAG,CAAC,IAAI,EAAE;IAAE,MAAM,EAAE,MAAM,OAAO,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;
|
|
1
|
+
{"version":3,"file":"serverTermination.d.ts","sourceRoot":"","sources":["../../../src/utils/serverTermination.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAA;AAE1C,QAAA,MAAM,OAAO;;;;CAIZ,CAAA;AACD,MAAM,MAAM,cAAc,GAAG,CAAC,IAAI,EAAE;IAAE,MAAM,EAAE,MAAM,OAAO,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;AAEpG,MAAM,WAAW,yBAAyB;IACzC;;;;OAIG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAA;CAChC;AAED,eAAO,MAAM,0BAA0B,GACtC,MAAM,cAAc,EAAE,EACtB,QAAQ,MAAM,EACd,qBAAwB,yBAA8B,SActD,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@contember/engine-http",
|
|
3
|
-
"version": "2.1.0-rc.
|
|
3
|
+
"version": "2.1.0-rc.5",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"main": "./dist/production/index.js",
|
|
6
6
|
"typings": "./dist/types/index.d.ts",
|
|
@@ -26,20 +26,20 @@
|
|
|
26
26
|
}
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@contember/config-loader": "2.1.0-rc.
|
|
30
|
-
"@contember/database": "2.1.0-rc.
|
|
31
|
-
"@contember/database-migrations": "2.1.0-rc.
|
|
32
|
-
"@contember/dic": "2.1.0-rc.
|
|
33
|
-
"@contember/engine-common": "2.1.0-rc.
|
|
34
|
-
"@contember/engine-content-api": "2.1.0-rc.
|
|
35
|
-
"@contember/engine-system-api": "2.1.0-rc.
|
|
36
|
-
"@contember/engine-tenant-api": "2.1.0-rc.
|
|
37
|
-
"@contember/graphql-utils": "2.1.0-rc.
|
|
38
|
-
"@contember/logger": "2.1.0-rc.
|
|
39
|
-
"@contember/schema": "2.1.0-rc.
|
|
40
|
-
"@contember/schema-migrations": "2.1.0-rc.
|
|
41
|
-
"@contember/schema-utils": "2.1.0-rc.
|
|
42
|
-
"@contember/typesafe": "2.1.0-rc.
|
|
29
|
+
"@contember/config-loader": "2.1.0-rc.5",
|
|
30
|
+
"@contember/database": "2.1.0-rc.5",
|
|
31
|
+
"@contember/database-migrations": "2.1.0-rc.5",
|
|
32
|
+
"@contember/dic": "2.1.0-rc.5",
|
|
33
|
+
"@contember/engine-common": "2.1.0-rc.5",
|
|
34
|
+
"@contember/engine-content-api": "2.1.0-rc.5",
|
|
35
|
+
"@contember/engine-system-api": "2.1.0-rc.5",
|
|
36
|
+
"@contember/engine-tenant-api": "2.1.0-rc.5",
|
|
37
|
+
"@contember/graphql-utils": "2.1.0-rc.5",
|
|
38
|
+
"@contember/logger": "2.1.0-rc.5",
|
|
39
|
+
"@contember/schema": "2.1.0-rc.5",
|
|
40
|
+
"@contember/schema-migrations": "2.1.0-rc.5",
|
|
41
|
+
"@contember/schema-utils": "2.1.0-rc.5",
|
|
42
|
+
"@contember/typesafe": "2.1.0-rc.5",
|
|
43
43
|
"@graphql-tools/merge": "^9.1.7",
|
|
44
44
|
"@graphql-tools/schema": "^10.0.31",
|
|
45
45
|
"@koa/cors": "^5.0.0",
|
|
@@ -18,6 +18,8 @@ import { cpuUsage, memoryUsage } from 'node:process'
|
|
|
18
18
|
import { performance } from 'node:perf_hooks'
|
|
19
19
|
import { getClientIP } from '../utils/remoteAddress'
|
|
20
20
|
|
|
21
|
+
const websocketCloseTimeoutMs = 5_000
|
|
22
|
+
|
|
21
23
|
type Route<C> = { match: RequestMatcher; controller: C; module: string }
|
|
22
24
|
export class Application {
|
|
23
25
|
private middlewares: KoaMiddleware<any>[] = []
|
|
@@ -70,6 +72,15 @@ export class Application {
|
|
|
70
72
|
async listen(): Promise<RunningApplication> {
|
|
71
73
|
const koa = new Koa()
|
|
72
74
|
const wss = new WebSocketServer({ noServer: true })
|
|
75
|
+
let closing = false
|
|
76
|
+
koa.use(async (ctx, next) => {
|
|
77
|
+
if (closing) {
|
|
78
|
+
ctx.status = 503
|
|
79
|
+
ctx.set('Connection', 'close')
|
|
80
|
+
return
|
|
81
|
+
}
|
|
82
|
+
await next()
|
|
83
|
+
})
|
|
73
84
|
for (const middleware of this.middlewares) {
|
|
74
85
|
koa.use(middleware)
|
|
75
86
|
}
|
|
@@ -87,11 +98,36 @@ export class Application {
|
|
|
87
98
|
await this.handleHttpRequest(ctx)
|
|
88
99
|
})
|
|
89
100
|
|
|
90
|
-
const
|
|
101
|
+
const activeHttpRequests = new Set<Promise<void>>()
|
|
102
|
+
const handleHttpRequest = koa.callback()
|
|
103
|
+
const server = http.createServer((request, response) => {
|
|
104
|
+
if (closing) {
|
|
105
|
+
handleHttpRequest(request, response)
|
|
106
|
+
return
|
|
107
|
+
}
|
|
108
|
+
let resolveRequest = () => {}
|
|
109
|
+
const completed = new Promise<void>(resolve => {
|
|
110
|
+
resolveRequest = resolve
|
|
111
|
+
})
|
|
112
|
+
activeHttpRequests.add(completed)
|
|
113
|
+
const complete = () => {
|
|
114
|
+
response.off('finish', complete)
|
|
115
|
+
response.off('close', complete)
|
|
116
|
+
activeHttpRequests.delete(completed)
|
|
117
|
+
resolveRequest()
|
|
118
|
+
}
|
|
119
|
+
response.once('finish', complete)
|
|
120
|
+
response.once('close', complete)
|
|
121
|
+
handleHttpRequest(request, response)
|
|
122
|
+
})
|
|
91
123
|
const abortController = new AbortController()
|
|
92
124
|
|
|
93
125
|
const wsRequests: (Promise<void>)[] = []
|
|
94
126
|
server.on('upgrade', (req, socket, head) => {
|
|
127
|
+
if (closing) {
|
|
128
|
+
this.sendRawHttpResponse(socket, new HttpErrorResponse(503, 'Server is shutting down'))
|
|
129
|
+
return
|
|
130
|
+
}
|
|
95
131
|
wsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head))
|
|
96
132
|
})
|
|
97
133
|
await new Promise<void>(resolve => {
|
|
@@ -101,9 +137,25 @@ export class Application {
|
|
|
101
137
|
return {
|
|
102
138
|
server,
|
|
103
139
|
close: async () => {
|
|
140
|
+
closing = true
|
|
104
141
|
abortController.abort()
|
|
105
|
-
await Promise.all(wsRequests)
|
|
106
|
-
|
|
142
|
+
await Promise.all([...wsRequests, ...activeHttpRequests])
|
|
143
|
+
if (process.versions.bun !== undefined) {
|
|
144
|
+
// Bun does not finish server.close() after a WebSocket upgrade unless all connections are closed first.
|
|
145
|
+
server.closeAllConnections()
|
|
146
|
+
} else {
|
|
147
|
+
server.closeIdleConnections()
|
|
148
|
+
}
|
|
149
|
+
if (server.listening) {
|
|
150
|
+
await new Promise<void>(resolve =>
|
|
151
|
+
server.close(error => {
|
|
152
|
+
if (error) {
|
|
153
|
+
this.logger.error(error)
|
|
154
|
+
}
|
|
155
|
+
resolve()
|
|
156
|
+
})
|
|
157
|
+
)
|
|
158
|
+
}
|
|
107
159
|
},
|
|
108
160
|
}
|
|
109
161
|
}
|
|
@@ -139,12 +191,25 @@ export class Application {
|
|
|
139
191
|
user: authResult?.identityId,
|
|
140
192
|
})
|
|
141
193
|
|
|
194
|
+
if (abortSignal.aborted) {
|
|
195
|
+
throw new HttpErrorResponse(503, 'Server is shutting down')
|
|
196
|
+
}
|
|
142
197
|
const ws = await new Promise<WebSocket>(resolve =>
|
|
143
198
|
wss.handleUpgrade(req, socket, head, (ws, request) => {
|
|
144
199
|
resolve(ws)
|
|
145
200
|
})
|
|
146
201
|
)
|
|
147
202
|
const wsEstablished = performance.now()
|
|
203
|
+
ws.on('error', e => {
|
|
204
|
+
requestLogger.error(e, {
|
|
205
|
+
websocketOpenMs: performance.now() - wsEstablished,
|
|
206
|
+
})
|
|
207
|
+
})
|
|
208
|
+
if (abortSignal.aborted) {
|
|
209
|
+
await this.closeWebsocket(ws)
|
|
210
|
+
return
|
|
211
|
+
}
|
|
212
|
+
const pendingWork: Promise<void>[] = []
|
|
148
213
|
webSocketContext = {
|
|
149
214
|
ws,
|
|
150
215
|
abortSignal,
|
|
@@ -156,23 +221,25 @@ export class Application {
|
|
|
156
221
|
authResult,
|
|
157
222
|
params: matchedRequest.params,
|
|
158
223
|
projectGroup: groupContainer,
|
|
224
|
+
waitUntil: promise => pendingWork.push(promise),
|
|
159
225
|
}
|
|
160
226
|
await matchedRequest.controller(webSocketContext)
|
|
227
|
+
if (abortSignal.aborted && ws.readyState === WebSocket.OPEN) {
|
|
228
|
+
ws.close(1012)
|
|
229
|
+
}
|
|
161
230
|
requestLogger.debug('Websocket connection established')
|
|
162
|
-
ws.on('error', e => {
|
|
163
|
-
requestLogger.error(e, {
|
|
164
|
-
websocketOpenMs: performance.now() - wsEstablished,
|
|
165
|
-
})
|
|
166
|
-
})
|
|
167
231
|
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
232
|
+
if (ws.readyState !== WebSocket.CLOSED) {
|
|
233
|
+
await new Promise<void>(resolve => {
|
|
234
|
+
ws.on('close', () => {
|
|
235
|
+
requestLogger.debug('Websocket connection closed', {
|
|
236
|
+
websocketOpenMs: performance.now() - wsEstablished,
|
|
237
|
+
})
|
|
238
|
+
resolve()
|
|
172
239
|
})
|
|
173
|
-
resolve()
|
|
174
240
|
})
|
|
175
|
-
}
|
|
241
|
+
}
|
|
242
|
+
await Promise.allSettled(pendingWork)
|
|
176
243
|
} catch (e) {
|
|
177
244
|
if (e instanceof HttpResponse) {
|
|
178
245
|
this.sendRawHttpResponse(socket, e)
|
|
@@ -304,6 +371,24 @@ export class Application {
|
|
|
304
371
|
}
|
|
305
372
|
}
|
|
306
373
|
|
|
374
|
+
private async closeWebsocket(ws: WebSocket): Promise<void> {
|
|
375
|
+
if (ws.readyState === WebSocket.CLOSED) {
|
|
376
|
+
return
|
|
377
|
+
}
|
|
378
|
+
ws.close(1012) // Service Restart
|
|
379
|
+
await new Promise<void>(resolve => {
|
|
380
|
+
// ws only gives up on the close handshake after 30 s, which outlives a typical shutdown grace period
|
|
381
|
+
const timeout = setTimeout(() => {
|
|
382
|
+
ws.terminate()
|
|
383
|
+
resolve()
|
|
384
|
+
}, websocketCloseTimeoutMs)
|
|
385
|
+
ws.once('close', () => {
|
|
386
|
+
clearTimeout(timeout)
|
|
387
|
+
resolve()
|
|
388
|
+
})
|
|
389
|
+
})
|
|
390
|
+
}
|
|
391
|
+
|
|
307
392
|
private sendRawHttpResponse(socket: Duplex, response: HttpResponse) {
|
|
308
393
|
const headers: Record<string, string> = {
|
|
309
394
|
'Connection': 'close',
|
|
@@ -461,6 +546,7 @@ export type WebSocketContext =
|
|
|
461
546
|
& {
|
|
462
547
|
ws: WebSocket
|
|
463
548
|
abortSignal: AbortSignal
|
|
549
|
+
waitUntil(promise: Promise<void>): void
|
|
464
550
|
}
|
|
465
551
|
|
|
466
552
|
export type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void
|
|
@@ -147,6 +147,8 @@ export const serverConfigSchema = Typesafe.partial({
|
|
|
147
147
|
monitoringPort: Typesafe.number,
|
|
148
148
|
workerCount: Typesafe.union(Typesafe.number, Typesafe.string),
|
|
149
149
|
applicationWorker: Typesafe.string,
|
|
150
|
+
// How long the engine keeps serving after SIGTERM before it shuts down; unset means at once.
|
|
151
|
+
shutdownDelayMs: Typesafe.number,
|
|
150
152
|
})
|
|
151
153
|
|
|
152
154
|
export const stageConfig = Typesafe.record(
|
|
@@ -81,6 +81,7 @@ export const configTemplate: any = {
|
|
|
81
81
|
monitoringPort: '%?env.CONTEMBER_MONITORING_PORT::number%',
|
|
82
82
|
workerCount: '%?env.CONTEMBER_WORKER_COUNT::string%',
|
|
83
83
|
applicationWorker: '%?env.CONTEMBER_APPLICATION_WORKER::string%',
|
|
84
|
+
shutdownDelayMs: '%?env.CONTEMBER_SHUTDOWN_DELAY_MS::number%',
|
|
84
85
|
http: {
|
|
85
86
|
requestBodySize: '%?env.CONTEMBER_HTTP_REQUEST_BODY_SIZE::string%',
|
|
86
87
|
suppressAccessLog: '%?env.CONTEMBER_HTTP_SUPPRESS_ACCESS_LOG::string%',
|
|
@@ -88,14 +88,18 @@ export class ProjectContainerFactory {
|
|
|
88
88
|
if (!project.db.read) {
|
|
89
89
|
return connection
|
|
90
90
|
}
|
|
91
|
-
return Connection.create(
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
91
|
+
return Connection.create(
|
|
92
|
+
{
|
|
93
|
+
...project.db,
|
|
94
|
+
...project.db.read,
|
|
95
|
+
pool: {
|
|
96
|
+
...project.db.pool,
|
|
97
|
+
...project.db.read.pool,
|
|
98
|
+
},
|
|
97
99
|
},
|
|
98
|
-
|
|
100
|
+
err => logger.error(err),
|
|
101
|
+
{ retryStaleConnection: true },
|
|
102
|
+
)
|
|
99
103
|
})
|
|
100
104
|
.addService('contentSchemaResolver', () => new ContentSchemaResolver(this.schemaProvider))
|
|
101
105
|
.addService('systemSchemaName', ({ project }) => project.db.systemSchema ?? 'system')
|
|
@@ -76,14 +76,18 @@ export class ProjectGroupContainerFactory {
|
|
|
76
76
|
if (!tenantDbCredentials.read) {
|
|
77
77
|
return tenantConnection
|
|
78
78
|
}
|
|
79
|
-
return Connection.create(
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
79
|
+
return Connection.create(
|
|
80
|
+
{
|
|
81
|
+
...tenantDbCredentials,
|
|
82
|
+
...tenantDbCredentials.read,
|
|
83
|
+
pool: {
|
|
84
|
+
...tenantDbCredentials.pool,
|
|
85
|
+
...tenantDbCredentials.read.pool,
|
|
86
|
+
},
|
|
85
87
|
},
|
|
86
|
-
|
|
88
|
+
err => logger.error(err),
|
|
89
|
+
{ retryStaleConnection: true },
|
|
90
|
+
)
|
|
87
91
|
})
|
|
88
92
|
.addService('projectSchemaResolver', () => new ProjectSchemaResolverProxy())
|
|
89
93
|
.addService('projectInitializer', () => new ProjectInitializerProxy())
|
|
@@ -7,9 +7,27 @@ const signals = {
|
|
|
7
7
|
SIGTERM: 15,
|
|
8
8
|
}
|
|
9
9
|
export type TerminationJob = (args: { signal: keyof typeof signals; code: number }) => Promise<void>
|
|
10
|
-
|
|
10
|
+
|
|
11
|
+
export interface ProcessTerminationOptions {
|
|
12
|
+
/**
|
|
13
|
+
* How long the process keeps serving after SIGTERM before the jobs run. An orchestrator stops routing to
|
|
14
|
+
* a process only some time after signalling it, so draining at once refuses what is still on its way.
|
|
15
|
+
* SIGINT and SIGHUP never wait.
|
|
16
|
+
*/
|
|
17
|
+
readonly sigtermDelayMs?: number
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const listenOnProcessTermination = (
|
|
21
|
+
jobs: TerminationJob[],
|
|
22
|
+
logger: Logger,
|
|
23
|
+
{ sigtermDelayMs = 0 }: ProcessTerminationOptions = {},
|
|
24
|
+
) => {
|
|
11
25
|
for (const [signal, code] of Object.entries(signals)) {
|
|
12
26
|
process.on(signal, async () => {
|
|
27
|
+
if (signal === 'SIGTERM' && sigtermDelayMs > 0) {
|
|
28
|
+
logger.info(`Process ${process.pid} received a SIGTERM signal, serving for another ${sigtermDelayMs} ms before terminating`)
|
|
29
|
+
await new Promise(resolve => setTimeout(resolve, sigtermDelayMs))
|
|
30
|
+
}
|
|
13
31
|
logger.info(`Process ${process.pid} received a ${signal} signal, executing ${jobs.length} termination jobs`)
|
|
14
32
|
await Promise.allSettled(jobs.map(it => it({ signal: signal as keyof typeof signals, code })))
|
|
15
33
|
logger.info(cluster.isMaster ? `All terminated, exiting` : 'All terminated, exiting a worker')
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { VerifyResult } from '@contember/engine-tenant-api'
|
|
3
|
+
import { createLogger, TestLoggerHandler } from '@contember/logger'
|
|
4
|
+
import { Readable } from 'node:stream'
|
|
5
|
+
import { WebSocket } from 'ws'
|
|
6
|
+
import { Application } from '../../../src/application/application'
|
|
7
|
+
import { Authenticator } from '../../../src/common/Authorizator'
|
|
8
|
+
import { serverConfigSchema } from '../../../src/config/configSchema'
|
|
9
|
+
import { ProjectGroupContainer } from '../../../src/projectGroup/ProjectGroupContainer'
|
|
10
|
+
import { ProjectGroupResolver } from '../../../src/projectGroup/ProjectGroupResolver'
|
|
11
|
+
import { createMock } from '../../utils'
|
|
12
|
+
|
|
13
|
+
const unavailable = (): never => {
|
|
14
|
+
throw new Error('This service is not available in the application shutdown test')
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const createTestApplication = (
|
|
18
|
+
authenticate: Authenticator['authenticate'] = async () => new VerifyResult('identity', 'api-key', ['member'], null),
|
|
19
|
+
) => {
|
|
20
|
+
const logger = createLogger(new TestLoggerHandler())
|
|
21
|
+
const authenticator = createMock<Authenticator>({ authenticate })
|
|
22
|
+
const projectGroup: ProjectGroupContainer = {
|
|
23
|
+
slug: undefined,
|
|
24
|
+
logger,
|
|
25
|
+
authenticator,
|
|
26
|
+
get projectMembershipResolver() {
|
|
27
|
+
return unavailable()
|
|
28
|
+
},
|
|
29
|
+
get projectContainerResolver() {
|
|
30
|
+
return unavailable()
|
|
31
|
+
},
|
|
32
|
+
get projectSchemaResolver() {
|
|
33
|
+
return unavailable()
|
|
34
|
+
},
|
|
35
|
+
get projectInitializer() {
|
|
36
|
+
return unavailable()
|
|
37
|
+
},
|
|
38
|
+
get tenantContainer() {
|
|
39
|
+
return unavailable()
|
|
40
|
+
},
|
|
41
|
+
get tenantGraphQLHandler() {
|
|
42
|
+
return unavailable()
|
|
43
|
+
},
|
|
44
|
+
get systemContainer() {
|
|
45
|
+
return unavailable()
|
|
46
|
+
},
|
|
47
|
+
get systemGraphQLHandler() {
|
|
48
|
+
return unavailable()
|
|
49
|
+
},
|
|
50
|
+
}
|
|
51
|
+
const projectGroupResolver = createMock<ProjectGroupResolver>({
|
|
52
|
+
resolveContainer: async () => projectGroup,
|
|
53
|
+
})
|
|
54
|
+
return new Application(projectGroupResolver, serverConfigSchema({ port: 0 }), false, undefined, logger)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
test('waits for an active HTTP stream when shutting down after a WebSocket upgrade', async () => {
|
|
58
|
+
const application = createTestApplication()
|
|
59
|
+
let releaseStream = () => {}
|
|
60
|
+
const streamReleased = new Promise<void>(resolve => {
|
|
61
|
+
releaseStream = resolve
|
|
62
|
+
})
|
|
63
|
+
application.addRoute('transfer', '/stream', context => {
|
|
64
|
+
context.koa.status = 200
|
|
65
|
+
context.koa.body = Readable.from((async function*() {
|
|
66
|
+
yield 'first'
|
|
67
|
+
await streamReleased
|
|
68
|
+
yield 'second'
|
|
69
|
+
})())
|
|
70
|
+
})
|
|
71
|
+
let resolveWebsocketCleanup = () => {}
|
|
72
|
+
const websocketCleanup = new Promise<void>(resolve => {
|
|
73
|
+
resolveWebsocketCleanup = resolve
|
|
74
|
+
})
|
|
75
|
+
application.addWebsocketRoute('actions', '/actions', ({ ws, abortSignal }) => {
|
|
76
|
+
abortSignal.addEventListener('abort', () => ws.close(1012), { once: true })
|
|
77
|
+
ws.once('close', resolveWebsocketCleanup)
|
|
78
|
+
})
|
|
79
|
+
const running = await application.listen()
|
|
80
|
+
const address = running.server.address()
|
|
81
|
+
if (address === null || typeof address === 'string') {
|
|
82
|
+
await running.close()
|
|
83
|
+
throw new Error('The test server did not bind to a TCP port')
|
|
84
|
+
}
|
|
85
|
+
const client = new WebSocket(`ws://127.0.0.1:${address.port}/actions`)
|
|
86
|
+
const opened = new Promise<void>((resolve, reject) => {
|
|
87
|
+
client.once('open', () => resolve())
|
|
88
|
+
client.once('error', reject)
|
|
89
|
+
})
|
|
90
|
+
const clientClosed = new Promise<number>(resolve => client.once('close', code => resolve(code)))
|
|
91
|
+
let shutdown: Promise<void> | undefined
|
|
92
|
+
try {
|
|
93
|
+
await opened
|
|
94
|
+
const response = await fetch(`http://127.0.0.1:${address.port}/stream`)
|
|
95
|
+
const responseBody = response.text()
|
|
96
|
+
let shutdownFinished = false
|
|
97
|
+
shutdown = running.close().then(() => {
|
|
98
|
+
shutdownFinished = true
|
|
99
|
+
})
|
|
100
|
+
await websocketCleanup
|
|
101
|
+
await new Promise<void>(resolve => setImmediate(resolve))
|
|
102
|
+
expect(shutdownFinished).toBe(false)
|
|
103
|
+
releaseStream()
|
|
104
|
+
expect(await responseBody).toBe('firstsecond')
|
|
105
|
+
await shutdown
|
|
106
|
+
expect(await clientClosed).toBe(1012)
|
|
107
|
+
} finally {
|
|
108
|
+
releaseStream()
|
|
109
|
+
shutdown ??= running.close()
|
|
110
|
+
await shutdown
|
|
111
|
+
client.terminate()
|
|
112
|
+
}
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
test('rejects a WebSocket upgrade whose authentication finishes during shutdown', async () => {
|
|
116
|
+
let releaseAuthentication = () => {}
|
|
117
|
+
const authenticationReleased = new Promise<void>(resolve => {
|
|
118
|
+
releaseAuthentication = resolve
|
|
119
|
+
})
|
|
120
|
+
let authenticationStarted = () => {}
|
|
121
|
+
const started = new Promise<void>(resolve => {
|
|
122
|
+
authenticationStarted = resolve
|
|
123
|
+
})
|
|
124
|
+
const application = createTestApplication(async () => {
|
|
125
|
+
authenticationStarted()
|
|
126
|
+
await authenticationReleased
|
|
127
|
+
return new VerifyResult('identity', 'api-key', ['member'], null)
|
|
128
|
+
})
|
|
129
|
+
let controllerCalled = false
|
|
130
|
+
application.addWebsocketRoute('actions', '/actions', () => {
|
|
131
|
+
controllerCalled = true
|
|
132
|
+
})
|
|
133
|
+
const running = await application.listen()
|
|
134
|
+
const address = running.server.address()
|
|
135
|
+
if (address === null || typeof address === 'string') {
|
|
136
|
+
await running.close()
|
|
137
|
+
throw new Error('The test server did not bind to a TCP port')
|
|
138
|
+
}
|
|
139
|
+
const client = new WebSocket(`ws://127.0.0.1:${address.port}/actions`)
|
|
140
|
+
client.on('error', () => {})
|
|
141
|
+
const clientClosed = new Promise<void>(resolve => client.once('close', () => resolve()))
|
|
142
|
+
|
|
143
|
+
await started
|
|
144
|
+
const shutdown = running.close()
|
|
145
|
+
releaseAuthentication()
|
|
146
|
+
await shutdown
|
|
147
|
+
await clientClosed
|
|
148
|
+
expect(controllerCalled).toBe(false)
|
|
149
|
+
})
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { readConfig } from '../../../src/config/config'
|
|
3
|
+
|
|
4
|
+
test('shutdownDelayMs: read from CONTEMBER_SHUTDOWN_DELAY_MS', async () => {
|
|
5
|
+
process.env.CONTEMBER_SHUTDOWN_DELAY_MS = '5000'
|
|
6
|
+
try {
|
|
7
|
+
const { serverConfig } = await readConfig()
|
|
8
|
+
expect(serverConfig.shutdownDelayMs).toBe(5000)
|
|
9
|
+
} finally {
|
|
10
|
+
delete process.env.CONTEMBER_SHUTDOWN_DELAY_MS
|
|
11
|
+
}
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
test('shutdownDelayMs: undefined when the variable is unset', async () => {
|
|
15
|
+
const { serverConfig } = await readConfig()
|
|
16
|
+
expect(serverConfig.shutdownDelayMs).toBeUndefined()
|
|
17
|
+
})
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createLogger, TestLoggerHandler } from '@contember/logger'
|
|
2
|
+
import { listenOnProcessTermination } from '../../../src/utils/serverTermination'
|
|
3
|
+
|
|
4
|
+
// Driven by serverTermination.test.ts: prints READY once it listens for signals, JOBS once the jobs run.
|
|
5
|
+
listenOnProcessTermination(
|
|
6
|
+
[async () => {
|
|
7
|
+
console.log('JOBS')
|
|
8
|
+
}],
|
|
9
|
+
createLogger(new TestLoggerHandler()),
|
|
10
|
+
{ sigtermDelayMs: Number(process.argv[2]) },
|
|
11
|
+
)
|
|
12
|
+
setInterval(() => {}, 60_000)
|
|
13
|
+
console.log('READY')
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
|
|
4
|
+
const fixture = join(import.meta.dir, 'serverTermination.fixture.ts')
|
|
5
|
+
|
|
6
|
+
/** Starts the fixture, sends `signal` once it listens, and measures how long the termination jobs waited. */
|
|
7
|
+
const terminate = async (signal: 'SIGTERM' | 'SIGINT', sigtermDelayMs: number) => {
|
|
8
|
+
const proc = Bun.spawn(['bun', '--conditions=typescript', fixture, String(sigtermDelayMs)], { stdout: 'pipe', stderr: 'inherit' })
|
|
9
|
+
const reader = proc.stdout.getReader()
|
|
10
|
+
const decoder = new TextDecoder()
|
|
11
|
+
let output = ''
|
|
12
|
+
const waitFor = async (marker: string): Promise<number> => {
|
|
13
|
+
while (!output.includes(marker)) {
|
|
14
|
+
const { done, value } = await reader.read()
|
|
15
|
+
if (done) {
|
|
16
|
+
throw new Error(`The fixture exited before printing ${marker}: ${output}`)
|
|
17
|
+
}
|
|
18
|
+
output += decoder.decode(value)
|
|
19
|
+
}
|
|
20
|
+
return performance.now()
|
|
21
|
+
}
|
|
22
|
+
await waitFor('READY')
|
|
23
|
+
const signalledAt = performance.now()
|
|
24
|
+
proc.kill(signal)
|
|
25
|
+
const jobsRanAt = await waitFor('JOBS')
|
|
26
|
+
return { jobsWaitedMs: jobsRanAt - signalledAt, exitCode: await proc.exited }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
test('keeps serving for the configured delay after SIGTERM, then runs the jobs', async () => {
|
|
30
|
+
const { jobsWaitedMs, exitCode } = await terminate('SIGTERM', 600)
|
|
31
|
+
|
|
32
|
+
expect(jobsWaitedMs).toBeGreaterThanOrEqual(590)
|
|
33
|
+
expect(exitCode).toBe(143)
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
test('runs the jobs at once on SIGTERM when no delay is configured', async () => {
|
|
37
|
+
const { jobsWaitedMs, exitCode } = await terminate('SIGTERM', 0)
|
|
38
|
+
|
|
39
|
+
expect(jobsWaitedMs).toBeLessThan(400)
|
|
40
|
+
expect(exitCode).toBe(143)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
// Only the orchestrator's stop signal waits: an interactive Ctrl+C must not.
|
|
44
|
+
test('runs the jobs at once on SIGINT even when a delay is configured', async () => {
|
|
45
|
+
const { jobsWaitedMs, exitCode } = await terminate('SIGINT', 600)
|
|
46
|
+
|
|
47
|
+
expect(jobsWaitedMs).toBeLessThan(400)
|
|
48
|
+
expect(exitCode).toBe(130)
|
|
49
|
+
})
|