-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
104 lines (88 loc) · 2.72 KB
/
index.js
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
'use strict'
const fp = require('fastify-plugin')
const EventEmitter = require('node:events')
const pluginName = '@kit-p/fastify-tasks'
/**
* @param {import('fastify').FastifyInstance} fastify
* @returns {Promise<void>}
*/
async function fastifyTasks (fastify) {
let closing = false
const taskEvent = new EventEmitter()
/**
* @type {{ named: string[], unnamed: number }}
*/
const tasks = {
named: [],
unnamed: 0
}
/**
* @returns {boolean} - true if there is no any named or unnamed task
*/
function isTasksEmpty () {
return tasks.named.length + tasks.unnamed <= 0
}
/**
* @param {string} [name] - Task name to add, does not need to be unique
* @returns {void}
*/
function addTask (name) {
if (closing) {
throw new Error('Server is closing. Tasks must be added before sending reply.')
}
if (typeof name === 'string') {
tasks.named.push(name)
} else {
tasks.unnamed++
}
}
/**
* @param {string} [name] - Task name to remove
* @returns {void}
*/
function removeTask (name) {
if (typeof name === 'string') {
const taskIdx = tasks.named.indexOf(name)
if (taskIdx < 0) {
throw new Error(`Task with name "${name}" does not exist`)
}
tasks.named.splice(name, 1)
} else if (tasks.unnamed <= 0) {
throw new Error('There is no unamed task to delete')
} else {
tasks.unnamed--
}
taskEvent.emit('TaskRemoved', name)
}
fastify.decorate('tasks', {
add: addTask,
remove: removeTask
})
fastify.addHook('preClose', (done) => {
closing = true
if (isTasksEmpty()) {
fastify.log.info(`[${pluginName}] all tasks have completed, server can be closed`)
done()
return
}
taskEvent.on('TaskRemoved', (name) => {
if (isTasksEmpty()) {
fastify.log.info(`[${pluginName}] all tasks have completed, server can be closed`)
done()
return
}
fastify.log.info(`[${pluginName}] waiting for all tasks to complete before closing the server, remaining ${tasks.named.length} named tasks and ${tasks.unnamed} unnamed tasks.`)
if (typeof name === 'string' && tasks.named.length > 0) {
fastify.log.debug(`[${pluginName}] remaining named tasks are ${JSON.stringify(tasks.named)}`)
}
})
fastify.log.info(`[${pluginName}] waiting for all tasks to complete before closing the server, remaining ${tasks.named.length} named tasks and ${tasks.unnamed} unnamed tasks.`)
fastify.log.debug(`[${pluginName}] remaining named tasks are ${JSON.stringify(tasks.named)}`)
})
}
module.exports = fp(fastifyTasks, {
fastify: '5.x',
name: pluginName
})
module.exports.default = fastifyTasks
module.exports.fastifyTasks = fastifyTasks