barebox 0.2.0 → 0.4.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/src/holds.js CHANGED
@@ -1,25 +1,111 @@
1
1
  // holds.js — the ONLY writer of the hold queue.
2
2
  //
3
- // A held request parks with its client socket open until a human approves,
4
- // denies, or the deadline / client / proxy goes away first. Approving a hold
5
- // whose client is gone must be impossible: `abandon()` removes the entry, so
6
- // a later `approve` answers `unknown <id>` and nothing is forwarded.
7
- import net from 'node:net';
3
+ // A held request parks with its client socket open until the ask channel
4
+ // answers. Two channels, one queue:
5
+ // - `onAsk(ask) -> Promise<{ decision, reason? }>` (bareguard's
6
+ // `humanChannel` shape): one promise per hold, no files involved.
7
+ // - the default file checkpoint: `<runtime>/asks/<id>.json` is written on
8
+ // park, and ONE interval per queue reads `<runtime>/answers/` once per
9
+ // tick (default 250 ms, PRD Q9), consuming each answer file (renamed away
10
+ // before reading). An answer for a held id settles it; anything else is
11
+ // stale: ignored, logged (`stale-answer`), removed.
12
+ // The deadline timer in `add()` is the only deadline: nothing else looks
13
+ // at the clock. Timeout — or any failure of the channel itself — is deny.
14
+ // A malformed answer (bad JSON, missing/unknown decision) is ignored,
15
+ // logged (`malformed-answer`), and removed; the hold keeps waiting until
16
+ // the deadline. The queue never throws on channel input: everything
17
+ // unexpected is loud in the log and eventually a deny.
18
+ //
19
+ // Decisions enter through one `normalizeDecision` (`allow`/`deny`, with
20
+ // `'approve'` accepted as an alias of `'allow'` in answer files only) and
21
+ // are reported through one optional `onEvent` callback: `{ type: 'ask' }`
22
+ // when a hold parks, `{ type: 'decided' }` when it settles or is abandoned
23
+ // (`deny` / `client gone`). Outcomes are
24
+ // reported, never reconstructed: `run()` and `sbx run` build their ask
25
+ // records from these events. The library never writes to stdout or stderr.
26
+ //
27
+ // Approving a hold whose client is gone must be impossible: `abandon()`
28
+ // removes the entry and its ask file, so a later answer is stale and
29
+ // nothing is forwarded.
30
+ //
31
+ // Ask payload (`asks/<id>.json`): `id`, `agent`, `method`, `url`, `rule`
32
+ // (the hold-reason string), `letter`, `bodyPreview` + `truncated`,
33
+ // `waitingSec` (0 at park; readers use the file mtime for a live value),
34
+ // `expiresAt` (ISO-8601 UTC string, or null when `timeoutMs: 'never'`).
35
+ // `letter` is `'x'` for every parked ask: letters are M3's job (rwxmap +
36
+ // bareguard) — the queue only parks what the decision function flags, and
37
+ // everything flagged today is irreversible. Headers are excluded from the
38
+ // payload (they carry Authorization secrets); the body preview is capped at
39
+ // ASK_BODY_LIMIT bytes but otherwise verbatim — M3's bareguard `secrets`
40
+ // redaction takes over redaction there.
41
+ //
42
+ // Answer payload (`answers/<id>.json`): `{ decision: 'allow' | 'deny',
43
+ // reason? }`. `'approve'` is accepted as an alias of `'allow'`. Writers
44
+ // must write atomically (tmp file + rename); readers never see partials.
8
45
  import fs from 'node:fs';
46
+ import path from 'node:path';
47
+ import { ensurePrivateDir, runtimePaths } from './runtime.js';
48
+
49
+ /** Body preview cap for `asks/<id>.json` (bytes). */
50
+ export const ASK_BODY_LIMIT = 4096;
51
+
52
+ /** Default answer poll interval in ms (PRD Q9). */
53
+ export const DEFAULT_POLL_MS = 250;
54
+
55
+ /** At most this many held requests wait in line per agent; the next is refused. */
56
+ const MAX_WAITING_PER_AGENT = 16;
9
57
 
