Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 4 additions & 15 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,10 @@ const cmd = require('yargs')
.argv

const hnd = require('./lib/worker.js')(cmd)
const createShutdownHandler = require('./lib/shutdown')

let shutdown = 0
process.on('SIGINT', () => {
if (shutdown) {
return
}
shutdown = 1

if (!hnd.active) {
return
}
console.log('BKW', process.title, 'shutting down')
hnd.stop(() => {
process.exit()
})
})
const shutdown = createShutdownHandler(hnd)
process.on('SIGINT', shutdown)
process.on('SIGTERM', shutdown)

module.exports = hnd
24 changes: 24 additions & 0 deletions lib/shutdown.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict'

function createShutdownHandler (hnd, exit = process.exit, log = console.log) {
let shutdown = 0

return () => {
if (shutdown) {
return
}
shutdown = 1

if (!hnd.active) {
exit(0)
return
}

log('BKW', process.title, 'shutting down')
hnd.stop(() => {
exit(0)
})
}
}

module.exports = createShutdownHandler
45 changes: 45 additions & 0 deletions test/unit.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const path = require('path')
const fs = require('fs')

const worker = require('../lib/worker')
const createShutdownHandler = require('../lib/shutdown')
const fixtureWorker = path.join(__dirname, 'fixtures', 'workers', 'dummy.js')

async function setupDir (t) {
Expand Down Expand Up @@ -103,3 +104,47 @@ test('config priority order', async (t) => {
t.is(wrk.conf.source, 'env-json')
})
})

test('shutdown handler', async (t) => {
await t.test('exits immediately when worker is not active', (t) => {
let exitCode = null
let stopCalled = false
const hnd = {
active: 0,
stop: () => {
stopCalled = true
}
}

const shutdown = createShutdownHandler(hnd, code => {
exitCode = code
}, () => {})

shutdown()

t.is(stopCalled, false)
t.is(exitCode, 0)
})

await t.test('stops active worker once before exiting', (t) => {
let exitCode = null
let stopCalls = 0
const hnd = {
active: 1,
stop: cb => {
stopCalls++
cb()
}
}

const shutdown = createShutdownHandler(hnd, code => {
exitCode = code
}, () => {})

shutdown()
shutdown()

t.is(stopCalls, 1)
t.is(exitCode, 0)
})
})