@darthcav/ts-utils 0.12.2 → 1.0.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 +152 -81
- package/dist/core/guards.d.ts +176 -0
- package/dist/core/guards.d.ts.map +1 -0
- package/dist/core/guards.js +207 -0
- package/dist/core/guards.js.map +1 -0
- package/dist/core/index.d.ts +16 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +16 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/millisecondsToString.d.ts.map +1 -0
- package/dist/{millisecondsToString.js → core/millisecondsToString.js} +3 -4
- package/dist/core/millisecondsToString.js.map +1 -0
- package/dist/core/noop.d.ts +3 -0
- package/dist/core/noop.d.ts.map +1 -0
- package/dist/core/noop.js +3 -0
- package/dist/core/noop.js.map +1 -0
- package/dist/index.d.ts +13 -17
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -10
- package/dist/index.js.map +1 -1
- package/dist/loggers/getConsoleLogger.d.ts +11 -12
- package/dist/loggers/getConsoleLogger.d.ts.map +1 -1
- package/dist/loggers/getConsoleLogger.js +14 -19
- package/dist/loggers/getConsoleLogger.js.map +1 -1
- package/dist/loggers/index.d.ts +14 -0
- package/dist/loggers/index.d.ts.map +1 -0
- package/dist/loggers/index.js +14 -0
- package/dist/loggers/index.js.map +1 -0
- package/dist/node/index.d.ts +15 -0
- package/dist/node/index.d.ts.map +1 -0
- package/dist/node/index.js +15 -0
- package/dist/node/index.js.map +1 -0
- package/dist/node/main.d.ts +156 -0
- package/dist/node/main.d.ts.map +1 -0
- package/dist/node/main.js +261 -0
- package/dist/node/main.js.map +1 -0
- package/dist/{monitorMemory.d.ts → node/monitorMemory.d.ts} +3 -5
- package/dist/node/monitorMemory.d.ts.map +1 -0
- package/dist/{monitorMemory.js → node/monitorMemory.js} +4 -7
- package/dist/node/monitorMemory.js.map +1 -0
- package/dist/node/osRelease.d.ts +55 -0
- package/dist/node/osRelease.d.ts.map +1 -0
- package/dist/{osRelease.js → node/osRelease.js} +77 -24
- package/dist/node/osRelease.js.map +1 -0
- package/dist/type-testing/index.d.ts +18 -0
- package/dist/type-testing/index.d.ts.map +1 -0
- package/dist/type-testing/index.js +12 -0
- package/dist/type-testing/index.js.map +1 -0
- package/package.json +23 -8
- package/src/core/guards.ts +243 -0
- package/src/core/index.ts +31 -0
- package/src/{millisecondsToString.ts → core/millisecondsToString.ts} +3 -4
- package/src/core/noop.ts +2 -0
- package/src/index.ts +13 -49
- package/src/loggers/getConsoleLogger.ts +14 -19
- package/src/loggers/index.ts +14 -0
- package/src/node/index.ts +21 -0
- package/src/node/main.ts +427 -0
- package/src/{monitorMemory.ts → node/monitorMemory.ts} +4 -7
- package/src/node/osRelease.ts +251 -0
- package/src/type-testing/index.ts +18 -0
- package/dist/main.d.ts +0 -112
- package/dist/main.d.ts.map +0 -1
- package/dist/main.js +0 -219
- package/dist/main.js.map +0 -1
- package/dist/millisecondsToString.d.ts.map +0 -1
- package/dist/millisecondsToString.js.map +0 -1
- package/dist/monitorMemory.d.ts.map +0 -1
- package/dist/monitorMemory.js.map +0 -1
- package/dist/noop.d.ts +0 -7
- package/dist/noop.d.ts.map +0 -1
- package/dist/noop.js +0 -7
- package/dist/noop.js.map +0 -1
- package/dist/osRelease.d.ts +0 -46
- package/dist/osRelease.d.ts.map +0 -1
- package/dist/osRelease.js.map +0 -1
- package/dist/types.d.ts +0 -70
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js +0 -84
- package/dist/types.js.map +0 -1
- package/src/main.ts +0 -302
- package/src/noop.ts +0 -6
- package/src/osRelease.ts +0 -174
- package/src/types.ts +0 -98
- /package/dist/{millisecondsToString.d.ts → core/millisecondsToString.d.ts} +0 -0
|
@@ -17,13 +17,9 @@ const FORMATTER_OPTIONS: TextFormatterOptions = {
|
|
|
17
17
|
}
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
* value enables them). Otherwise colors are used only when both stdout and
|
|
24
|
-
* stderr are terminals that support them, since the console sink writes
|
|
25
|
-
* warnings and errors to stderr. `hasColors()` also honors `NO_COLOR`,
|
|
26
|
-
* `NODE_DISABLE_COLORS`, and `TERM=dumb`.
|
|
20
|
+
* Whether console output should use ANSI colors. `FORCE_COLOR` wins when set;
|
|
21
|
+
* otherwise both stdout and stderr must support colors, since the console
|
|
22
|
+
* sink writes warnings and errors to stderr.
|
|
27
23
|
*/
|
|
28
24
|
function useColors(): boolean {
|
|
29
25
|
const force = process.env["FORCE_COLOR"]
|
|
@@ -36,22 +32,21 @@ function useColors(): boolean {
|
|
|
36
32
|
}
|
|
37
33
|
|
|
38
34
|
/**
|
|
39
|
-
* Configures
|
|
35
|
+
* Configures LogTape globally and returns a {@link Logger} for the given
|
|
36
|
+
* category.
|
|
40
37
|
*
|
|
41
|
-
* Records at or above `lowestLevel`
|
|
42
|
-
* timestamps and full level names
|
|
38
|
+
* Records at or above `lowestLevel` go to the console with RFC 3339
|
|
39
|
+
* timestamps and full level names; the internal `logtape/meta` logger is
|
|
43
40
|
* silenced.
|
|
44
41
|
*
|
|
45
|
-
* ANSI colors are used only when both stdout and stderr are terminals
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
* value enables them. The decision is made when this function is called.
|
|
42
|
+
* ANSI colors are used only when both stdout and stderr are color terminals
|
|
43
|
+
* (respecting `NO_COLOR`, `NODE_DISABLE_COLORS`, and `TERM=dumb`), so
|
|
44
|
+
* redirected output has no escape codes. `FORCE_COLOR` overrides this: `"0"`
|
|
45
|
+
* or `"false"` disables colors, any other value enables them.
|
|
50
46
|
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
* configured.)
|
|
47
|
+
* Each call replaces the whole global LogTape configuration, so the latest
|
|
48
|
+
* call wins. Applications that configure LogTape themselves should use
|
|
49
|
+
* LogTape's `getLogger` instead.
|
|
55
50
|
*
|
|
56
51
|
* @param name - The top-level category name (typically the application name).
|
|
57
52
|
* @param lowestLevel - The minimum log level to output. Defaults to `"info"`.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LogTape logger helpers: a configured console logger and a no-op logger for
|
|
3
|
+
* tests.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { getConsoleLogger } from "@darthcav/ts-utils/loggers"
|
|
8
|
+
* ```
|
|
9
|
+
*
|
|
10
|
+
* @module loggers
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export { getConsoleLogger } from "./getConsoleLogger.ts"
|
|
14
|
+
export { getDummyLogger } from "./getDummyLogger.ts"
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Node.js process utilities: application bootstrap and shutdown (`main`),
|
|
3
|
+
* memory monitoring, and OS release information.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { main, osRelease } from "@darthcav/ts-utils/node"
|
|
8
|
+
* ```
|
|
9
|
+
*
|
|
10
|
+
* @module node
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export {
|
|
14
|
+
type LauncherFunction,
|
|
15
|
+
type MainOptions,
|
|
16
|
+
main,
|
|
17
|
+
type ShutdownContext,
|
|
18
|
+
type ShutdownFunction,
|
|
19
|
+
} from "./main.ts"
|
|
20
|
+
export { monitorMemory } from "./monitorMemory.ts"
|
|
21
|
+
export { type OsRelease, osRelease } from "./osRelease.ts"
|
package/src/node/main.ts
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
import { constants } from "node:os"
|
|
2
|
+
import process, { env, execArgv, pid, title } from "node:process"
|
|
3
|
+
import { dispose, type Logger } from "@logtape/logtape"
|
|
4
|
+
import { monitorMemory } from "./monitorMemory.ts"
|
|
5
|
+
|
|
6
|
+
/** Default for {@link MainOptions.flushTimeoutMs}. */
|
|
7
|
+
const DEFAULT_FLUSH_TIMEOUT_MS = 3_000
|
|
8
|
+
|
|
9
|
+
/** Default for {@link MainOptions.shutdownTimeoutMs}. */
|
|
10
|
+
const DEFAULT_SHUTDOWN_TIMEOUT_MS = 10_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_TIMEOUT_MS = 2_147_483_647
|
|
17
|
+
|
|
18
|
+
/** Whether a {@link main} call has not been torn down yet. */
|
|
19
|
+
let active = false
|
|
20
|
+
|
|
21
|
+
/** How a task run by {@link runBounded} ended. */
|
|
22
|
+
type BoundedOutcome =
|
|
23
|
+
| { status: "fulfilled" }
|
|
24
|
+
| { status: "rejected"; reason: unknown }
|
|
25
|
+
| { status: "timeout" }
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Runs a possibly asynchronous task and waits for it for at most `timeoutMs`.
|
|
29
|
+
* Never rejects: a throwing or rejecting task is reported as `"rejected"`.
|
|
30
|
+
* The timer stays referenced, so the process keeps running while it waits.
|
|
31
|
+
*/
|
|
32
|
+
async function runBounded(
|
|
33
|
+
task: () => unknown,
|
|
34
|
+
timeoutMs: number,
|
|
35
|
+
): Promise<BoundedOutcome> {
|
|
36
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
37
|
+
try {
|
|
38
|
+
return await Promise.race([
|
|
39
|
+
Promise.try(task).then(
|
|
40
|
+
(): BoundedOutcome => ({ status: "fulfilled" }),
|
|
41
|
+
(reason: unknown): BoundedOutcome => ({
|
|
42
|
+
status: "rejected",
|
|
43
|
+
reason,
|
|
44
|
+
}),
|
|
45
|
+
),
|
|
46
|
+
new Promise<BoundedOutcome>((resolve) => {
|
|
47
|
+
timer = setTimeout(
|
|
48
|
+
() => resolve({ status: "timeout" }),
|
|
49
|
+
timeoutMs,
|
|
50
|
+
)
|
|
51
|
+
}),
|
|
52
|
+
])
|
|
53
|
+
} finally {
|
|
54
|
+
clearTimeout(timer)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Renders an error (with its stack when available) or any other value. */
|
|
59
|
+
function describe(value: unknown): string {
|
|
60
|
+
return value instanceof Error
|
|
61
|
+
? (value.stack ?? String(value))
|
|
62
|
+
: String(value)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Throws a `RangeError` unless `value` is a valid timer delay. */
|
|
66
|
+
function assertTimeout(option: string, value: number): void {
|
|
67
|
+
if (!Number.isFinite(value) || value < 0 || value > MAX_TIMEOUT_MS) {
|
|
68
|
+
throw new RangeError(
|
|
69
|
+
`main: "${option}" must be a finite number between 0 and ${MAX_TIMEOUT_MS}, received ${value}`,
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Throws a `TypeError` unless `value` is a function or `undefined`. */
|
|
75
|
+
function assertOptionalFunction(option: string, value: unknown): void {
|
|
76
|
+
if (value !== undefined && typeof value !== "function") {
|
|
77
|
+
throw new TypeError(
|
|
78
|
+
`main: "${option}" must be a function, received ${value === null ? "null" : typeof value}`,
|
|
79
|
+
)
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Starts the application once {@link main} has registered the process
|
|
85
|
+
* handlers. Use a closure to capture any context needed (e.g. a logger). It
|
|
86
|
+
* may be asynchronous; if it throws or rejects, {@link main} logs the failure
|
|
87
|
+
* and shuts down with exit status `1`.
|
|
88
|
+
*/
|
|
89
|
+
export type LauncherFunction = () => void | Promise<void>
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Why {@link main} is shutting down, passed to the {@link ShutdownFunction}.
|
|
93
|
+
*
|
|
94
|
+
* - `reason: "signal"`: a normal stop requested with `SIGINT` or `SIGTERM`.
|
|
95
|
+
* - `reason: "error"`: a fatal failure; `source` says where it came from and
|
|
96
|
+
* `error` holds the thrown value or rejection reason. The application may
|
|
97
|
+
* be in an inconsistent state, so only clean up (e.g. close connections).
|
|
98
|
+
*/
|
|
99
|
+
export type ShutdownContext =
|
|
100
|
+
| {
|
|
101
|
+
readonly reason: "signal"
|
|
102
|
+
readonly signal: "SIGINT" | "SIGTERM"
|
|
103
|
+
}
|
|
104
|
+
| {
|
|
105
|
+
readonly reason: "error"
|
|
106
|
+
readonly source:
|
|
107
|
+
| "uncaughtException"
|
|
108
|
+
| "unhandledRejection"
|
|
109
|
+
| "launcher"
|
|
110
|
+
readonly error: unknown
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Application cleanup (e.g. closing servers and database connections), run
|
|
115
|
+
* once by {@link main} before the logs are flushed and the process exits. It
|
|
116
|
+
* may be asynchronous; {@link main} waits at most
|
|
117
|
+
* {@link MainOptions.shutdownTimeoutMs} for it.
|
|
118
|
+
*
|
|
119
|
+
* @param context - Why the process is shutting down.
|
|
120
|
+
*/
|
|
121
|
+
export type ShutdownFunction = (
|
|
122
|
+
context: ShutdownContext,
|
|
123
|
+
) => void | Promise<void>
|
|
124
|
+
|
|
125
|
+
/** Options for {@link main}, all optional. */
|
|
126
|
+
export type MainOptions = {
|
|
127
|
+
/** Starts the application (see {@link LauncherFunction}). */
|
|
128
|
+
launcher?: LauncherFunction
|
|
129
|
+
/**
|
|
130
|
+
* Application cleanup, run once on shutdown (see {@link ShutdownFunction}).
|
|
131
|
+
* If it throws, rejects, or exceeds {@link MainOptions.shutdownTimeoutMs},
|
|
132
|
+
* the failure is logged and the process exits with status `1`.
|
|
133
|
+
*/
|
|
134
|
+
shutdown?: ShutdownFunction
|
|
135
|
+
/**
|
|
136
|
+
* Maximum wait in milliseconds for {@link MainOptions.shutdown}, between
|
|
137
|
+
* `0` and 2³¹ − 1. Defaults to `10000`.
|
|
138
|
+
*/
|
|
139
|
+
shutdownTimeoutMs?: number
|
|
140
|
+
/**
|
|
141
|
+
* When greater than `0`, logs the memory usage every `monitorMemoryHours`
|
|
142
|
+
* hours via {@link monitorMemory}. Must be `0` or a positive finite
|
|
143
|
+
* number. Defaults to `0` (disabled).
|
|
144
|
+
*/
|
|
145
|
+
monitorMemoryHours?: number
|
|
146
|
+
/**
|
|
147
|
+
* When `true` (default), registers `SIGINT` and `SIGTERM` handlers that
|
|
148
|
+
* run the shutdown sequence and stop the process. Set to `false` when the
|
|
149
|
+
* application handles these signals itself.
|
|
150
|
+
*/
|
|
151
|
+
defaultInterruptionHandler?: boolean
|
|
152
|
+
/**
|
|
153
|
+
* Flushes the log sinks before the process exits; errors are ignored.
|
|
154
|
+
* Defaults to LogTape's `dispose`, which flushes the sinks configured
|
|
155
|
+
* through the `@logtape/logtape` copy this package uses. Pass another
|
|
156
|
+
* function (e.g. the `dispose` of the application's own LogTape copy), or
|
|
157
|
+
* `noop` to skip flushing.
|
|
158
|
+
*/
|
|
159
|
+
flushLogs?: () => void | Promise<void>
|
|
160
|
+
/**
|
|
161
|
+
* Maximum wait in milliseconds for {@link MainOptions.flushLogs}, between
|
|
162
|
+
* `0` and 2³¹ − 1. Defaults to `3000`.
|
|
163
|
+
*/
|
|
164
|
+
flushTimeoutMs?: number
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Bootstraps an application process: logs startup information, optionally
|
|
169
|
+
* registers handlers for `SIGINT` and `SIGTERM` (see
|
|
170
|
+
* {@link MainOptions.defaultInterruptionHandler}), always registers handlers
|
|
171
|
+
* for `uncaughtException` and `unhandledRejection`, optionally starts memory
|
|
172
|
+
* monitoring, then runs the optional launcher function.
|
|
173
|
+
*
|
|
174
|
+
* The process title, PID, name, and `NODE_ENV` are logged at `info` level.
|
|
175
|
+
* The Node.js process options (`execArgv` and `NODE_OPTIONS`) are logged at
|
|
176
|
+
* `debug` level only, since they can reveal sensitive flags such as
|
|
177
|
+
* `--inspect=0.0.0.0` or `--require` paths.
|
|
178
|
+
*
|
|
179
|
+
* On `SIGINT`/`SIGTERM`, an uncaught exception, an unhandled rejection, or a
|
|
180
|
+
* launcher failure, `main` runs a shutdown sequence once:
|
|
181
|
+
*
|
|
182
|
+
* 1. The cause is logged (signals at `info`, failures at `error` level) and
|
|
183
|
+
* the memory monitoring stops.
|
|
184
|
+
* 2. The {@link MainOptions.shutdown} function, if any, runs for at most
|
|
185
|
+
* `shutdownTimeoutMs` (10 seconds by default). A failure or timeout is
|
|
186
|
+
* logged at `error` level.
|
|
187
|
+
* 3. The logs are flushed with {@link MainOptions.flushLogs} for at most
|
|
188
|
+
* `flushTimeoutMs` (3 seconds by default), so asynchronous sinks keep the
|
|
189
|
+
* final messages.
|
|
190
|
+
* 4. The process exits. A signal is re-raised, so the process ends as killed
|
|
191
|
+
* by it (exit status 130/143), which shells and supervisors such as
|
|
192
|
+
* systemd treat as a clean stop; if another listener for that signal
|
|
193
|
+
* exists, it exits with status `128 + signal number` instead. Fatal
|
|
194
|
+
* failures, and a failed or timed-out shutdown function, exit with
|
|
195
|
+
* status `1`.
|
|
196
|
+
*
|
|
197
|
+
* A second signal or fatal failure during the sequence exits immediately.
|
|
198
|
+
*
|
|
199
|
+
* Only one `main` call can be active at a time: calling it again before
|
|
200
|
+
* running the returned teardown function throws.
|
|
201
|
+
*
|
|
202
|
+
* @param name - Human-readable application name used in log output.
|
|
203
|
+
* @param logger - Logger instance used for all startup and lifecycle messages.
|
|
204
|
+
* @param options - Optional {@link MainOptions}.
|
|
205
|
+
* @returns A teardown function that removes the process handlers registered
|
|
206
|
+
* by this call and stops the memory monitoring, allowing `main` to be called
|
|
207
|
+
* again (e.g. in tests). It neither runs the shutdown function nor exits
|
|
208
|
+
* the process; calling it more than once is harmless.
|
|
209
|
+
* @throws {TypeError} If `options` is not an object, or `launcher`,
|
|
210
|
+
* `shutdown`, or `flushLogs` is not a function.
|
|
211
|
+
* @throws {Error} If another `main` call is still active.
|
|
212
|
+
* @throws {RangeError} If `monitorMemoryHours`, `shutdownTimeoutMs`, or
|
|
213
|
+
* `flushTimeoutMs` is out of range. Nothing is registered in that case.
|
|
214
|
+
*
|
|
215
|
+
* @example Without options:
|
|
216
|
+
* ```ts
|
|
217
|
+
* main("my-app", logger)
|
|
218
|
+
* ```
|
|
219
|
+
*
|
|
220
|
+
* @example With an async launcher and memory monitoring every 2 hours:
|
|
221
|
+
* ```ts
|
|
222
|
+
* main("my-app", logger, {
|
|
223
|
+
* launcher: async () => {
|
|
224
|
+
* await connectToDatabase()
|
|
225
|
+
* startServer()
|
|
226
|
+
* },
|
|
227
|
+
* monitorMemoryHours: 2,
|
|
228
|
+
* })
|
|
229
|
+
* ```
|
|
230
|
+
*
|
|
231
|
+
* @example With graceful shutdown of the application's resources:
|
|
232
|
+
* ```ts
|
|
233
|
+
* let server: Server | undefined
|
|
234
|
+
* main("my-app", logger, {
|
|
235
|
+
* launcher: async () => {
|
|
236
|
+
* await connectToDatabase()
|
|
237
|
+
* server = startServer()
|
|
238
|
+
* },
|
|
239
|
+
* shutdown: async () => {
|
|
240
|
+
* await server?.close()
|
|
241
|
+
* await disconnectFromDatabase()
|
|
242
|
+
* },
|
|
243
|
+
* shutdownTimeoutMs: 15_000,
|
|
244
|
+
* })
|
|
245
|
+
* ```
|
|
246
|
+
*/
|
|
247
|
+
export function main(
|
|
248
|
+
name: string,
|
|
249
|
+
logger: Logger,
|
|
250
|
+
options?: MainOptions,
|
|
251
|
+
): () => void {
|
|
252
|
+
// Rejects the positional arguments removed in 0.11.0 (e.g. a launcher
|
|
253
|
+
// function) from untyped callers, instead of silently ignoring them.
|
|
254
|
+
if (
|
|
255
|
+
options !== undefined &&
|
|
256
|
+
(typeof options !== "object" || options === null)
|
|
257
|
+
) {
|
|
258
|
+
throw new TypeError(
|
|
259
|
+
`main: "options" must be a MainOptions object, received ${options === null ? "null" : typeof options}`,
|
|
260
|
+
)
|
|
261
|
+
}
|
|
262
|
+
const {
|
|
263
|
+
launcher,
|
|
264
|
+
shutdown,
|
|
265
|
+
shutdownTimeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS,
|
|
266
|
+
monitorMemoryHours = 0,
|
|
267
|
+
defaultInterruptionHandler = true,
|
|
268
|
+
flushLogs = dispose,
|
|
269
|
+
flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS,
|
|
270
|
+
} = options ?? {}
|
|
271
|
+
|
|
272
|
+
assertOptionalFunction("launcher", launcher)
|
|
273
|
+
assertOptionalFunction("shutdown", shutdown)
|
|
274
|
+
assertOptionalFunction("flushLogs", flushLogs)
|
|
275
|
+
if (!Number.isFinite(monitorMemoryHours) || monitorMemoryHours < 0) {
|
|
276
|
+
throw new RangeError(
|
|
277
|
+
`main: "monitorMemoryHours" must be 0 (disabled) or a positive finite number, received ${monitorMemoryHours}`,
|
|
278
|
+
)
|
|
279
|
+
}
|
|
280
|
+
assertTimeout("shutdownTimeoutMs", shutdownTimeoutMs)
|
|
281
|
+
assertTimeout("flushTimeoutMs", flushTimeoutMs)
|
|
282
|
+
if (active) {
|
|
283
|
+
throw new Error(
|
|
284
|
+
"main: already active; call the teardown function returned by the previous main() call first",
|
|
285
|
+
)
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const __logger = logger.getChild(["main"])
|
|
289
|
+
|
|
290
|
+
__logger.info`Main process launched [${title} :: ${pid}]`
|
|
291
|
+
__logger.info`Process name: ${name}`
|
|
292
|
+
__logger.info`Node.js environment: ${env["NODE_ENV"] ?? ""}`
|
|
293
|
+
__logger.debug`Node.js process options: ${execArgv.concat(env["NODE_OPTIONS"] ?? []).join(" | ")}`
|
|
294
|
+
|
|
295
|
+
// Started before any handler is registered, since it validates the hours
|
|
296
|
+
// further and may throw.
|
|
297
|
+
const stopMonitoring =
|
|
298
|
+
monitorMemoryHours > 0
|
|
299
|
+
? monitorMemory(__logger, monitorMemoryHours)
|
|
300
|
+
: undefined
|
|
301
|
+
|
|
302
|
+
// A second signal or failure during the shutdown sequence exits at once.
|
|
303
|
+
let shuttingDown = false
|
|
304
|
+
|
|
305
|
+
/** Runs the shutdown sequence, then `exit` (or status `1` on failure). */
|
|
306
|
+
const shutDown = async (
|
|
307
|
+
context: ShutdownContext,
|
|
308
|
+
exit: () => void,
|
|
309
|
+
): Promise<void> => {
|
|
310
|
+
if (shuttingDown) {
|
|
311
|
+
exit()
|
|
312
|
+
return
|
|
313
|
+
}
|
|
314
|
+
shuttingDown = true
|
|
315
|
+
stopMonitoring?.()
|
|
316
|
+
|
|
317
|
+
let cleanupFailed = false
|
|
318
|
+
if (shutdown !== undefined) {
|
|
319
|
+
const outcome = await runBounded(
|
|
320
|
+
() => shutdown(context),
|
|
321
|
+
shutdownTimeoutMs,
|
|
322
|
+
)
|
|
323
|
+
if (outcome.status === "rejected") {
|
|
324
|
+
cleanupFailed = true
|
|
325
|
+
__logger.error`Shutdown function failed: ${describe(outcome.reason)}`
|
|
326
|
+
} else if (outcome.status === "timeout") {
|
|
327
|
+
cleanupFailed = true
|
|
328
|
+
__logger.error`Shutdown function timed out after ${shutdownTimeoutMs} ms`
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Best effort: flush failures and timeouts are ignored.
|
|
333
|
+
await runBounded(flushLogs, flushTimeoutMs)
|
|
334
|
+
|
|
335
|
+
if (cleanupFailed) {
|
|
336
|
+
process.exit(1)
|
|
337
|
+
} else {
|
|
338
|
+
exit()
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const removeListeners: (() => void)[] = []
|
|
343
|
+
|
|
344
|
+
if (defaultInterruptionHandler) {
|
|
345
|
+
for (const signal of ["SIGINT", "SIGTERM"] as const) {
|
|
346
|
+
const onSignal = (): Promise<void> => {
|
|
347
|
+
__logger.info`Process interrupted. Received signal: ${signal}`
|
|
348
|
+
return shutDown({ reason: "signal", signal }, () => {
|
|
349
|
+
// Re-raise the signal so the process ends as killed by it,
|
|
350
|
+
// unless another listener would intercept it.
|
|
351
|
+
process.off(signal, onSignal)
|
|
352
|
+
if (process.listenerCount(signal) === 0) {
|
|
353
|
+
process.kill(pid, signal)
|
|
354
|
+
} else {
|
|
355
|
+
process.exit(128 + constants.signals[signal])
|
|
356
|
+
}
|
|
357
|
+
})
|
|
358
|
+
}
|
|
359
|
+
process.on(signal, onSignal)
|
|
360
|
+
removeListeners.push(() => process.off(signal, onSignal))
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const exitWithFailure = (): void => {
|
|
365
|
+
process.exit(1)
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const onUncaughtException = (
|
|
369
|
+
error: Error,
|
|
370
|
+
origin: NodeJS.UncaughtExceptionOrigin,
|
|
371
|
+
): Promise<void> => {
|
|
372
|
+
__logger.error`Uncaught exception: ${describe(error)}`
|
|
373
|
+
__logger.error`Exception origin: ${origin}`
|
|
374
|
+
return shutDown(
|
|
375
|
+
{ reason: "error", source: "uncaughtException", error },
|
|
376
|
+
exitWithFailure,
|
|
377
|
+
)
|
|
378
|
+
}
|
|
379
|
+
process.on("uncaughtException", onUncaughtException)
|
|
380
|
+
removeListeners.push(() =>
|
|
381
|
+
process.off("uncaughtException", onUncaughtException),
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
const onUnhandledRejection = (reason: unknown): Promise<void> => {
|
|
385
|
+
__logger.error`Unhandled promise rejection. Reason:\n${describe(reason)}`
|
|
386
|
+
return shutDown(
|
|
387
|
+
{ reason: "error", source: "unhandledRejection", error: reason },
|
|
388
|
+
exitWithFailure,
|
|
389
|
+
)
|
|
390
|
+
}
|
|
391
|
+
process.on("unhandledRejection", onUnhandledRejection)
|
|
392
|
+
removeListeners.push(() =>
|
|
393
|
+
process.off("unhandledRejection", onUnhandledRejection),
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
active = true
|
|
397
|
+
let tornDown = false
|
|
398
|
+
const teardown = (): void => {
|
|
399
|
+
if (tornDown) {
|
|
400
|
+
return
|
|
401
|
+
}
|
|
402
|
+
tornDown = true
|
|
403
|
+
stopMonitoring?.()
|
|
404
|
+
for (const remove of removeListeners) {
|
|
405
|
+
remove()
|
|
406
|
+
}
|
|
407
|
+
active = false
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const onLauncherFailure = (error: unknown): Promise<void> => {
|
|
411
|
+
__logger.error`Launcher failed: ${describe(error)}`
|
|
412
|
+
return shutDown(
|
|
413
|
+
{ reason: "error", source: "launcher", error },
|
|
414
|
+
exitWithFailure,
|
|
415
|
+
)
|
|
416
|
+
}
|
|
417
|
+
try {
|
|
418
|
+
const result = launcher?.()
|
|
419
|
+
if (result !== undefined) {
|
|
420
|
+
Promise.resolve(result).catch(onLauncherFailure)
|
|
421
|
+
}
|
|
422
|
+
} catch (error) {
|
|
423
|
+
void onLauncherFailure(error)
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
return teardown
|
|
427
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { memoryUsage, uptime } from "node:process"
|
|
2
2
|
import type { Logger } from "@logtape/logtape"
|
|
3
|
-
import { millisecondsToString } from "
|
|
3
|
+
import { millisecondsToString } from "../core/millisecondsToString.ts"
|
|
4
4
|
|
|
5
5
|
/** Shortest allowed reporting interval: one minute. */
|
|
6
6
|
const MIN_DELAY_MS = 60 * 1_000
|
|
@@ -33,13 +33,11 @@ const MAX_DELAY_MS = 2_147_483_647
|
|
|
33
33
|
*
|
|
34
34
|
* @param logger - Logger whose `"monitorMemory"` child emits the memory
|
|
35
35
|
* reports.
|
|
36
|
-
* @param hours - Interval between reports in hours
|
|
37
|
-
*
|
|
38
|
-
* delay `setInterval` supports). Defaults to `24`.
|
|
36
|
+
* @param hours - Interval between reports in hours, from `1 / 60` (one
|
|
37
|
+
* minute) to about `596.5` (2³¹ − 1 ms). Defaults to `24`.
|
|
39
38
|
* @returns A function that stops the monitoring. Calling it more than once is
|
|
40
39
|
* harmless.
|
|
41
|
-
* @throws {RangeError} If `hours` is not finite or
|
|
42
|
-
* shorter than one minute or longer than 2³¹ − 1 milliseconds.
|
|
40
|
+
* @throws {RangeError} If `hours` is not finite or out of that range.
|
|
43
41
|
*
|
|
44
42
|
* @example
|
|
45
43
|
* ```ts
|
|
@@ -82,7 +80,6 @@ export function monitorMemory(logger: Logger, hours: number = 24): () => void {
|
|
|
82
80
|
{ rss, heapTotal, heapUsed, external },
|
|
83
81
|
)
|
|
84
82
|
}, delay)
|
|
85
|
-
// Monitoring alone must not keep the process alive.
|
|
86
83
|
timer.unref()
|
|
87
84
|
|
|
88
85
|
return () => clearInterval(timer)
|