~mser/emote-server

ref: 1.2.0 emote-server/bin/www -rwxr-xr-x 1.9 KiB
671a8f4cMichael Serajnik Merge branch 'release/1.2.0' 9 months ago
                                                                                
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
#!/usr/bin/env node

const path = require('path')
const cluster = require('cluster')

require('dotenv').config({ path: path.resolve(__dirname, '../.env') })

const config = require('../src/config')
const service = require('../index.js')
const logger = require('../src/util/logger')

let shuttingDown = false

const shutDown = signal => {
  if (!cluster.isMaster) {
    return
  }

  shuttingDown = true

  logger.log('Emote server is shutting down…')

  let exitCode = 0

  const promises = []
  const workerIds = Object.keys(cluster.workers)

  for (const id of workerIds) {
    const worker = cluster.workers[id]

    promises.push(new Promise(resolve => {
      let resolved = false

      worker.once('exit', () => {
        if (resolved) {
          return
        }

        resolved = true

        resolve()
      })

      setTimeout(() => {
        if (resolved) {
          return
        }

        resolved = true

        logger.log('Could not close worker in time, killing it.', 'error')

        worker.kill(signal)

        exitCode = 1

        resolve()
      }, 4000)
    }))

    worker.send('shutdown')
    worker.disconnect()
  }

  Promise.all(promises).then(() => {
    process.exit(exitCode)
  })
}

;(async () => {
  if (cluster.isMaster) {
    logger.log('Emote server is starting…')

    const numberOfWorkers = config.numberOfWorkers > 1
      ? config.numberOfWorkers
      : 1

    for (let i = 0; i < numberOfWorkers; i++) {
      cluster.fork()
    }

    cluster.on('exit', worker => {
      if (!shuttingDown) {
        cluster.fork()
      }
    })

    logger.log('Emote server has started.')
  } else {
    await service.start(config.port)

    process.on('message', async message => {
      if (message === 'shutdown') {
        await service.close()
      }
    })
  }
})()

process.on('SIGTERM', () => {
  shutDown('SIGTERM')
})

process.on('SIGINT', () => {
  shutDown('SIGINT')
})