@blamejs/core 0.10.7 → 0.10.8

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.
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ /**
3
+ * @module b.promisePool
4
+ * @nav Async
5
+ * @title Promise Pool
6
+ *
7
+ * @intro
8
+ * Bounded-concurrency task runner for promise-returning work — the
9
+ * common gap between `b.workerPool` (worker_threads for CPU-bound
10
+ * work) and `b.queue` (durable cross-process messaging). Wraps the
11
+ * typical "I have N parallel I/O fan-outs and want at most K in
12
+ * flight at any moment" pattern with back-pressure on enqueue
13
+ * (so the caller can't out-run the worker side) and a clean drain
14
+ * path that composes with `b.appShutdown`.
15
+ *
16
+ * Two enqueue paths:
17
+ *
18
+ * - `pool.run(taskFn)` returns a Promise that resolves to the
19
+ * task's return value (or rejects with the task's error). When
20
+ * the pool is at capacity, `run` waits until a slot frees
21
+ * BEFORE the task starts — back-pressure is part of the
22
+ * contract, not an opt.
23
+ *
24
+ * - `pool.fire(taskFn)` is the synchronous-enqueue variant for
25
+ * fan-out from non-async contexts. Returns the same Promise
26
+ * but the call itself can't await — useful inside event
27
+ * handlers that fire-and-forget.
28
+ *
29
+ * Drain semantics: `pool.drain()` resolves when every queued and
30
+ * in-flight task settles. Callers wire this into shutdown via
31
+ * `b.appShutdown.create({ priority: 50, run: () => pool.drain() })`
32
+ * so the process doesn't tear down with work mid-flight.
33
+ *
34
+ * The pool does NOT retry failed tasks; rejection of a task's
35
+ * promise is the caller's signal. Operators that want retry compose
36
+ * `b.retry.withRetry` inside the task body.
37
+ *
38
+ * @card
39
+ * Bounded-concurrency promise pool — back-pressure on enqueue, drain-on-shutdown, no hidden retry. The thing every consumer reaches for p-limit for.
40
+ */
41
+
42
+ var validateOpts = require("./validate-opts");
43
+ var numericBounds = require("./numeric-bounds");
44
+ var { defineClass } = require("./framework-error");
45
+
46
+ var PromisePoolError = defineClass("PromisePoolError", { alwaysPermanent: true });
47
+
48
+ var MAX_CONCURRENCY = 65536; // allow:raw-byte-literal — uint16 ceiling on parallel I/O fan-out
49
+
50
+ /**
51
+ * @primitive b.promisePool.create
52
+ * @signature b.promisePool.create(opts)
53
+ * @since 0.10.8
54
+ * @status stable
55
+ * @related b.workerPool.create, b.appShutdown.create, b.retry.withRetry
56
+ *
57
+ * Build a bounded-concurrency pool. Returns
58
+ * `{ run, fire, drain, size, inFlight, queued, closed }`. The pool is
59
+ * closed via `drain({ close: true })`; subsequent enqueues throw.
60
+ *
61
+ * @opts
62
+ * concurrency: number, // required; integer in [1, 65536]
63
+ * queueLimit: number, // default Infinity; once exceeded, enqueue throws
64
+ *
65
+ * @example
66
+ * var pool = b.promisePool.create({ concurrency: 8 });
67
+ * var results = await Promise.all(items.map(function (item) {
68
+ * return pool.run(function () { return fetchOne(item); });
69
+ * }));
70
+ * await pool.drain({ close: true });
71
+ */
72
+ function create(opts) {
73
+ validateOpts.requireObject(opts, "b.promisePool.create",
74
+ PromisePoolError, "promise-pool/bad-opts");
75
+ numericBounds.requirePositiveFiniteIntIfPresent(opts.concurrency,
76
+ "b.promisePool.create: concurrency", PromisePoolError, "promise-pool/bad-concurrency");
77
+ if (opts.concurrency === undefined || opts.concurrency > MAX_CONCURRENCY) {
78
+ throw new PromisePoolError("promise-pool/bad-concurrency",
79
+ "b.promisePool.create: concurrency must be an integer in [1, " +
80
+ MAX_CONCURRENCY + "] (got " + opts.concurrency + ")");
81
+ }
82
+ var queueLimit = opts.queueLimit === undefined ? Infinity : opts.queueLimit;
83
+ if (queueLimit !== Infinity) {
84
+ numericBounds.requirePositiveFiniteIntIfPresent(queueLimit + 1,
85
+ "b.promisePool.create: queueLimit (must be non-negative int)", PromisePoolError,
86
+ "promise-pool/bad-queue-limit");
87
+ }
88
+ var concurrency = opts.concurrency;
89
+ var inFlight = 0;
90
+ var queue = []; // FIFO of pending { taskFn, resolve, reject }
91
+ var drainWaiters = [];
92
+ var closed = false;
93
+
94
+ function _pump() {
95
+ while (inFlight < concurrency && queue.length > 0) {
96
+ var slot = queue.shift();
97
+ inFlight += 1;
98
+ Promise.resolve().then(function () { return slot.taskFn(); })
99
+ .then(function (val) { slot.resolve(val); _settle(); })
100
+ .catch(function (err) { slot.reject(err); _settle(); });
101
+ }
102
+ if (inFlight === 0 && queue.length === 0 && drainWaiters.length > 0) {
103
+ var waiters = drainWaiters.slice();
104
+ drainWaiters.length = 0;
105
+ for (var i = 0; i < waiters.length; i += 1) waiters[i]();
106
+ }
107
+ }
108
+
109
+ function _settle() {
110
+ inFlight -= 1;
111
+ _pump();
112
+ }
113
+
114
+ function _enqueue(taskFn) {
115
+ if (typeof taskFn !== "function") {
116
+ throw new PromisePoolError("promise-pool/bad-task",
117
+ "b.promisePool: task must be a function returning a value or Promise");
118
+ }
119
+ if (closed) {
120
+ throw new PromisePoolError("promise-pool/closed",
121
+ "b.promisePool: pool is closed (drain({close:true}) was called)");
122
+ }
123
+ if (queue.length >= queueLimit) {
124
+ throw new PromisePoolError("promise-pool/queue-full",
125
+ "b.promisePool: queueLimit=" + queueLimit + " reached");
126
+ }
127
+ return new Promise(function (resolve, reject) {
128
+ queue.push({ taskFn: taskFn, resolve: resolve, reject: reject });
129
+ _pump();
130
+ });
131
+ }
132
+
133
+ function run(taskFn) { return _enqueue(taskFn); }
134
+ function fire(taskFn) { return _enqueue(taskFn); }
135
+
136
+ function drain(drainOpts) {
137
+ drainOpts = drainOpts || {};
138
+ return new Promise(function (resolve) {
139
+ function _done() {
140
+ if (drainOpts.close === true) closed = true;
141
+ resolve();
142
+ }
143
+ if (inFlight === 0 && queue.length === 0) { _done(); return; }
144
+ drainWaiters.push(_done);
145
+ });
146
+ }
147
+
148
+ return {
149
+ run: run,
150
+ fire: fire,
151
+ drain: drain,
152
+ size: function () { return concurrency; },
153
+ inFlight: function () { return inFlight; },
154
+ queued: function () { return queue.length; },
155
+ closed: function () { return closed; },
156
+ };
157
+ }
158
+
159
+ module.exports = {
160
+ create: create,
161
+ PromisePoolError: PromisePoolError,
162
+ };
@@ -0,0 +1,269 @@
1
+ "use strict";
2
+ /**
3
+ * @module b.sdNotify
4
+ * @nav Process
5
+ * @title systemd Notify
6
+ *
7
+ * @intro
8
+ * `sd_notify` protocol surface for daemons running under
9
+ * `Type=notify` systemd units. Composes the standard lifecycle
10
+ * messages — `READY=1` on boot, `WATCHDOG=1` on heartbeat,
11
+ * `STOPPING=1` on shutdown, `RELOADING=1` on hot-reload — against
12
+ * the `$NOTIFY_SOCKET` env var systemd populates for the child
13
+ * process.
14
+ *
15
+ * Transport: Node has no unix-DGRAM socket support in its `dgram`
16
+ * module, so the v1 path shells out to `systemd-notify(1)` via
17
+ * `execFile` (NOT `exec` — no shell-string parsing on the
18
+ * message bytes). Operators running under systemd already have
19
+ * `systemd-tools` installed by definition, so the dependency is
20
+ * no expansion of the trust surface.
21
+ *
22
+ * Compose with `b.appShutdown` for the STOPPING signal: register a
23
+ * priority-0 phase that calls `b.sdNotify.stopping()` so systemd
24
+ * sees the shutdown intent before the framework tears anything
25
+ * down. Compose with a periodic `WATCHDOG=1` against the unit's
26
+ * `WatchdogSec=` interval so systemd auto-restarts the daemon if
27
+ * the event loop wedges.
28
+ *
29
+ * When `$NOTIFY_SOCKET` is unset (process running outside systemd
30
+ * — bare invocation, foreground dev, container without
31
+ * `--notify-ready`), every call is a no-op that surfaces a single
32
+ * boot-time audit entry. Operators get observability of the
33
+ * degraded state without per-call log noise.
34
+ *
35
+ * @card
36
+ * sd_notify protocol for systemd Type=notify daemons — READY / WATCHDOG / STOPPING / RELOADING. Composes b.appShutdown for shutdown signaling.
37
+ */
38
+
39
+ var { execFile } = require("node:child_process");
40
+ var C = require("./constants");
41
+ var safeEnv = require("./parsers/safe-env");
42
+ var audit = require("./audit");
43
+ var { defineClass } = require("./framework-error");
44
+
45
+ var SdNotifyError = defineClass("SdNotifyError", { alwaysPermanent: true });
46
+
47
+ // Whitelist of sd_notify state= values we ship as named helpers. The
48
+ // underlying `send({ state })` accepts any string but the helpers are
49
+ // the operator-facing surface — `READY=1` etc. — and the audit log
50
+ // records the named state, not arbitrary payload bytes.
51
+ var KNOWN_STATES = Object.freeze({
52
+ ready: "READY=1",
53
+ stopping: "STOPPING=1",
54
+ reloading: "RELOADING=1",
55
+ watchdog: "WATCHDOG=1",
56
+ });
57
+
58
+ function _notifySocketPath() {
59
+ var p = safeEnv.readVar("NOTIFY_SOCKET");
60
+ if (typeof p !== "string" || p.length === 0) return null;
61
+ // Abstract namespace socket (Linux-only) prefixed with `@` —
62
+ // systemd-notify(1) accepts the same form, so we don't normalize.
63
+ return p;
64
+ }
65
+
66
+ function _runNotify(payload) {
67
+ return new Promise(function (resolve, reject) {
68
+ var args = [];
69
+ var lines = String(payload).split("\n");
70
+ for (var i = 0; i < lines.length; i += 1) {
71
+ if (lines[i].length > 0) args.push(lines[i]);
72
+ }
73
+ if (args.length === 0) { resolve(); return; }
74
+ // execFile (not exec) — no shell evaluation; the message bytes
75
+ // pass through argv exactly. systemd-notify accepts one or more
76
+ // KEY=VALUE arguments. The `--no-block` flag returns immediately
77
+ // without waiting for the notification to be processed.
78
+ execFile("systemd-notify", ["--no-block"].concat(args),
79
+ { timeout: C.TIME.seconds(5), windowsHide: true },
80
+ function (err) {
81
+ if (err) reject(err);
82
+ else resolve();
83
+ });
84
+ });
85
+ }
86
+
87
+ /**
88
+ * @primitive b.sdNotify.send
89
+ * @signature b.sdNotify.send(opts)
90
+ * @since 0.10.8
91
+ * @status stable
92
+ * @related b.sdNotify.ready, b.sdNotify.stopping, b.appShutdown.create
93
+ *
94
+ * Generic sd_notify dispatch. Sends one or more `KEY=VALUE` payload
95
+ * lines to systemd via `systemd-notify(1)`. No-op when
96
+ * `$NOTIFY_SOCKET` is unset (foreground / container without
97
+ * `--notify-ready` / non-systemd init). Returns a Promise resolving
98
+ * on dispatch success.
99
+ *
100
+ * @opts
101
+ * state: string, // e.g. "READY=1" / "STOPPING=1"
102
+ * status: string, // free-form status text → `STATUS=`
103
+ * mainpid: number, // PID override → `MAINPID=`
104
+ * audit: boolean, // default true
105
+ *
106
+ * @example
107
+ * await b.sdNotify.send({ state: "READY=1", status: "Listening on :8080" });
108
+ */
109
+ function send(opts) {
110
+ opts = opts || {};
111
+ var lines = [];
112
+ if (typeof opts.state === "string" && opts.state.length > 0) lines.push(opts.state);
113
+ if (typeof opts.status === "string" && opts.status.length > 0) {
114
+ // STATUS= permits arbitrary UTF-8 except newline — refuse newline
115
+ // so a hostile status string can't smuggle a second key.
116
+ if (opts.status.indexOf("\n") !== -1 || opts.status.indexOf("\r") !== -1) {
117
+ throw new SdNotifyError("sd-notify/control-char-in-status",
118
+ "send: status field must not contain CR/LF (sd_notify framing)");
119
+ }
120
+ lines.push("STATUS=" + opts.status);
121
+ }
122
+ if (opts.mainpid !== undefined) {
123
+ if (typeof opts.mainpid !== "number" || !isFinite(opts.mainpid) ||
124
+ Math.floor(opts.mainpid) !== opts.mainpid || opts.mainpid < 1) {
125
+ throw new SdNotifyError("sd-notify/bad-mainpid",
126
+ "send: mainpid must be a positive integer");
127
+ }
128
+ lines.push("MAINPID=" + opts.mainpid);
129
+ }
130
+ if (lines.length === 0) return Promise.resolve();
131
+
132
+ var socketPath = _notifySocketPath();
133
+ if (socketPath === null) {
134
+ if (opts.audit !== false) {
135
+ try {
136
+ audit.safeEmit({
137
+ action: "sdnotify.send.skipped",
138
+ outcome: "denied",
139
+ metadata: { reason: "no-notify-socket", state: opts.state || null },
140
+ });
141
+ } catch (_e) { /* drop-silent */ }
142
+ }
143
+ return Promise.resolve();
144
+ }
145
+ var auditOn = opts.audit !== false;
146
+ return _runNotify(lines.join("\n")).then(function () {
147
+ if (auditOn) {
148
+ try {
149
+ audit.safeEmit({
150
+ action: "sdnotify.send",
151
+ outcome: "success",
152
+ metadata: { state: opts.state || null, status: opts.status || null },
153
+ });
154
+ } catch (_e) { /* drop-silent */ }
155
+ }
156
+ }).catch(function (err) {
157
+ if (auditOn) {
158
+ try {
159
+ audit.safeEmit({
160
+ action: "sdnotify.send",
161
+ outcome: "failure",
162
+ metadata: { state: opts.state || null, error: (err && err.message) || String(err) },
163
+ });
164
+ } catch (_e2) { /* drop-silent */ }
165
+ }
166
+ throw new SdNotifyError("sd-notify/dispatch-failed",
167
+ "send: systemd-notify dispatch failed: " + ((err && err.message) || String(err)));
168
+ });
169
+ }
170
+
171
+ /**
172
+ * @primitive b.sdNotify.ready
173
+ * @signature b.sdNotify.ready(opts?)
174
+ * @since 0.10.8
175
+ * @status stable
176
+ * @related b.sdNotify.send, b.sdNotify.stopping
177
+ *
178
+ * Send `READY=1` to systemd, signaling boot complete. Use once the
179
+ * listener is bound and the daemon is accepting work.
180
+ *
181
+ * @opts
182
+ * status: string, // free-form status text → STATUS=
183
+ *
184
+ * @opts
185
+ * status: string, // free-form status text → STATUS=
186
+ * audit: boolean, // default true
187
+ *
188
+ * @example
189
+ * await b.sdNotify.ready({ status: "Listening on :8080" });
190
+ */
191
+ function ready(opts) {
192
+ return send(Object.assign({}, opts || {}, { state: KNOWN_STATES.ready }));
193
+ }
194
+
195
+ /**
196
+ * @primitive b.sdNotify.stopping
197
+ * @signature b.sdNotify.stopping(opts?)
198
+ * @since 0.10.8
199
+ * @status stable
200
+ * @related b.sdNotify.send, b.appShutdown.create
201
+ *
202
+ * Send `STOPPING=1`. Operators wire this into `b.appShutdown` as the
203
+ * earliest shutdown phase (priority 0) so systemd sees the shutdown
204
+ * intent before any teardown begins.
205
+ *
206
+ * @opts
207
+ * status: string, // free-form status text → STATUS=
208
+ * audit: boolean, // default true
209
+ *
210
+ * @example
211
+ * b.appShutdown.create({ name: "sd-notify-stopping", priority: 0,
212
+ * run: function () { return b.sdNotify.stopping(); } });
213
+ */
214
+ function stopping(opts) {
215
+ return send(Object.assign({}, opts || {}, { state: KNOWN_STATES.stopping }));
216
+ }
217
+
218
+ /**
219
+ * @primitive b.sdNotify.reloading
220
+ * @signature b.sdNotify.reloading(opts?)
221
+ * @since 0.10.8
222
+ * @status stable
223
+ *
224
+ * Send `RELOADING=1` then (after the reload completes) `READY=1`.
225
+ * Use during hot-config-reload paths; systemd treats the unit as
226
+ * "reloading" until the next `READY=1`.
227
+ *
228
+ * @opts
229
+ * status: string, // free-form status text → STATUS=
230
+ * audit: boolean, // default true
231
+ *
232
+ * @example
233
+ * await b.sdNotify.reloading();
234
+ * await reloadConfig();
235
+ * await b.sdNotify.ready();
236
+ */
237
+ function reloading(opts) {
238
+ return send(Object.assign({}, opts || {}, { state: KNOWN_STATES.reloading }));
239
+ }
240
+
241
+ /**
242
+ * @primitive b.sdNotify.watchdog
243
+ * @signature b.sdNotify.watchdog(opts?)
244
+ * @since 0.10.8
245
+ * @status stable
246
+ *
247
+ * Send `WATCHDOG=1`. Operators with `WatchdogSec=` configured on
248
+ * their unit call this periodically (e.g. every `WatchdogSec/2`)
249
+ * so systemd auto-restarts the daemon when the event loop wedges.
250
+ *
251
+ * @opts
252
+ * audit: boolean, // default true
253
+ *
254
+ * @example
255
+ * setInterval(function () { b.sdNotify.watchdog(); }, 15000);
256
+ */
257
+ function watchdog(opts) {
258
+ return send(Object.assign({}, opts || {}, { state: KNOWN_STATES.watchdog }));
259
+ }
260
+
261
+ module.exports = {
262
+ send: send,
263
+ ready: ready,
264
+ stopping: stopping,
265
+ reloading: reloading,
266
+ watchdog: watchdog,
267
+ isAvailable: function () { return _notifySocketPath() !== null; },
268
+ SdNotifyError: SdNotifyError,
269
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/core",
3
- "version": "0.10.7",
3
+ "version": "0.10.8",
4
4
  "description": "The Node framework that owns its stack.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
package/sbom.cdx.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.6",
5
- "serialNumber": "urn:uuid:62b21ffc-fcde-4782-a950-d9b2db933f5c",
5
+ "serialNumber": "urn:uuid:2db3bd59-b835-4672-aac5-7c874f2f9276",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-05-17T20:52:27.570Z",
8
+ "timestamp": "2026-05-18T00:17:19.942Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -19,14 +19,14 @@
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/core@0.10.7",
22
+ "bom-ref": "@blamejs/core@0.10.8",
23
23
  "type": "library",
24
24
  "name": "blamejs",
25
- "version": "0.10.7",
25
+ "version": "0.10.8",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "The Node framework that owns its stack.",
29
- "purl": "pkg:npm/%40blamejs/core@0.10.7",
29
+ "purl": "pkg:npm/%40blamejs/core@0.10.8",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/core@0.10.7",
57
+ "ref": "@blamejs/core@0.10.8",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]