gracefully quit after CLI window is closed

Massimo Melina committed May 1, 2022 at 16:13 UTC c614ef6c871fd840e3ec20bcaba8323d06263066
4 files changed +19 -11
server/src/index.ts
+7 -1
@@ -5,7 +5,7 @@ import mount from 'koa-mount'
5 import { apiMiddleware } from './apiMiddleware'
6 import { API_URI, DEV } from './const'
7 import { frontEndApis } from './frontEndApis'
8 -import { log } from './log'
8 +import { debugLog, log } from './log'
9 import { pluginsMiddleware } from './plugins'
10 import { throttler } from './throttler'
11 import { headRequests, gzipper, sessions, serveGuiAndSharedFiles, someSecurity, prepareState } from './middlewares'
@@ -14,6 +14,7 @@ import { adminApis } from './adminApis'
14 import { defineConfig } from './config'
15 import { ok } from 'assert'
16 import _ from 'lodash'
17 +import { onProcessExit } from './misc'
18
19 ok(_.intersection(Object.keys(frontEndApis), Object.keys(adminApis)).length === 0) // they share same endpoints
20
@@ -47,3 +48,8 @@ defineConfig('proxies', 0).sub(n => {
48 app.proxy = n > 0
49 app.maxIpsCount = n
50 })
51 +
52 +onProcessExit(sig => {
53 + debugLog('exit by', sig)
54 + setTimeout(()=> process.exit(0), 1000) // 1-second grace period
55 +})
server/src/log.ts
+10 -6
@@ -104,13 +104,17 @@ function doubleDigit(n: number) {
104
105 { // dump console.error to file
106 const was = console.error
107 - let log: WriteStream
107 console.error = function(...args: any[]) {
108 was.apply(this, args)
110 - if (!log || !existsSync(log.path))
111 - log = createWriteStream('debug.log', { flags: 'a' })
112 - const params = args.map(x =>
113 - typeof x === 'string' ? x : JSON.stringify(x)).join(' ')
114 - log.write(new Date().toJSON() + ': ' + params + '\n')
109 + debugLog(...args)
110 }
111 }
112 +
113 +let debugLogFile: WriteStream
114 +export function debugLog(...args: any[]) {
115 + if (!debugLogFile || !existsSync(debugLogFile.path))
116 + debugLogFile = createWriteStream('debug.log', { flags: 'a' })
117 + const params = args.map(x =>
118 + typeof x === 'string' ? x : JSON.stringify(x)).join(' ')
119 + debugLogFile.write(new Date().toJSON() + ': ' + params + '\n')
120 +}
server/src/misc.ts
+1 -1
@@ -105,7 +105,7 @@ export function randomId(len = 10) {
105 }
106
107 export function onProcessExit(cb: (signal:string)=>void) {
108 - onFirstEvent(process, ['exit', 'SIGQUIT', 'SIGTERM', 'SIGINT'], cb)
108 + onFirstEvent(process, ['exit', 'SIGQUIT', 'SIGTERM', 'SIGINT', 'SIGHUP'], cb)
109 }
110
111 export function onFirstEvent(emitter:EventEmitter, events: string[], cb: (...args:any[])=> void) {
server/src/plugins.ts
+1 -3
@@ -246,9 +246,7 @@ function deleteModule(id: string) {
246 }
247 }
248
249 -onProcessExit(sig => {
249 +onProcessExit(() => {
250 for (const pl of Object.values(plugins))
251 pl.unload()
252 - if (sig === 'SIGINT') // ctrl+c
253 - setTimeout(()=> process.exit(0))
252 })