10
58
  /**
11
59
  * A parked request, as returned by {@link pending}. Plain objects only —
12
- * the queue itself never leaves this module.
60
+ * the queue itself never leaves this module. No body: returning whole 1 MB
61
+ * bodies from a status call is never needed, and the ask payload in
62
+ * `asks/<id>.json` carries the preview.
13
63
  *
14
64
  * @typedef {object} HeldRequest
15
65
  * @property {string} id hold id (`h<n>`)
16
66
  * @property {string} agent agent name (its socket), never `c<n>`
17
67
  * @property {string} method HTTP method
18
68
  * @property {string} url full URL
19
- * @property {string} body request body so far (utf8)
69
+ * @property {string} rule hold-reason string from the decision function
20
70
  * @property {number} waitingSec seconds since the hold parked
21
71
  */
22
72
 
73
+ /**
74
+ * A queue event, as delivered to the `onEvent` callback: `{ type: 'ask' }`
75
+ * when a hold parks, `{ type: 'decided' }` when it settles or its client
76
+ * goes away (`deny` / `client gone`): every ask ends in exactly one.
77
+ *
78
+ * @typedef {{ type: 'ask', ask: AskPayload } | { type: 'decided', id: string, decision: 'allow' | 'deny', reason?: string }} HoldEvent
79
+ */
80
+
81
+ /**
82
+ * Queue event callback.
83
+ *
84
+ * @typedef {(e: HoldEvent) => void} OnEvent
85
+ */
86
+
87
+ /**
88
+ * The decision-ready ask written to `asks/<id>.json`.
89
+ *
90
+ * @typedef {object} AskPayload
91
+ * @property {string} id hold id (`h<n>`)
92
+ * @property {string} agent agent name (its socket)
93
+ * @property {string} method HTTP method
94
+ * @property {string} url full URL
95
+ * @property {string} rule hold-reason string from the decision function
96
+ * @property {string} letter always `'x'` until M3 owns letters
97
+ * @property {string} bodyPreview request body preview, utf8, capped at ASK_BODY_LIMIT bytes
98
+ * @property {boolean} truncated true when the body exceeded ASK_BODY_LIMIT
99
+ * @property {number} waitingSec 0 at park; readers use the file mtime for a live value
100
+ * @property {string|null} expiresAt ISO-8601 UTC deadline, or null when `timeoutMs: 'never'`
101
+ */
102
+
103
+ /**
104
+ * Decide a parked ask. Resolves `{ decision: 'allow' | 'deny', reason? }`.
105
+ *
106
+ * @typedef {(ask: AskPayload) => Promise<{ decision: string, reason?: string }>} OnAsk
107
+ */
108
+
23
109
  /**
24
110
  * Decide whether a request parks. Return a human-readable reason, or null
25
111
  * to forward. M3 plugs the rwxmap + bareguard classifier into this one seam.
@@ -28,7 +114,102 @@ import fs from 'node:fs';
28
114
  */
29
115
 
