-
Notifications
You must be signed in to change notification settings - Fork 17
/
index.js
121 lines (98 loc) · 2.36 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import {format} from 'node:util';
import {setInterval} from 'node:timers';
import {createRequire} from 'node:module';
const require = createRequire(import.meta.url);
// @ts-ignore
const binding = require('./daemon.node');
let watchdog = null;
/** @type {number} */
export const LISTEN_FDS_START = binding.LISTEN_FDS_START;
/**
* @returns {0|1}
*/
export function booted() {
return binding.booted();
}
export function listenFDs() {
return Number(process.env.LISTEN_FDS ?? 0);
}
/**
* @typedef {object} Listener
* @property {number} fd
* @property {string} [name]
*/
export function listeners() {
const count = Number(process.env.LISTEN_FDS ?? 0);
const fdNames = (process.env.LISTEN_FDNAMES || '').split(':');
/** @type {Listener[]} */
const arr = new Array(count);
for (let i = 0; i < count; i++) {
arr[i] = {
fd: binding.LISTEN_FDS_START + i
};
if (fdNames[i]) {
arr[i].name = fdNames[i];
}
}
return arr;
}
/**
* @param {... string} args
* @returns
*/
export function notify(... args) {
return binding.notify(format(... args));
}
export function notifyReady() {
return notify('READY=1');
}
export function notifyReloading() {
return notify('RELOADING=1');
}
/**
* @param {string} status
* @returns
*/
export function notifyStatus(status) {
return notify('STATUS=%s', status);
}
export function notifyStopping() {
return notify('STOPPING=1');
}
export function notifyWatchdog() {
return notify('WATCHDOG=1');
}
export function watchdogEnabled() {
const usec = Number(process.env.WATCHDOG_USEC);
const pid = Number(process.env.WATCHDOG_PID);
return usec > 0 && (!pid || pid === process.pid)? usec: 0;
}
export function watchdogUsec() {
return Number(process.env.WATCHDOG_USEC) || null;
}
/**
* Starts the watchdog ping if the watchdog enabled (WatchdogSec)
* @param {number} [k]
*/
export function startWatchdogPing(k = 0.5) {
if (watchdog) {
return;
}
const usec = watchdogUsec();
if (!usec) {
return;
}
if (!(k > 0 && k < 1)) {
k = 0.5;
}
const timeout = Math.round(usec * k / 1000);
watchdog = setInterval(() => {
notifyWatchdog();
}, timeout);
}
export function stopWatchdogPing() {
if (watchdog) {
clearInterval(watchdog);
watchdog = null;
}
}