@darthcav/ts-utils 0.10.9 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +137 -39
- package/dist/index.d.ts +9 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -8
- package/dist/index.js.map +1 -1
- package/dist/loggers/getConsoleLogger.d.ts +10 -4
- package/dist/loggers/getConsoleLogger.d.ts.map +1 -1
- package/dist/loggers/getConsoleLogger.js +36 -9
- package/dist/loggers/getConsoleLogger.js.map +1 -1
- package/dist/loggers/getDummyLogger.d.ts +14 -3
- package/dist/loggers/getDummyLogger.d.ts.map +1 -1
- package/dist/loggers/getDummyLogger.js +29 -11
- package/dist/loggers/getDummyLogger.js.map +1 -1
- package/dist/main.d.ts +83 -51
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +200 -40
- package/dist/main.js.map +1 -1
- package/dist/millisecondsToString.d.ts +1 -1
- package/dist/millisecondsToString.d.ts.map +1 -1
- package/dist/millisecondsToString.js +1 -1
- package/dist/millisecondsToString.js.map +1 -1
- package/dist/monitorMemory.d.ts +25 -7
- package/dist/monitorMemory.d.ts.map +1 -1
- package/dist/monitorMemory.js +52 -14
- package/dist/monitorMemory.js.map +1 -1
- package/dist/noop.d.ts +1 -2
- package/dist/noop.d.ts.map +1 -1
- package/dist/noop.js +1 -2
- package/dist/noop.js.map +1 -1
- package/dist/{os-utils.d.ts → osRelease.d.ts} +11 -7
- package/dist/osRelease.d.ts.map +1 -0
- package/dist/osRelease.js +153 -0
- package/dist/osRelease.js.map +1 -0
- package/dist/types.d.ts +42 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +61 -16
- package/dist/types.js.map +1 -1
- package/package.json +8 -8
- package/src/index.ts +12 -7
- package/src/loggers/getConsoleLogger.ts +41 -8
- package/src/loggers/getDummyLogger.ts +31 -11
- package/src/main.ts +249 -126
- package/src/millisecondsToString.ts +1 -4
- package/src/monitorMemory.ts +58 -19
- package/src/noop.ts +1 -3
- package/src/osRelease.ts +172 -0
- package/src/types.ts +65 -17
- package/dist/os-utils.d.ts.map +0 -1
- package/dist/os-utils.js +0 -94
- package/dist/os-utils.js.map +0 -1
- package/src/os-utils.ts +0 -110
package/src/main.ts
CHANGED
|
@@ -1,143 +1,199 @@
|
|
|
1
|
+
import { constants } from "node:os"
|
|
1
2
|
import process, { env, execArgv, pid, title } from "node:process"
|
|
2
|
-
import type
|
|
3
|
-
import monitorMemory from "./monitorMemory.ts"
|
|
3
|
+
import { dispose, type Logger } from "@logtape/logtape"
|
|
4
|
+
import { monitorMemory } from "./monitorMemory.ts"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Default upper bound for flushing log sinks before the process exits, so a
|
|
8
|
+
* hanging sink cannot block shutdown.
|
|
9
|
+
*/
|
|
10
|
+
const DEFAULT_FLUSH_TIMEOUT_MS = 3_000
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Longest delay `setTimeout` supports (2³¹ − 1 ms). Node.js silently replaces
|
|
14
|
+
* larger delays with 1 ms.
|
|
15
|
+
*/
|
|
16
|
+
const MAX_FLUSH_TIMEOUT_MS = 2_147_483_647
|
|
17
|
+
|
|
18
|
+
/** Whether a {@link main} call is active, i.e. not yet torn down. */
|
|
19
|
+
let active = false
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Flushes and disposes the configured logtape sinks, giving up after
|
|
23
|
+
* `timeoutMs`. Never rejects: logging is best effort while the process is
|
|
24
|
+
* shutting down.
|
|
25
|
+
*/
|
|
26
|
+
async function flushLogs(timeoutMs: number): Promise<void> {
|
|
27
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
28
|
+
try {
|
|
29
|
+
await Promise.race([
|
|
30
|
+
dispose(),
|
|
31
|
+
new Promise<void>((resolve) => {
|
|
32
|
+
timer = setTimeout(resolve, timeoutMs)
|
|
33
|
+
}),
|
|
34
|
+
])
|
|
35
|
+
} catch {
|
|
36
|
+
// Ignore sink errors: the process is exiting anyway.
|
|
37
|
+
} finally {
|
|
38
|
+
clearTimeout(timer)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Renders an error (with its stack when available) or any other value. */
|
|
43
|
+
function describe(value: unknown): string {
|
|
44
|
+
return value instanceof Error
|
|
45
|
+
? (value.stack ?? String(value))
|
|
46
|
+
: String(value)
|
|
47
|
+
}
|
|
4
48
|
|
|
5
49
|
/**
|
|
6
50
|
* A function that performs the actual application launch after process
|
|
7
51
|
* lifecycle handlers have been set up by {@link main}. Use a closure to
|
|
8
52
|
* capture any context needed (e.g. a logger).
|
|
53
|
+
*
|
|
54
|
+
* It may be asynchronous: if it throws or its promise rejects, {@link main}
|
|
55
|
+
* logs the failure and exits the process with status `1`.
|
|
9
56
|
*/
|
|
10
|
-
export type LauncherFunction = () => void
|
|
57
|
+
export type LauncherFunction = () => void | Promise<void>
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Options for {@link main}. All of them are optional.
|
|
61
|
+
*/
|
|
62
|
+
export type MainOptions = {
|
|
63
|
+
/**
|
|
64
|
+
* Function invoked after all process handlers are registered. Use a
|
|
65
|
+
* closure to capture any context needed (e.g. a logger).
|
|
66
|
+
*/
|
|
67
|
+
launcher?: LauncherFunction
|
|
68
|
+
/**
|
|
69
|
+
* When greater than `0`, starts periodic memory logging every
|
|
70
|
+
* `monitorMemoryHours` hours via {@link monitorMemory} (which validates
|
|
71
|
+
* the value). Must be `0` or a positive finite number; negative values
|
|
72
|
+
* and `NaN` throw. Defaults to `0` (disabled).
|
|
73
|
+
*/
|
|
74
|
+
monitorMemoryHours?: number
|
|
75
|
+
/**
|
|
76
|
+
* When `true` (default), registers `SIGINT` and `SIGTERM` handlers that
|
|
77
|
+
* log, flush the logs, and stop the process. Set to `false` when the
|
|
78
|
+
* application manages its own graceful shutdown (e.g. closing servers or
|
|
79
|
+
* database connections).
|
|
80
|
+
*/
|
|
81
|
+
defaultInterruptionHandler?: boolean
|
|
82
|
+
/**
|
|
83
|
+
* Maximum time in milliseconds to wait for the logtape sinks to flush
|
|
84
|
+
* before the process exits. Must be between `0` and 2³¹ − 1. Defaults to
|
|
85
|
+
* `3000`.
|
|
86
|
+
*/
|
|
87
|
+
flushTimeoutMs?: number
|
|
88
|
+
}
|
|
11
89
|
|
|
12
90
|
/**
|
|
13
91
|
* Bootstraps an application process: logs startup information, registers
|
|
14
92
|
* handlers for `SIGINT`, `SIGTERM`, `uncaughtException`, and
|
|
15
|
-
* `unhandledRejection`,
|
|
93
|
+
* `unhandledRejection`, optionally starts memory monitoring, then runs the
|
|
94
|
+
* optional launcher function.
|
|
95
|
+
*
|
|
96
|
+
* The process title, PID, name, and `NODE_ENV` are logged at `info` level.
|
|
97
|
+
* The Node.js process options (`execArgv` and `NODE_OPTIONS`) are logged at
|
|
98
|
+
* `debug` level only, since they can reveal sensitive flags such as
|
|
99
|
+
* `--inspect=0.0.0.0` or `--require` paths.
|
|
16
100
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
101
|
+
* Before the process exits, the configured logtape sinks are flushed and
|
|
102
|
+
* disposed (for at most `flushTimeoutMs`, 3 seconds by default), so buffered
|
|
103
|
+
* or asynchronous sinks do not lose the final messages. On `SIGINT`/`SIGTERM`
|
|
104
|
+
* the signal is logged at `info` level and then re-raised, so the process ends
|
|
105
|
+
* as killed by that signal (exit status 130/143), which shells and
|
|
106
|
+
* supervisors such as systemd treat as a clean stop. If another listener for
|
|
107
|
+
* that signal is registered, the process exits with status
|
|
108
|
+
* `128 + signal number` instead. Uncaught exceptions, unhandled rejections,
|
|
109
|
+
* and launcher failures exit with status `1`. A second signal or error during
|
|
110
|
+
* the flush exits immediately.
|
|
20
111
|
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* | `main(name, logger, fn)` | fn | 0 | true |
|
|
25
|
-
* | `main(name, logger, 2)` | — | 2 | true |
|
|
26
|
-
* | `main(name, logger, false)` | — | 0 | false |
|
|
27
|
-
* | `main(name, logger, fn, 2)` | fn | 2 | true |
|
|
28
|
-
* | `main(name, logger, fn, false)` | fn | 0 | false |
|
|
29
|
-
* | `main(name, logger, 2, false)` | — | 2 | false |
|
|
30
|
-
* | `main(name, logger, fn, 2, false)` | fn | 2 | false |
|
|
112
|
+
* Only one `main` call can be active at a time: calling it again before
|
|
113
|
+
* running the returned teardown function throws, instead of registering a
|
|
114
|
+
* second set of handlers.
|
|
31
115
|
*
|
|
32
116
|
* @param name - Human-readable application name used in log output.
|
|
33
117
|
* @param logger - Logger instance used for all startup and lifecycle messages.
|
|
118
|
+
* @param options - Optional {@link MainOptions}.
|
|
119
|
+
* @returns A teardown function that removes the process handlers registered
|
|
120
|
+
* by this call and stops the memory monitoring, allowing `main` to be called
|
|
121
|
+
* again (e.g. in tests). It does not exit the process; calling it more than
|
|
122
|
+
* once is harmless.
|
|
123
|
+
* @throws {TypeError} If `options` is not an object.
|
|
124
|
+
* @throws {Error} If another `main` call is still active.
|
|
125
|
+
* @throws {RangeError} If `monitorMemoryHours` or `flushTimeoutMs` is out of
|
|
126
|
+
* range. Nothing is registered in that case.
|
|
34
127
|
*
|
|
35
|
-
* @example Without
|
|
128
|
+
* @example Without options:
|
|
36
129
|
* ```ts
|
|
37
130
|
* main("my-app", logger)
|
|
38
131
|
* ```
|
|
39
132
|
*
|
|
40
|
-
* @example With
|
|
41
|
-
* ```ts
|
|
42
|
-
* main("my-app", logger, () => startServer())
|
|
43
|
-
* ```
|
|
44
|
-
*
|
|
45
|
-
* @example With memory monitoring every 2 hours:
|
|
133
|
+
* @example With an async launcher and memory monitoring every 2 hours:
|
|
46
134
|
* ```ts
|
|
47
|
-
* main("my-app", logger,
|
|
48
|
-
*
|
|
135
|
+
* main("my-app", logger, {
|
|
136
|
+
* launcher: async () => {
|
|
137
|
+
* await connectToDatabase()
|
|
138
|
+
* startServer()
|
|
139
|
+
* },
|
|
140
|
+
* monitorMemoryHours: 2,
|
|
141
|
+
* })
|
|
49
142
|
* ```
|
|
50
143
|
*
|
|
51
|
-
* @example
|
|
144
|
+
* @example Managing graceful shutdown in the application:
|
|
52
145
|
* ```ts
|
|
53
|
-
* main("my-app", logger,
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
146
|
+
* const teardown = main("my-app", logger, {
|
|
147
|
+
* launcher: () => startServer(),
|
|
148
|
+
* defaultInterruptionHandler: false,
|
|
149
|
+
* })
|
|
150
|
+
* process.once("SIGTERM", async () => {
|
|
151
|
+
* await server.close()
|
|
152
|
+
* teardown()
|
|
153
|
+
* })
|
|
57
154
|
* ```
|
|
58
155
|
*/
|
|
59
|
-
export function main(name: string, logger: Logger): void
|
|
60
|
-
export function main(
|
|
61
|
-
name: string,
|
|
62
|
-
logger: Logger,
|
|
63
|
-
launcher: LauncherFunction,
|
|
64
|
-
): void
|
|
65
|
-
export function main(
|
|
66
|
-
name: string,
|
|
67
|
-
logger: Logger,
|
|
68
|
-
monitorMemoryHours: number,
|
|
69
|
-
): void
|
|
70
|
-
export function main(
|
|
71
|
-
name: string,
|
|
72
|
-
logger: Logger,
|
|
73
|
-
defaultInterruptionHandler: boolean,
|
|
74
|
-
): void
|
|
75
|
-
export function main(
|
|
76
|
-
name: string,
|
|
77
|
-
logger: Logger,
|
|
78
|
-
launcher: LauncherFunction,
|
|
79
|
-
monitorMemoryHours: number,
|
|
80
|
-
): void
|
|
81
156
|
export function main(
|
|
82
157
|
name: string,
|
|
83
158
|
logger: Logger,
|
|
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
|
-
|
|
122
|
-
let defaultInterruptionHandler = true
|
|
123
|
-
|
|
124
|
-
if (typeof arg3 === "function") {
|
|
125
|
-
launcher = arg3
|
|
126
|
-
if (typeof arg4 === "number") {
|
|
127
|
-
monitorMemoryHours = arg4
|
|
128
|
-
if (typeof arg5 === "boolean") {
|
|
129
|
-
defaultInterruptionHandler = arg5
|
|
130
|
-
}
|
|
131
|
-
} else if (typeof arg4 === "boolean") {
|
|
132
|
-
defaultInterruptionHandler = arg4
|
|
133
|
-
}
|
|
134
|
-
} else if (typeof arg3 === "number") {
|
|
135
|
-
monitorMemoryHours = arg3
|
|
136
|
-
if (typeof arg4 === "boolean") {
|
|
137
|
-
defaultInterruptionHandler = arg4
|
|
138
|
-
}
|
|
139
|
-
} else if (typeof arg3 === "boolean") {
|
|
140
|
-
defaultInterruptionHandler = arg3
|
|
159
|
+
options?: MainOptions,
|
|
160
|
+
): () => void {
|
|
161
|
+
// Rejects the positional arguments removed in 0.11.0 (e.g. a launcher
|
|
162
|
+
// function) from untyped callers, instead of silently ignoring them.
|
|
163
|
+
if (
|
|
164
|
+
options !== undefined &&
|
|
165
|
+
(typeof options !== "object" || options === null)
|
|
166
|
+
) {
|
|
167
|
+
throw new TypeError(
|
|
168
|
+
`main: "options" must be a MainOptions object, received ${options === null ? "null" : typeof options}`,
|
|
169
|
+
)
|
|
170
|
+
}
|
|
171
|
+
const {
|
|
172
|
+
launcher,
|
|
173
|
+
monitorMemoryHours = 0,
|
|
174
|
+
defaultInterruptionHandler = true,
|
|
175
|
+
flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS,
|
|
176
|
+
} = options ?? {}
|
|
177
|
+
|
|
178
|
+
// Positive values are validated further by `monitorMemory`.
|
|
179
|
+
if (!Number.isFinite(monitorMemoryHours) || monitorMemoryHours < 0) {
|
|
180
|
+
throw new RangeError(
|
|
181
|
+
`main: "monitorMemoryHours" must be 0 (disabled) or a positive finite number, received ${monitorMemoryHours}`,
|
|
182
|
+
)
|
|
183
|
+
}
|
|
184
|
+
if (
|
|
185
|
+
!Number.isFinite(flushTimeoutMs) ||
|
|
186
|
+
flushTimeoutMs < 0 ||
|
|
187
|
+
flushTimeoutMs > MAX_FLUSH_TIMEOUT_MS
|
|
188
|
+
) {
|
|
189
|
+
throw new RangeError(
|
|
190
|
+
`main: "flushTimeoutMs" must be a finite number between 0 and ${MAX_FLUSH_TIMEOUT_MS}, received ${flushTimeoutMs}`,
|
|
191
|
+
)
|
|
192
|
+
}
|
|
193
|
+
if (active) {
|
|
194
|
+
throw new Error(
|
|
195
|
+
"main: already active; call the teardown function returned by the previous main() call first",
|
|
196
|
+
)
|
|
141
197
|
}
|
|
142
198
|
|
|
143
199
|
const __logger = logger.getChild(["main"])
|
|
@@ -145,31 +201,98 @@ export function main(
|
|
|
145
201
|
__logger.info`Main process launched [${title} :: ${pid}]`
|
|
146
202
|
__logger.info`Process name: ${name}`
|
|
147
203
|
__logger.info`Node.js environment: ${env["NODE_ENV"] ?? ""}`
|
|
148
|
-
|
|
204
|
+
// Process options can reveal sensitive flags (e.g. `--inspect=0.0.0.0`
|
|
205
|
+
// or `--require` paths), so they are only logged at debug level.
|
|
206
|
+
__logger.debug`Node.js process options: ${execArgv.concat(env["NODE_OPTIONS"] ?? []).join(" | ")}`
|
|
149
207
|
|
|
150
|
-
|
|
151
|
-
|
|
208
|
+
// Started before any handler is registered: it throws on invalid hours.
|
|
209
|
+
const stopMonitoring =
|
|
210
|
+
monitorMemoryHours > 0
|
|
211
|
+
? monitorMemory(__logger, monitorMemoryHours)
|
|
212
|
+
: undefined
|
|
213
|
+
|
|
214
|
+
// Set once a shutdown starts: a second signal or error while the logs are
|
|
215
|
+
// being flushed exits immediately instead of waiting again.
|
|
216
|
+
let shuttingDown = false
|
|
217
|
+
const exitAfterFlush = async (exit: () => void): Promise<void> => {
|
|
218
|
+
if (!shuttingDown) {
|
|
219
|
+
shuttingDown = true
|
|
220
|
+
await flushLogs(flushTimeoutMs)
|
|
221
|
+
}
|
|
222
|
+
exit()
|
|
152
223
|
}
|
|
153
224
|
|
|
225
|
+
const removeListeners: (() => void)[] = []
|
|
226
|
+
|
|
154
227
|
if (defaultInterruptionHandler) {
|
|
155
228
|
for (const signal of ["SIGINT", "SIGTERM"] as const) {
|
|
156
|
-
|
|
157
|
-
__logger.
|
|
158
|
-
|
|
159
|
-
|
|
229
|
+
const onSignal = (): Promise<void> => {
|
|
230
|
+
__logger.info`Process interrupted. Received signal: ${signal}`
|
|
231
|
+
return exitAfterFlush(() => {
|
|
232
|
+
// Re-raise the signal with its default disposition so the
|
|
233
|
+
// process ends as killed by it. Exit with the conventional
|
|
234
|
+
// status instead if another listener would intercept it.
|
|
235
|
+
process.off(signal, onSignal)
|
|
236
|
+
if (process.listenerCount(signal) === 0) {
|
|
237
|
+
process.kill(pid, signal)
|
|
238
|
+
} else {
|
|
239
|
+
process.exit(128 + constants.signals[signal])
|
|
240
|
+
}
|
|
241
|
+
})
|
|
242
|
+
}
|
|
243
|
+
process.on(signal, onSignal)
|
|
244
|
+
removeListeners.push(() => process.off(signal, onSignal))
|
|
160
245
|
}
|
|
161
246
|
}
|
|
162
247
|
|
|
163
|
-
|
|
164
|
-
|
|
248
|
+
const onUncaughtException = (
|
|
249
|
+
error: Error,
|
|
250
|
+
origin: NodeJS.UncaughtExceptionOrigin,
|
|
251
|
+
): Promise<void> => {
|
|
252
|
+
__logger.error`Uncaught exception: ${describe(error)}`
|
|
165
253
|
__logger.error`Exception origin: ${origin}`
|
|
166
|
-
process.exit(1)
|
|
167
|
-
}
|
|
254
|
+
return exitAfterFlush(() => process.exit(1))
|
|
255
|
+
}
|
|
256
|
+
process.on("uncaughtException", onUncaughtException)
|
|
257
|
+
removeListeners.push(() =>
|
|
258
|
+
process.off("uncaughtException", onUncaughtException),
|
|
259
|
+
)
|
|
168
260
|
|
|
169
|
-
|
|
170
|
-
__logger.error`Unhandled promise rejection. Reason:\n${
|
|
171
|
-
process.exit(1)
|
|
172
|
-
}
|
|
261
|
+
const onUnhandledRejection = (reason: unknown): Promise<void> => {
|
|
262
|
+
__logger.error`Unhandled promise rejection. Reason:\n${describe(reason)}`
|
|
263
|
+
return exitAfterFlush(() => process.exit(1))
|
|
264
|
+
}
|
|
265
|
+
process.on("unhandledRejection", onUnhandledRejection)
|
|
266
|
+
removeListeners.push(() =>
|
|
267
|
+
process.off("unhandledRejection", onUnhandledRejection),
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
active = true
|
|
271
|
+
let tornDown = false
|
|
272
|
+
const teardown = (): void => {
|
|
273
|
+
if (tornDown) {
|
|
274
|
+
return
|
|
275
|
+
}
|
|
276
|
+
tornDown = true
|
|
277
|
+
stopMonitoring?.()
|
|
278
|
+
for (const remove of removeListeners) {
|
|
279
|
+
remove()
|
|
280
|
+
}
|
|
281
|
+
active = false
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const onLauncherFailure = (error: unknown): Promise<void> => {
|
|
285
|
+
__logger.error`Launcher failed: ${describe(error)}`
|
|
286
|
+
return exitAfterFlush(() => process.exit(1))
|
|
287
|
+
}
|
|
288
|
+
try {
|
|
289
|
+
const result = launcher?.()
|
|
290
|
+
if (result !== undefined) {
|
|
291
|
+
Promise.resolve(result).catch(onLauncherFailure)
|
|
292
|
+
}
|
|
293
|
+
} catch (error) {
|
|
294
|
+
void onLauncherFailure(error)
|
|
295
|
+
}
|
|
173
296
|
|
|
174
|
-
|
|
297
|
+
return teardown
|
|
175
298
|
}
|
|
@@ -60,10 +60,7 @@ function getDurationFormatter(locale: string): Intl.DurationFormat {
|
|
|
60
60
|
* millisecondsToString(90_061_000, "es") // "1d 1h 1min 1s"
|
|
61
61
|
* ```
|
|
62
62
|
*/
|
|
63
|
-
export
|
|
64
|
-
ms: number,
|
|
65
|
-
locale = "en",
|
|
66
|
-
): string {
|
|
63
|
+
export function millisecondsToString(ms: number, locale = "en"): string {
|
|
67
64
|
if (!Number.isFinite(ms)) {
|
|
68
65
|
throw new RangeError(
|
|
69
66
|
`millisecondsToString: "ms" must be a finite number, received ${ms}`,
|
package/src/monitorMemory.ts
CHANGED
|
@@ -1,20 +1,45 @@
|
|
|
1
1
|
import { memoryUsage, uptime } from "node:process"
|
|
2
2
|
import type { Logger } from "@logtape/logtape"
|
|
3
|
-
import millisecondsToString from "./millisecondsToString.ts"
|
|
3
|
+
import { millisecondsToString } from "./millisecondsToString.ts"
|
|
4
|
+
|
|
5
|
+
/** Shortest allowed reporting interval: one minute. */
|
|
6
|
+
const MIN_DELAY_MS = 60 * 1_000
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Longest delay `setInterval` supports (2³¹ − 1 ms, about 596.5 hours). Node.js
|
|
10
|
+
* silently replaces larger delays with 1 ms, which would flood the logs.
|
|
11
|
+
*/
|
|
12
|
+
const MAX_DELAY_MS = 2_147_483_647
|
|
4
13
|
|
|
5
14
|
/**
|
|
6
|
-
* Starts a periodic interval that logs process uptime and memory usage
|
|
15
|
+
* Starts a periodic interval that logs process uptime and memory usage, and
|
|
16
|
+
* returns a function that stops it.
|
|
7
17
|
*
|
|
8
18
|
* Memory figures are reported in bytes as returned by Node.js
|
|
9
19
|
* {@link https://nodejs.org/api/process.html#processmemoryusage | process.memoryUsage()}.
|
|
10
20
|
* Reports are emitted through a `"monitorMemory"` child category of the given
|
|
11
|
-
* logger
|
|
21
|
+
* logger as two `info` records whose figures are also attached as structured
|
|
22
|
+
* properties, so sinks and formatters that keep properties (e.g. JSON Lines)
|
|
23
|
+
* can query them:
|
|
24
|
+
*
|
|
25
|
+
* - `"Process uptime: <duration>"` with `uptime` (the duration formatted by
|
|
26
|
+
* `millisecondsToString`) and `uptimeMs` (integer milliseconds).
|
|
27
|
+
* - `"Process memory - Resident set size: {rss} | Heap total: {heapTotal} |
|
|
28
|
+
* Heap used: {heapUsed} | External: {external}"` with `rss`, `heapTotal`,
|
|
29
|
+
* `heapUsed`, and `external`.
|
|
30
|
+
*
|
|
31
|
+
* The interval timer is unreferenced, so monitoring alone does not keep the
|
|
32
|
+
* process alive.
|
|
12
33
|
*
|
|
13
34
|
* @param logger - Logger whose `"monitorMemory"` child emits the memory
|
|
14
35
|
* reports.
|
|
15
36
|
* @param hours - Interval between reports in hours. Must be a finite number
|
|
16
|
-
*
|
|
17
|
-
*
|
|
37
|
+
* between `1 / 60` (one minute) and about `596.5` (2³¹ − 1 ms, the longest
|
|
38
|
+
* delay `setInterval` supports). Defaults to `24`.
|
|
39
|
+
* @returns A function that stops the monitoring. Calling it more than once is
|
|
40
|
+
* harmless.
|
|
41
|
+
* @throws {RangeError} If `hours` is not finite or the resulting interval is
|
|
42
|
+
* shorter than one minute or longer than 2³¹ − 1 milliseconds.
|
|
18
43
|
*
|
|
19
44
|
* @example
|
|
20
45
|
* ```ts
|
|
@@ -22,29 +47,43 @@ import millisecondsToString from "./millisecondsToString.ts"
|
|
|
22
47
|
*
|
|
23
48
|
* const logger = await getConsoleLogger("my-app")
|
|
24
49
|
*
|
|
25
|
-
* monitorMemory(logger)
|
|
26
|
-
* monitorMemory(logger, 1) // every hour
|
|
50
|
+
* monitorMemory(logger) // every 24 hours
|
|
51
|
+
* const stop = monitorMemory(logger, 1) // every hour
|
|
52
|
+
* // ...
|
|
53
|
+
* stop()
|
|
27
54
|
* ```
|
|
28
55
|
*/
|
|
29
|
-
export
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
)
|
|
33
|
-
|
|
56
|
+
export function monitorMemory(logger: Logger, hours: number = 24): () => void {
|
|
57
|
+
const delay = 60 * 60 * 1_000 * hours
|
|
58
|
+
if (
|
|
59
|
+
!Number.isFinite(delay) ||
|
|
60
|
+
delay < MIN_DELAY_MS ||
|
|
61
|
+
delay > MAX_DELAY_MS
|
|
62
|
+
) {
|
|
34
63
|
throw new RangeError(
|
|
35
|
-
`monitorMemory: "hours" must be a finite number
|
|
64
|
+
`monitorMemory: "hours" must be a finite number between ${MIN_DELAY_MS / 3_600_000} and ${MAX_DELAY_MS / 3_600_000} (1 minute to 2^31 - 1 ms), received ${hours}`,
|
|
36
65
|
)
|
|
37
66
|
}
|
|
38
67
|
const __logger = logger.getChild(["monitorMemory"])
|
|
39
68
|
|
|
40
|
-
const
|
|
41
|
-
|
|
69
|
+
const timer = setInterval(() => {
|
|
70
|
+
const uptimeMs = Math.round(uptime() * 1_000)
|
|
71
|
+
const formattedUptime = millisecondsToString(uptimeMs)
|
|
42
72
|
const { rss, heapTotal, heapUsed, external } = memoryUsage()
|
|
73
|
+
// The duration goes into the message text itself: as a `{uptime}`
|
|
74
|
+
// placeholder, text formatters would render the string quoted. It is
|
|
75
|
+
// safe to embed because "en" durations never contain `{` or `}`.
|
|
76
|
+
__logger.info(`Process uptime: ${formattedUptime}`, {
|
|
77
|
+
uptime: formattedUptime,
|
|
78
|
+
uptimeMs,
|
|
79
|
+
})
|
|
43
80
|
__logger.info(
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
__logger.info(
|
|
47
|
-
`Process memory - Resident set size: ${rss} | Heap total: ${heapTotal} | Heap used: ${heapUsed} | External: ${external}`,
|
|
81
|
+
"Process memory - Resident set size: {rss} | Heap total: {heapTotal} | Heap used: {heapUsed} | External: {external}",
|
|
82
|
+
{ rss, heapTotal, heapUsed, external },
|
|
48
83
|
)
|
|
49
84
|
}, delay)
|
|
85
|
+
// Monitoring alone must not keep the process alive.
|
|
86
|
+
timer.unref()
|
|
87
|
+
|
|
88
|
+
return () => clearInterval(timer)
|
|
50
89
|
}
|