30
116
  /**
31
- * Create the hold queue.
117
+ * Atomic write: tmp file + rename, so readers never see a partial payload.
118
+ *
119
+ * @param {string} file destination path
120
+ * @param {string} text content
121
+ * @returns {void}
122
+ */
123
+ export function writeFileAtomic(file, text) {
124
+ fs.mkdirSync(path.dirname(file), { recursive: true });
125
+ const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
126
+ // 0600, not the 0644 default: asks carry the audit trail and unredacted
127
+ // body previews, and answers carry the decision. (Umask can only remove
128
+ // bits from 0600, never add group/other access.)
129
+ fs.writeFileSync(tmp, text, { mode: 0o600 });
130
+ fs.renameSync(tmp, file);
131
+ }
132
+
133
+ let consumeN = 0;
134
+
135
+ /**
136
+ * Consume a file exactly once: rename it away, then read and unlink the
137
+ * renamed copy. Returns null when there is nothing to consume.
138
+ *
139
+ * @param {string} file path to consume
140
+ * @returns {string|null} content, `''` when the renamed copy is unreadable, null when absent
141
+ */
142
+ function consumeFile(file) {
143
+ const tmp = `${file}.consumed-${process.pid}-${++consumeN}`;
144
+ try {
145
+ fs.renameSync(file, tmp);
146
+ } catch {
147
+ return null;
148
+ }
149
+ let text = '';
150
+ try {
151
+ text = fs.readFileSync(tmp, 'utf8');
152
+ } catch {}
153
+ try {
154
+ fs.unlinkSync(tmp);
155
+ } catch {}
156
+ return text;
157
+ }
158
+
159
+ /**
160
+ * Validate an answer payload's shape. Returns the raw decision pair;
161
+ * normalization (including the `'approve'` alias) is `normalizeDecision`'s
162
+ * job. Anything unparsable, or with a missing decision, is malformed.
163
+ *
164
+ * @param {string} text raw answer file content
165
+ * @returns {{ decision: unknown, reason?: unknown } | null} raw pair, or null when malformed
166
+ */
167
+ function parseAnswer(text) {
168
+ let obj;
169
+ try {
170
+ obj = JSON.parse(text);
171
+ } catch {
172
+ return null;
173
+ }
174
+ if (!obj || typeof obj !== 'object') return null;
175
+ const { decision, reason } = /** @type {{ decision?: unknown, reason?: unknown }} */ (obj);
176
+ if (typeof decision !== 'string' || !decision) return null;
177
+ return { decision, reason };
178
+ }
179
+
180
+ /**
181
+ * The one normalization of decisions, applied once wherever a decision
182
+ * enters (an answer file, or an `onAsk` result). The audit log speaks
183
+ * `allow`/`deny`, which is bareguard's vocabulary.
184
+ *
185
+ * @param {{ decision?: unknown, reason?: unknown } | null} input raw decision pair
186
+ * @param {object} [opts]
187
+ * @param {boolean} [opts.approveAlias] accept `'approve'` as an alias of `'allow'` (answer files only)
188
+ * @returns {{ decision: 'allow' | 'deny', reason?: string } | null} normalized, or null when not a decision at all
189
+ */
190
+ export function normalizeDecision(input, { approveAlias = false } = {}) {
191
+ const decision = input?.decision;
192
+ if (decision === 'allow' || (approveAlias && decision === 'approve')) {
193
+ return { decision: 'allow' };
194
+ }
195
+ if (decision === 'deny') {
196
+ const reason = input?.reason;
197
+ return {
198
+ decision: 'deny',
199
+ reason: typeof reason === 'string' && reason ? reason : 'denied',
200
+ };
201
+ }
202
+ return null;
203
+ }
204
+
205
+ /**
206
+ * Create the hold queue. One queue per runtime, enforced by `claimRuntime`
207
+ * in `createProxy` (a second live proxy on the same runtime never starts):
208
+ * on the file channel the queue owns `asks/` and `answers/` for its
209
+ * runtime, clearing both at start and removing its asks on close, so no
210
+ * answer outlives its queue. One parked request per agent: `reserve` hands
211
+ * out the agent's hold slot before a held body is read, and the slot passes
212
+ * to the next waiter when the parked entry leaves by any path.
32
213
  *
33
214
  * @param {object} opts
34
215
  * @param {(o: Record<string, unknown>) => void} opts.log audit-log writer
@@ -36,75 +217,378 @@ import fs from 'node:fs';
36
217
  * @param {string} [opts.match] path substring that parks a request (default impl when `shouldHold` is absent)
37
218
  * @param {number|string} [opts.timeoutMs] hold deadline in ms, or `'never'` (default 120000)
38
219
  * @param {number} [opts.maxBody] bodies over this are denied at the door, never queued (default 1048576)
39
- * @param {string|null} [opts.controlSocket] unix socket path for `pending | approve | deny`
220
+ * @param {string|null} [opts.runtime] runtime dir; required for the default file checkpoint (writes `asks/`, polls `answers/`)
221
+ * @param {OnAsk|null} [opts.onAsk] ask seam (bareguard `humanChannel` shape); when present no files are involved
222
+ * @param {number} [opts.pollMs] answer poll interval in ms for the default file checkpoint (default 250, PRD Q9)
223
+ * @param {OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon
40
224
  * @param {(entry: object) => void} opts.onApprove forward the parked request upstream
41
225
  * @param {(entry: object, reason: string) => void} opts.onDeny refuse the parked request
42
- * @returns {{ add: (entry: object) => string, decide: (req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null, approve: (id: string) => string, deny: (id: string, reason: string) => string, abandon: (id: string) => void, abandonSocket: (sock: object) => void, pending: () => HeldRequest[], size: () => number, close: () => void }} queue handle
226
+ * @returns {{ add: (entry: object) => string|null, reserve: (agent: string, cbs: { onReady: () => void, onExpire: (reason: string) => void }) => { state: 'now'|'queued'|'full', arrivedAt: number, cancel: () => void }, decide: (req: { agent: string, method: string, url: string, headers: Record<string, string | string[] | undefined> }) => string | null, abandon: (id: string) => void, abandonSocket: (sock: object) => void, pending: () => HeldRequest[], close: () => void }} queue handle
43
227
  */
