-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.ts
77 lines (67 loc) · 2.37 KB
/
server.ts
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
const primaryProcInfo = { name: '#', deployedAt: new Date(), pid: process.pid }
await import('reflect-metadata')
const { promises:{readFile, writeFile} } = await import('fs')
const { default: cluster } = await import('cluster')
const { default: os } = await import('os')
await import('dotenv/config')
const { logger } = await import('./src/utils/logger.js')
if (cluster.isPrimary) logger.procInfo = primaryProcInfo
if (cluster.isWorker) {
const forkList = JSON.parse(await readFile('.app-init.json', 'utf8'))
logger.procInfo = forkList.find(f => f.pid === process.pid)
}
const { expand, isDevEnv, genUniqTimestamp } = await import('./src/utils/basic.js')
const { sendDevMail } = await import('./src/utils/mail.js')
// Catch all errors, and send to DevMail.
// - unhandled errors
// - unhandled unawaited promise rejections
process.on('uncaughtException', error => sendDevMail(error))
process.on('unhandledRejection', (reason, promise) => sendDevMail({ reason, promise }))
if (cluster.isPrimary) {
// eslint-disable-next-line no-var
var forkList: any = []
const cpus = isDevEnv()? 1: os.cpus().length
logger.app(`Deploying ${cpus} forks.`)
for (let i = 0; i < cpus; i++) {
const worker = cluster.fork()
addForkRecord(worker.process.pid)
}
await writeFile(`.app-init.json`, JSON.stringify(forkList))
cluster.on('online', worker => {
const { pid } = worker.process
logger.app(`Fork ${pid} is online.`)
})
cluster.on('exit', (worker, c, s) => {
const pid = worker.process.pid
logger.app(`Fork ${pid} exited. Code: ${c}. Signal: ${s}. Deploying new fork.`)
cluster.fork()
})
}
if (cluster.isWorker) {
// Each is a fork
const {
env: { APP_PORT },
} = process
const { app } = await import('./app.js')
const port = APP_PORT || 3000
app.listen(port, () => logger.app(`Listening at PORT ${port}.`))
}
/**
* Stores app instance information,
* and assigns single alphabet names.
*/
function addForkRecord (pid) {
//const {forkList} = app.locals
const _forkData = { pid, deployedAt: new Date() }
if (!forkList.length) {
const forkData = { name: 'A', ..._forkData }
forkList.push(forkData)
return
}
const forkNames: any[] = forkList.map(fork => fork.name)
const lastNameCodepoint = forkNames[forkNames.length - 1].codePointAt(0)
const nextName = String.fromCodePoint(lastNameCodepoint + 1)
const forkData = { name: nextName, ..._forkData }
forkList.push(forkData)
}
export {}