44
228
  export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
45
- maxBody = 1048576, controlSocket = null, onApprove, onDeny }) {
46
- const decide = shouldHold
47
- ?? ((req) => (match && new URL(req.url).pathname.includes(match) ? `path matches ${match}` : null));
229
+ maxBody = 1048576, runtime = null, onAsk = null, pollMs = DEFAULT_POLL_MS,
230
+ onEvent = null, onApprove, onDeny }) {
231
+ // The default IS matchPath: one definition of the path-substring rule (see below).
232
+ const decide = shouldHold ?? (match ? matchPath(match) : () => null);
48
233
  /** @returns {number|null} */
49
234
  const deadlineMs = () => {
50
235
  if (timeoutMs === 'never') return null;
51
236
  const ms = timeoutMs ?? 120000;
52
237
  return typeof ms === 'number' && Number.isFinite(ms) && ms >= 0 ? ms : 120000;
53
238
  };
239
+ if (onAsk != null && typeof onAsk !== 'function') {
240
+ throw new Error('createHolds: onAsk must be a function');
241
+ }
242
+ if (onEvent != null && typeof onEvent !== 'function') {
243
+ throw new Error('createHolds: onEvent must be a function');
244
+ }
245
+ const poll = typeof pollMs === 'number' && Number.isFinite(pollMs) && pollMs > 0
246
+ ? pollMs
247
+ : DEFAULT_POLL_MS;
248
+ // Custom onAsk owns decisions with no files involved; the default IS the
249
+ // file checkpoint and needs a runtime dir for asks/ + answers/.
250
+ const useFiles = onAsk == null;
251
+ if (useFiles && !runtime) {
252
+ throw new Error('createHolds: runtime is required for the default file checkpoint (or pass onAsk)');
253
+ }
254
+ const paths = runtime ? runtimePaths(runtime) : null;
255
+ if (paths) {
256
+ ensurePrivateDir(paths.asksDir);
257
+ ensurePrivateDir(paths.answersDir);
258
+ }
259
+ // A dead queue's leftovers must never decide the next queue's holds
260
+ // (ids restart at h1): clear both folders at start, logging one audit
261
+ // line per removed answer.
262
+ if (useFiles && paths) {
263
+ for (const [dir, isAnswers] of /** @type {[string, boolean][]} */ ([[paths.asksDir, false], [paths.answersDir, true]])) {
264
+ let names;
265
+ try {
266
+ names = fs.readdirSync(dir);
267
+ } catch {
268
+ continue;
269
+ }
270
+ for (const name of names) {
271
+ try {
272
+ fs.unlinkSync(path.join(dir, name));
273
+ } catch {
274
+ continue;
275
+ }
276
+ if (isAnswers) {
277
+ log({ ev: 'stale-answer', id: name.endsWith('.json') ? name.slice(0, -'.json'.length) : name, note: 'leftover from a dead queue; removed at start' });
278
+ }
279
+ }
280
+ }
281
+ }
54
282
 
55
283
  let n = 0;
56
284
  /** @type {Map<string, object>} */
57
285
  const queue = new Map();
286
+ /**
287
+ * One hold slot per agent: `holder` is the reservation holding it (or the
288
+ * parked entry's marker), `line` the FIFO of waiting reservation handles.
289
+ *
290
+ * @type {Map<string, { holder: object|null, line: Array<object> }>}
291
+ */
292
+ const slots = new Map();
293
+ /** Internal reserve state by returned handle identity. @type {WeakMap<object, { agent: string, onReady: () => void, onExpire: (reason: string) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean }>} */
294
+ const handleState = new WeakMap();
295
+
296
+ /**
297
+ * The one expiry path for every reservation timer: mark it done, take it
298
+ * out of the line or hand its slot to the next waiter (whose own timer
299
+ * keeps running from its arrival), then expire it. Once.
300
+ *
301
+ * @param {string} agent agent name
302
+ * @param {object} handle the reservation's handle
303
+ * @param {string} reason expiry reason
304
+ * @returns {void}
305
+ */
306
+ function expireReservation(agent, handle, reason) {
307
+ const st = handleState.get(handle);
308
+ if (!st || st.done) return;
309
+ st.done = true;
310
+ st.timer = null;
311
+ const s = slots.get(agent);
312
+ if (s) {
313
+ if (s.holder === handle) {
314
+ releaseSlot(agent);
315
+ } else {
316
+ const i = s.line.indexOf(handle);
317
+ if (i >= 0) s.line.splice(i, 1);
318
+ if (!s.holder && s.line.length === 0) slots.delete(agent);
319
+ }
320
+ }
321
+ st.onExpire(reason);
322
+ }
323
+
324
+ /**
325
+ * Drop the current holder and hand the slot to the next waiter in line,
326
+ * or forget the agent when nobody waits. A promoted waiter keeps its own
327
+ * arrival timer: nothing here arms, clears or resets one.
328
+ *
329
+ * @param {string} agent agent name
330
+ * @returns {void}
331
+ */
332
+ function releaseSlot(agent) {
333
+ const s = slots.get(agent);
334
+ if (!s) return;
335
+ s.holder = null;
336
+ const next = s.line.shift();
337
+ if (!next) {
338
+ slots.delete(agent);
339
+ return;
340
+ }
341
+ s.holder = next;
342
+ const hst = handleState.get(next);
343
+ if (hst) hst.onReady();
344
+ }
58
345
 
59
346
  const pub = (h) => ({
60
- id: h.id, agent: h.agent, method: h.method, url: h.url,
61
- body: h.body.toString('utf8'), waitingSec: Math.round((Date.now() - h.t0) / 1000),
347
+ id: h.id, agent: h.agent, method: h.method, url: h.url, rule: h.note,
348
+ waitingSec: Math.round((Date.now() - h.t0) / 1000),
62
349
  });
63
350
 
64
- function settle(id, approve, reason) {
351
+ /**
352
+ * Build the decision-ready ask payload for a parked entry.
353
+ *
354
+ * @param {object} entry queue entry
355
+ * @param {number|null} ms hold deadline in ms, or null for never
356
+ * @param {string} rule hold-reason string
357
+ * @returns {AskPayload}
358
+ */
359
+ function askPayload(entry, ms, rule) {
360
+ const body = Buffer.isBuffer(entry.body) ? entry.body : Buffer.from(String(entry.body ?? ''));
361
+ return {
362
+ id: entry.id,
363
+ agent: entry.agent,
364
+ method: entry.method,
365
+ url: entry.url,
366
+ rule,
367
+ // M3 owns letters; everything the queue parks today is irreversible.
368
+ letter: 'x',
369
+ bodyPreview: body.subarray(0, ASK_BODY_LIMIT).toString('utf8'),
370
+ truncated: body.length > ASK_BODY_LIMIT,
371
+ waitingSec: 0,
372
+ // ISO-8601 UTC (not epoch ms): readable in `sbx pending` and logs.
373
+ expiresAt: ms === null ? null : new Date(entry.t0 + ms).toISOString(),
374
+ };
375
+ }
376
+
377
+ function removeAskFile(id) {
378
+ if (!paths) return;
379
+ try {
380
+ fs.unlinkSync(paths.askFile(id));
381
+ } catch {}
382
+ }
383
+
384
+ function settle(id, approved, reason) {
65
385
  const h = queue.get(id);
66
386
  if (!h) return `unknown ${id}`;
67
387
  queue.delete(id);
68
388
  if (h.timer) clearTimeout(h.timer);
69
- if (approve) {
70
- log({ ev: 'decide', id, agent: h.agent, decision: 'approve', reason: reason || undefined });
389
+ if (h.slot) releaseSlot(h.agent);
390
+ removeAskFile(id);
391
+ const decision = approved ? 'allow' : 'deny';
392
+ if (approved) {
393
+ log({ ev: 'decide', id, agent: h.agent, decision, reason: reason || undefined });
71
394
  onApprove(h);
72
- return `approved ${id}`;
395
+ } else {
396
+ log({ ev: 'decide', id, agent: h.agent, decision, reason });
397
+ onDeny(h, reason);
398
+ }
399
+ onEvent?.({ type: 'decided', id, decision, reason: reason || undefined });
400
+ return approved ? `approved ${id}` : `denied ${id}`;
401
+ }
402
+
403
+ /**
404
+ * Park an entry: write the ask file (file channel only) and report the
405
+ * ask. Double-settle is safe: the deadline timer and the answer race,
406
+ * and the loser finds no entry. The file channel never waits here: the
407
+ * single interval settles on answer, the timer denies on deadline.
408
+ * The `onAsk` channel stays a promise per hold.
409
+ *
410
+ * @param {object} entry queue entry
411
+ * @param {number|null} ms hold deadline in ms, or null for never
412
+ * @param {string} rule hold-reason string
413
+ * @returns {Promise<void>}
414
+ */
415
+ async function park(entry, ms, rule) {
416
+ const ask = askPayload(entry, ms, rule);
417
+ if (useFiles && paths) {
418
+ try {
419
+ writeFileAtomic(paths.askFile(entry.id), JSON.stringify(ask));
420
+ } catch (e) {
421
+ const msg = e instanceof Error ? e.message : String(e);
422
+ log({ ev: 'deny', agent: entry.agent, code: 500, note: `ask channel failed: ${msg}` });
423
+ settle(entry.id, false, 'ask channel failed');
424
+ return;
425
+ }
426
+ }
427
+ onEvent?.({ type: 'ask', ask });
428
+ if (!useFiles) {
429
+ /** @type {{ decision?: unknown, reason?: unknown } | null} */
430
+ let raw = null;
431
+ try {
432
+ raw = await onAsk(ask);
433
+ } catch (e) {
434
+ const msg = e instanceof Error ? e.message : String(e);
435
+ raw = { decision: 'deny', reason: `onAsk failed: ${msg}` };
436
+ }
437
+ const norm = normalizeDecision(raw);
438
+ if (norm && norm.decision === 'allow') settle(entry.id, true, '');
439
+ else settle(entry.id, false, norm?.reason ?? 'denied');
73
440
  }
74
- log({ ev: 'decide', id, agent: h.agent, decision: 'deny', reason });
75
- onDeny(h, reason);
76
- return `denied ${id}`;
77
441
  }
78
442
 
443
+ /**
444
+ * The one answer reader (file channel only): each tick reads `answers/`
445
+ * once, consuming every answer file. A held id settles; anything else is
446
+ * stale (ignored, logged, removed). Malformed answers are ignored and
447
+ * logged; the hold keeps waiting until its deadline.
448
+ *
449
+ * @returns {void}
450
+ */
451
+ function pollAnswers() {
452
+ if (!paths) return;
453
+ let names;
454
+ try {
455
+ names = fs.readdirSync(paths.answersDir);
456
+ } catch {
457
+ return;
458
+ }
459
+ for (const name of names) {
460
+ if (!name.endsWith('.json')) continue;
461
+ const id = name.slice(0, -'.json'.length);
462
+ const text = consumeFile(paths.answerFile(id));
463
+ if (text === null) continue;
464
+ const norm = normalizeDecision(parseAnswer(text), { approveAlias: true });
465
+ if (!norm) {
466
+ log({ ev: 'malformed-answer', id, note: 'ignored; still waiting' });
467
+ continue;
468
+ }
469
+ if (!queue.has(id)) {
470
+ log({ ev: 'stale-answer', id, note: 'unknown or already-settled id; ignored' });
471
+ continue;
472
+ }
473
+ settle(id, norm.decision === 'allow', norm.reason ?? '');
474
+ }
475
+ }
476
+
477
+ const pollTimer = useFiles && paths
478
+ ? setInterval(pollAnswers, poll)
479
+ : null;
480
+ if (pollTimer && typeof pollTimer.unref === 'function') pollTimer.unref();
481
+
79
482
  const holds = {
80
- add({ agent, method, url, headers, body, sock, cres, note }) {
483
+ /**
484
+ * Park a held request. With `slot` (from `reserve`) the parked entry
485
+ * takes over that slot, clearing the reservation's timer; with
486
+ * `arrivedAt` the deadline counts from arrival, not from now. A
487
+ * finished slot (expired, cancelled, closed, or no longer the holder)
488
+ * parks nothing and returns `null`. Without `slot`, parks exactly as
489
+ * before, without limit.
490
+ *
491
+ * @param {object} entry queue entry
492
+ * @returns {string|null} hold id, or null for a finished slot
493
+ */
494
+ add({ agent, method, url, headers, body, sock, cres, note, slot, arrivedAt }) {
495
+ const hst = typeof slot === 'object' && slot !== null ? handleState.get(slot) : undefined;
496
+ const s = slots.get(agent);
497
+ if (slot && (!hst || hst.done || !s || s.holder !== slot)) return null;
81
498
  const id = `h${++n}`;
82
499
  const ms = deadlineMs();
500
+ const t0 = typeof arrivedAt === 'number' ? arrivedAt : Date.now();
83
501
  const entry = {
84
- id, agent, method, url, headers, body, sock, cres, t0: Date.now(),
502
+ id, agent, method, url, headers, body, sock, cres, note, t0,
503
+ slot: null,
85
504
  timer: ms === null ? null
86
- : setTimeout(() => settle(id, false, 'hold timeout'), ms),
505
+ : setTimeout(() => settle(id, false, 'hold timeout'), Math.max(0, ms - (Date.now() - t0))),
87
506
  };
88
507
  // Unref: a parked `never` hold must not keep the process alive by itself.
89
508
  if (entry.timer?.unref) entry.timer.unref();
509
+ if (slot && hst && s && s.holder === slot) {
510
+ if (hst.timer) clearTimeout(hst.timer);
511
+ hst.timer = null;
512
+ hst.consumed = true;
513
+ s.holder = { parked: id };
514
+ entry.slot = slot;
515
+ }
90
516
  queue.set(id, entry);
91
517
  log({ ev: 'hold', id, agent, method, url, reason: note ?? undefined,
92
- timeoutMs: ms, waiting: queue.size });
518
+ timeoutMs: ms, waiting: queue.size, queued: s ? s.line.length : 0 });
519
+ void park(entry, ms, note ?? '');
93
520
  return id;
94
521
  },
95
522
 
96
- approve(id) { return settle(id, true, ''); },
97
- deny(id, reason) { return settle(id, false, reason || 'denied by user'); },
523
+ /**
524
+ * Ask for this agent's hold slot before reading a held request's body.
525
+ * @param {string} agent
526
+ * @param {{ onReady: () => void, onExpire: (reason: string) => void }} cbs
527
+ * @returns {{ state: 'now'|'queued'|'full', arrivedAt: number, cancel: () => void }}
528
+ */
529
+ reserve(agent, { onReady, onExpire }) {
530
+ const arrivedAt = Date.now();
531
+ // Internal slot state, keyed by the returned handle's identity: `add`
532
+ // receives that same object as `slot`, so holder comparisons use it.
533
+ // The one deadline timer lives here, armed below for 'now' and
534
+ // 'queued' alike; expiry runs through `expireReservation` only.
535
+ /** @type {{ agent: string, onReady: () => void, onExpire: (reason: string) => void, timer: ReturnType<typeof setTimeout>|null, consumed: boolean, done: boolean }} */
536
+ const st = { agent, onReady, onExpire, timer: null, consumed: false, done: false };
537
+ const s0 = slots.get(agent);
538
+ /** @type {'now'|'queued'|'full'} */
539
+ const state = !s0 ? 'now' : (s0.line.length >= MAX_WAITING_PER_AGENT ? 'full' : 'queued');
540
+ const handle = {
541
+ state,
542
+ arrivedAt,
543
+ cancel() {
544
+ if (st.done) return;
545
+ st.done = true;
546
+ if (st.timer) clearTimeout(st.timer);
547
+ st.timer = null;
548
+ if (st.consumed) return;
549
+ const s = slots.get(agent);
550
+ if (!s) return;
551
+ if (s.holder === handle) {
552
+ releaseSlot(agent);
553
+ return;
554
+ }
555
+ const i = s.line.indexOf(handle);
556
+ if (i >= 0) {
557
+ s.line.splice(i, 1);
558
+ if (!s.holder && s.line.length === 0) slots.delete(agent);
559
+ }
560
+ },
561
+ };
562
+ handleState.set(handle, st);
563
+ if (state === 'now') {
564
+ slots.set(agent, { holder: handle, line: [] });
565
+ } else if (state === 'full') {
566
+ log({ ev: 'hold-queue-full', agent });
567
+ return handle;
568
+ } else {
569
+ if (!s0) throw new Error(`reserve: no slot record for ${agent}`);
570
+ s0.line.push(handle);
571
+ }
572
+ const ms = deadlineMs();
573
+ if (ms !== null) {
574
+ st.timer = setTimeout(() => expireReservation(agent, handle, 'hold timeout'), ms);
575
+ if (st.timer.unref) st.timer.unref();
576
+ }
577
+ return handle;
578
+ },
98
579
 
99
- // The client went away: drop its holds so no later approve can forward
580
+ // The client went away: drop its holds so no later answer can forward
100
581
  // a request nobody is listening for.
101
582
  abandon(id) {
102
583
  const h = queue.get(id);
103
584
  if (!h) return;
104
585
  queue.delete(id);
105
586
  if (h.timer) clearTimeout(h.timer);
587
+ if (h.slot) releaseSlot(h.agent);
588
+ removeAskFile(id);
106
589
  log({ ev: 'hold-abandoned', id, agent: h.agent, method: h.method, url: h.url });
107
590
  onDeny(h, 'client gone');
591
+ onEvent?.({ type: 'decided', id, decision: 'deny', reason: 'client gone' });
108
592
  },
109
593
 
110
594
  abandonSocket(sock) {
@@ -116,40 +600,27 @@ export function createHolds({ log, shouldHold, match, timeoutMs = 120000,
116
600
  decide(req) { return decide(req); },
117
601
 
118
602
  pending() { return [...queue.values()].map(pub); },
119
- size() { return queue.size; },
120
603
 
121
604
  close() {
122
- for (const [id] of queue) settle(id, false, 'proxy closing');
123
- ctl?.close();
605
+ if (pollTimer) clearInterval(pollTimer);
606
+ for (const s of [...slots.values()]) {
607
+ const handles = [...s.line];
608
+ if (s.holder && !('parked' in s.holder)) handles.push(s.holder);
609
+ for (const handle of handles) {
610
+ const hst = handleState.get(handle);
611
+ if (!hst) continue;
612
+ if (hst.timer) clearTimeout(hst.timer);
613
+ hst.timer = null;
614
+ hst.done = true;
615
+ hst.onExpire('proxy closing');
616
+ }
617
+ }
618
+ slots.clear();
619
+ // settle() removes each ask file: `sbx pending` never lists a dead queue's holds.
620
+ for (const [id] of [...queue]) settle(id, false, 'proxy closing');
124
621
  },
125
622
  };
126
623
 
127
- let ctl = null;
128
- if (controlSocket) {
129
- try { fs.unlinkSync(controlSocket); } catch {}
130
- ctl = net.createServer((sock) => {
131
- let line = '';
132
- sock.on('data', (ch) => {
133
- line += ch.toString('latin1');
134
- const i = line.indexOf('\n');
135
- if (i < 0) return;
136
- const [cmd, arg, ...rest] = line.slice(0, i).trim().split(' ');
137
- let out = '';
138
- if (cmd === 'pending') out = JSON.stringify(holds.pending());
139
- else if (cmd === 'approve' && arg) out = holds.approve(arg);
140
- else if (cmd === 'deny' && arg) out = holds.deny(arg, rest.join(' '));
141
- else out = 'usage: pending | approve <id> | deny <id> [reason]';
142
- sock.end(out + '\n');
143
- });
144
- sock.on('error', () => {});
145
- });
146
- ctl.on('error', () => {});
147
- ctl.listen(controlSocket, () => {
148
- // Anyone who can connect can approve payments.
149
- try { fs.chmodSync(controlSocket, 0o600); } catch {}
150
- });
151
- }
152
-
153
624
  return holds;
154
625
  }
155
626
 
package/src/index.js CHANGED
@@ -1,3 +1,5 @@
1
1
  // barebox public barrel. Every export with @when appears in primitives.json.
2
2
  export { launch } from './launcher.js';
3
3
  export { createProxy } from './proxy.js';
4
+ export { run } from './run.js';
5
+ export { diffOverlay, commitOverlay, rollbackOverlay } from './overlay.js';