@brud/daemon 0.0.0-stage → 0.0.1

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.
Files changed (61) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +67 -2
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.js +88 -0
  5. package/dist/client/DaemonClient.d.ts +55 -0
  6. package/dist/client/DaemonClient.js +383 -0
  7. package/dist/client/connectToDaemon.d.ts +19 -0
  8. package/dist/client/connectToDaemon.js +131 -0
  9. package/dist/client/errors.d.ts +74 -0
  10. package/dist/client/errors.js +104 -0
  11. package/dist/client/identity.d.ts +3 -0
  12. package/dist/client/identity.js +7 -0
  13. package/dist/client/index.d.ts +6 -0
  14. package/dist/client/index.js +23 -0
  15. package/dist/client/socket.d.ts +9 -0
  16. package/dist/client/socket.js +101 -0
  17. package/dist/client/spawn.d.ts +7 -0
  18. package/dist/client/spawn.js +171 -0
  19. package/dist/index.d.ts +12 -0
  20. package/dist/index.js +29 -0
  21. package/dist/instanceRegistry.d.ts +130 -0
  22. package/dist/instanceRegistry.js +332 -0
  23. package/dist/lifecycle/endpoint.d.ts +19 -0
  24. package/dist/lifecycle/endpoint.js +124 -0
  25. package/dist/lifecycle/idle.d.ts +28 -0
  26. package/dist/lifecycle/idle.js +69 -0
  27. package/dist/lifecycle/index.d.ts +4 -0
  28. package/dist/lifecycle/index.js +21 -0
  29. package/dist/lifecycle/lock.d.ts +28 -0
  30. package/dist/lifecycle/lock.js +155 -0
  31. package/dist/lifecycle/shutdown.d.ts +39 -0
  32. package/dist/lifecycle/shutdown.js +115 -0
  33. package/dist/operatorConfig.d.ts +36 -0
  34. package/dist/operatorConfig.js +92 -0
  35. package/dist/security/channel.d.ts +113 -0
  36. package/dist/security/channel.js +448 -0
  37. package/dist/security/noise.d.ts +64 -0
  38. package/dist/security/noise.js +313 -0
  39. package/dist/security/ownership.d.ts +36 -0
  40. package/dist/security/ownership.js +86 -0
  41. package/dist/security/peerCredentials.d.ts +104 -0
  42. package/dist/security/peerCredentials.js +244 -0
  43. package/dist/server/Connection.d.ts +70 -0
  44. package/dist/server/Connection.js +412 -0
  45. package/dist/server/DaemonServer.d.ts +77 -0
  46. package/dist/server/DaemonServer.js +396 -0
  47. package/dist/server/createDaemon.d.ts +52 -0
  48. package/dist/server/createDaemon.js +165 -0
  49. package/dist/server/dispatch.d.ts +52 -0
  50. package/dist/server/dispatch.js +291 -0
  51. package/dist/server/framing.d.ts +63 -0
  52. package/dist/server/framing.js +196 -0
  53. package/dist/server/handshake.d.ts +22 -0
  54. package/dist/server/handshake.js +94 -0
  55. package/dist/server/protocolValidation.d.ts +47 -0
  56. package/dist/server/protocolValidation.js +366 -0
  57. package/dist/server/wireErrors.d.ts +5 -0
  58. package/dist/server/wireErrors.js +190 -0
  59. package/dist/version.d.ts +2 -0
  60. package/dist/version.js +6 -0
  61. package/package.json +55 -4
@@ -0,0 +1,412 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.Connection = exports.DEFAULT_SERVER_REQUEST_TIMEOUT_MS = exports.DEFAULT_MAX_IN_FLIGHT_PER_CONNECTION = void 0;
37
+ const Protocol = __importStar(require("@brud/protocol"));
38
+ const protocolValidation_js_1 = require("./protocolValidation.js");
39
+ const wireErrors_js_1 = require("./wireErrors.js");
40
+ /** How long a cancellation waits for the operation to settle before acking. */
41
+ const CANCEL_ACK_GRACE_MS = 5_000;
42
+ /** Default ceiling on concurrent in-flight requests per connection. */
43
+ exports.DEFAULT_MAX_IN_FLIGHT_PER_CONNECTION = 64;
44
+ /** Default server-side deadline for one request. */
45
+ exports.DEFAULT_SERVER_REQUEST_TIMEOUT_MS = 5 * 60_000;
46
+ function readCancelId(value) {
47
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
48
+ return undefined;
49
+ }
50
+ if (!('id' in value)) {
51
+ return undefined;
52
+ }
53
+ const id = value.id;
54
+ if (typeof id === 'string' || typeof id === 'number' || id === null) {
55
+ return id;
56
+ }
57
+ return undefined;
58
+ }
59
+ function readOperationStatus(response) {
60
+ if (!('result' in response)) {
61
+ return undefined;
62
+ }
63
+ const result = response.result;
64
+ if (typeof result !== 'object' || result === null || Array.isArray(result)) {
65
+ return undefined;
66
+ }
67
+ const nested = result.result;
68
+ if (typeof nested === 'object' && nested !== null && !Array.isArray(nested)) {
69
+ const status = nested.status;
70
+ if (typeof status === 'string') {
71
+ return status;
72
+ }
73
+ }
74
+ // A routed Brud request: any aborted operation means the work stopped.
75
+ const operations = result.operations;
76
+ if (Array.isArray(operations)) {
77
+ for (const operation of operations) {
78
+ const entry = operation;
79
+ if (entry?.status === 'aborted' || entry?.result?.status === 'aborted') {
80
+ return 'aborted';
81
+ }
82
+ }
83
+ }
84
+ const status = result.status;
85
+ return typeof status === 'string' ? status : undefined;
86
+ }
87
+ function cancelAckFor(entry, settled) {
88
+ if (!settled) {
89
+ return {
90
+ id: entry.id,
91
+ status: 'aborting',
92
+ message: `Cancellation was delivered to "${entry.method}" but it did not settle within ${CANCEL_ACK_GRACE_MS} ms.`,
93
+ };
94
+ }
95
+ if (entry.operationStatus === 'aborted') {
96
+ return {
97
+ id: entry.id,
98
+ status: 'cancelled',
99
+ message: `Cancellation stopped "${entry.method}".`,
100
+ };
101
+ }
102
+ if (entry.operationStatus === 'success') {
103
+ return {
104
+ id: entry.id,
105
+ status: 'not-abortable',
106
+ message: `"${entry.method}" does not honor cancellation and completed.`,
107
+ };
108
+ }
109
+ return {
110
+ id: entry.id,
111
+ status: 'not-abortable',
112
+ message: `"${entry.method}" finished with status "${entry.operationStatus ?? 'unknown'}" after cancellation.`,
113
+ };
114
+ }
115
+ /**
116
+ * One authenticated daemon connection.
117
+ *
118
+ * The principal and daemon home are already fixed by the Noise session. This
119
+ * class enforces the post-handshake JSON-RPC contract, request correlation,
120
+ * the in-flight ceiling, and the per-request deadline.
121
+ */
122
+ class Connection {
123
+ connectionId;
124
+ /** Principal fixed by the authenticated handshake. */
125
+ tier;
126
+ channel;
127
+ dispatcher;
128
+ hooks;
129
+ closeListeners = new Set();
130
+ maxInFlight;
131
+ requestTimeoutMs;
132
+ /**
133
+ * Serializes ordinary request dispatch. Cancellation notifications
134
+ * deliberately bypass this chain.
135
+ */
136
+ requestChain = Promise.resolve();
137
+ inFlight = new Map();
138
+ handshakeCompleted = false;
139
+ closed = false;
140
+ constructor(connectionId, channel, context, dispatcher, hooks = {}, limits = {}) {
141
+ this.connectionId = connectionId;
142
+ this.channel = channel;
143
+ this.dispatcher = dispatcher;
144
+ this.hooks = hooks;
145
+ this.tier = context.principal;
146
+ this.maxInFlight = Math.max(1, Math.trunc(limits.maxInFlight ?? exports.DEFAULT_MAX_IN_FLIGHT_PER_CONNECTION));
147
+ this.requestTimeoutMs = Math.max(1, Math.trunc(limits.requestTimeoutMs ?? exports.DEFAULT_SERVER_REQUEST_TIMEOUT_MS));
148
+ channel.onMessage((type, text) => {
149
+ this.handleRecord(type, text);
150
+ });
151
+ channel.onClose(() => {
152
+ this.closed = true;
153
+ this.abortInFlight();
154
+ this.notifyClose();
155
+ });
156
+ }
157
+ get handshaken() {
158
+ return this.handshakeCompleted;
159
+ }
160
+ get isClosed() {
161
+ return this.closed || this.channel.isClosed;
162
+ }
163
+ markHandshaken() {
164
+ this.handshakeCompleted = true;
165
+ }
166
+ onClose(listener) {
167
+ if (this.closed || this.channel.isClosed) {
168
+ listener();
169
+ return;
170
+ }
171
+ this.closeListeners.add(listener);
172
+ }
173
+ destroy() {
174
+ this.closed = true;
175
+ this.abortInFlight();
176
+ this.channel.destroy();
177
+ this.notifyClose();
178
+ }
179
+ end() {
180
+ this.closed = true;
181
+ this.abortInFlight();
182
+ this.channel.end();
183
+ this.notifyClose();
184
+ }
185
+ handleRecord(type, text) {
186
+ if (this.closed) {
187
+ return;
188
+ }
189
+ let value;
190
+ try {
191
+ value = (0, protocolValidation_js_1.parseStrictJson)(text);
192
+ }
193
+ catch (error) {
194
+ if (error instanceof protocolValidation_js_1.JsonContractError) {
195
+ this.send((0, wireErrors_js_1.createRpcErrorResponse)(error.frameId, Protocol.PARSE_ERROR, error.message));
196
+ return;
197
+ }
198
+ this.handleFatalError(error);
199
+ return;
200
+ }
201
+ const envelope = (0, protocolValidation_js_1.validateIncomingEnvelope)(value, type);
202
+ if (!envelope.ok) {
203
+ this.send((0, wireErrors_js_1.createRpcErrorResponse)(envelope.id, envelope.code, envelope.message));
204
+ return;
205
+ }
206
+ if (envelope.kind === 'notification') {
207
+ this.handleNotification(envelope.notification);
208
+ return;
209
+ }
210
+ this.scheduleRequest(envelope.request);
211
+ }
212
+ handleNotification(notification) {
213
+ if (notification.method === Protocol.REQUEST_CANCEL) {
214
+ void this.handleCancel(notification.params, undefined);
215
+ }
216
+ }
217
+ scheduleRequest(request) {
218
+ if (request.method === Protocol.REQUEST_CANCEL) {
219
+ if (!this.handshaken) {
220
+ this.send((0, wireErrors_js_1.createRpcErrorResponse)(request.id, Protocol.HANDSHAKE_REQUIRED, 'request.cancel requires a completed daemon handshake'));
221
+ return;
222
+ }
223
+ void this.handleCancel(request.params, request.id);
224
+ return;
225
+ }
226
+ if (this.inFlight.has(request.id)) {
227
+ this.send((0, wireErrors_js_1.createRpcErrorResponse)(request.id, Protocol.INVALID_REQUEST, 'A request with this id is already in flight'));
228
+ return;
229
+ }
230
+ if (this.inFlight.size >= this.maxInFlight) {
231
+ this.send((0, wireErrors_js_1.createRpcErrorResponse)(request.id, Protocol.RESOURCE_EXHAUSTED, `The connection already has ${this.maxInFlight} requests in flight`));
232
+ return;
233
+ }
234
+ const entry = this.registerInFlight(request);
235
+ this.requestChain = this.requestChain
236
+ .then(async () => {
237
+ // A request the client abandoned before it started must not run.
238
+ if (entry.finished || entry.controller.signal.aborted) {
239
+ entry.operationStatus = 'aborted';
240
+ this.finishInFlight(entry);
241
+ return;
242
+ }
243
+ await this.dispatchRequest(request, entry);
244
+ })
245
+ .catch((error) => {
246
+ this.handleFatalError(error);
247
+ });
248
+ }
249
+ registerInFlight(request) {
250
+ const controller = new AbortController();
251
+ let resolveSettled = () => undefined;
252
+ const settled = new Promise((resolve) => {
253
+ resolveSettled = resolve;
254
+ });
255
+ const entry = {
256
+ id: request.id,
257
+ method: request.method,
258
+ controller,
259
+ settled,
260
+ resolveSettled,
261
+ timer: undefined,
262
+ operationStatus: undefined,
263
+ finished: false,
264
+ };
265
+ entry.timer = setTimeout(() => {
266
+ this.timeoutInFlight(entry);
267
+ }, this.requestTimeoutMs);
268
+ entry.timer.unref?.();
269
+ this.inFlight.set(request.id, entry);
270
+ this.hooks.onRequestStart?.();
271
+ return entry;
272
+ }
273
+ async dispatchRequest(request, entry) {
274
+ let response;
275
+ try {
276
+ response = await this.dispatcher.dispatch(request, this, {
277
+ signal: entry.controller.signal,
278
+ });
279
+ }
280
+ catch (error) {
281
+ const message = error instanceof Error ? error.message : 'Unexpected dispatch failure';
282
+ response = (0, wireErrors_js_1.createRpcErrorResponse)(request.id, Protocol.INTERNAL_ERROR, message);
283
+ }
284
+ if (entry.finished) {
285
+ // The deadline or a disconnect already answered this request.
286
+ return;
287
+ }
288
+ entry.operationStatus = readOperationStatus(response);
289
+ try {
290
+ this.send(response);
291
+ }
292
+ finally {
293
+ this.finishInFlight(entry);
294
+ }
295
+ }
296
+ timeoutInFlight(entry) {
297
+ if (entry.finished) {
298
+ return;
299
+ }
300
+ entry.controller.abort();
301
+ entry.operationStatus = 'aborted';
302
+ this.send((0, wireErrors_js_1.createRpcErrorResponse)(entry.id, Protocol.REQUEST_TIMEOUT, `Request "${entry.method}" exceeded its ${this.requestTimeoutMs} ms deadline`));
303
+ this.finishInFlight(entry);
304
+ }
305
+ finishInFlight(entry) {
306
+ if (entry.finished) {
307
+ return;
308
+ }
309
+ entry.finished = true;
310
+ if (entry.timer !== undefined) {
311
+ clearTimeout(entry.timer);
312
+ entry.timer = undefined;
313
+ }
314
+ entry.resolveSettled();
315
+ if (this.inFlight.get(entry.id) === entry) {
316
+ this.inFlight.delete(entry.id);
317
+ }
318
+ this.hooks.onRequestEnd?.();
319
+ }
320
+ abortInFlight() {
321
+ for (const entry of this.inFlight.values()) {
322
+ if (!entry.finished) {
323
+ entry.controller.abort();
324
+ }
325
+ }
326
+ }
327
+ /**
328
+ * Delivers cancellation to the in-flight operation and acknowledges the
329
+ * observed outcome.
330
+ *
331
+ * `requestId` is defined when the caller sent `request.cancel` as a request;
332
+ * in that case the ack is that request's result. Otherwise the ack is the
333
+ * additive `request.cancelled` notification.
334
+ */
335
+ async handleCancel(value, requestId) {
336
+ const cancelledId = readCancelId(value);
337
+ if (cancelledId === undefined) {
338
+ this.deliverCancelAck(requestId, {
339
+ id: null,
340
+ status: 'invalid',
341
+ message: 'request.cancel requires an object with a string, number, or null "id".',
342
+ });
343
+ return;
344
+ }
345
+ const entry = this.inFlight.get(cancelledId);
346
+ if (entry === undefined) {
347
+ this.deliverCancelAck(requestId, {
348
+ id: cancelledId,
349
+ status: 'not-found',
350
+ message: 'No matching request is in flight.',
351
+ });
352
+ return;
353
+ }
354
+ entry.controller.abort();
355
+ const settled = await this.waitForSettlement(entry);
356
+ this.deliverCancelAck(requestId, cancelAckFor(entry, settled));
357
+ }
358
+ async waitForSettlement(entry) {
359
+ if (entry.finished) {
360
+ return true;
361
+ }
362
+ let timer;
363
+ const grace = new Promise((resolve) => {
364
+ timer = setTimeout(() => resolve(false), CANCEL_ACK_GRACE_MS);
365
+ timer.unref?.();
366
+ });
367
+ try {
368
+ return await Promise.race([entry.settled.then(() => true), grace]);
369
+ }
370
+ finally {
371
+ if (timer !== undefined) {
372
+ clearTimeout(timer);
373
+ }
374
+ }
375
+ }
376
+ deliverCancelAck(requestId, ack) {
377
+ if (requestId !== undefined) {
378
+ this.send({ jsonrpc: '2.0', id: requestId, result: ack });
379
+ return;
380
+ }
381
+ this.send({
382
+ jsonrpc: '2.0',
383
+ method: Protocol.REQUEST_CANCELLED,
384
+ params: ack,
385
+ });
386
+ }
387
+ send(message) {
388
+ if (this.closed || this.channel.isClosed) {
389
+ return;
390
+ }
391
+ try {
392
+ this.channel.send(message);
393
+ }
394
+ catch {
395
+ this.destroy();
396
+ }
397
+ }
398
+ handleFatalError(error) {
399
+ const message = error instanceof Error ? error.message : 'Unexpected connection failure';
400
+ this.send((0, wireErrors_js_1.createRpcErrorResponse)(null, Protocol.INTERNAL_ERROR, message));
401
+ this.destroy();
402
+ }
403
+ notifyClose() {
404
+ const listeners = [...this.closeListeners];
405
+ this.closeListeners.clear();
406
+ for (const listener of listeners) {
407
+ listener();
408
+ }
409
+ }
410
+ }
411
+ exports.Connection = Connection;
412
+ //# sourceMappingURL=Connection.js.map
@@ -0,0 +1,77 @@
1
+ import type { DaemonCallerTier } from '@brud/protocol';
2
+ import type { KernelInstanceRegistry } from '../instanceRegistry.js';
3
+ /** Default ceiling on simultaneously open local connections. */
4
+ export declare const DEFAULT_MAX_CONNECTIONS = 64;
5
+ export interface DaemonServerConfig {
6
+ /** The daemon's kernels. */
7
+ readonly registry: KernelInstanceRegistry;
8
+ readonly socketPath: string;
9
+ /**
10
+ * Per-principal pre-shared keys used to authenticate the Noise handshake.
11
+ * `ui` and `ai` are distinct, so the principal is fixed by whichever PSK
12
+ * authenticates rather than by a request field.
13
+ */
14
+ readonly principals: Readonly<Record<DaemonCallerTier, string>>;
15
+ /** Canonical daemon home; a client must name the same home in its handshake. */
16
+ readonly home: string;
17
+ readonly serverName?: string;
18
+ readonly serverVersion?: string;
19
+ /** Maximum simultaneously open connections. */
20
+ readonly maxConnections?: number;
21
+ /** Maximum concurrent in-flight requests per connection. */
22
+ readonly maxInFlightPerConnection?: number;
23
+ /** Server-side deadline for one request. */
24
+ readonly requestTimeoutMs?: number;
25
+ /**
26
+ * Process that is allowed to connect: normally the host that spawned the
27
+ * daemon. Defaults to the current process, which is the host when the
28
+ * daemon is embedded in it (tests and in-process embeddings).
29
+ */
30
+ readonly expectedPeerPid?: number;
31
+ }
32
+ export interface DaemonActivitySnapshot {
33
+ readonly activeConnections: number;
34
+ readonly inFlightRequests: number;
35
+ }
36
+ export type DaemonActivityListener = (snapshot: DaemonActivitySnapshot) => void;
37
+ export declare class DaemonServer {
38
+ readonly socketPath: string;
39
+ private readonly server;
40
+ private readonly dispatcher;
41
+ private readonly connections;
42
+ /** Sockets that have been accepted but have not finished the handshake. */
43
+ private readonly handshaking;
44
+ private readonly activityListeners;
45
+ private readonly principals;
46
+ private readonly home;
47
+ private readonly maxConnections;
48
+ private readonly maxInFlightPerConnection;
49
+ private readonly requestTimeoutMs;
50
+ private readonly expectedPeerPid;
51
+ private peerCredentialHost;
52
+ private expectedPeer;
53
+ private pipeListener;
54
+ private inFlightRequests;
55
+ private listening;
56
+ private stopping;
57
+ private closedPromise;
58
+ static create(config: DaemonServerConfig): Promise<DaemonServer>;
59
+ private constructor();
60
+ get connectionCount(): number;
61
+ get inFlightCount(): number;
62
+ get activity(): DaemonActivitySnapshot;
63
+ onActivity(listener: DaemonActivityListener): () => void;
64
+ listen(): Promise<void>;
65
+ private listenPosix;
66
+ private listenWindows;
67
+ private acceptPipeConnections;
68
+ private discardPipePeer;
69
+ stopAccepting(): void;
70
+ closeConnections(): void;
71
+ close(): Promise<void>;
72
+ private accept;
73
+ private admit;
74
+ private refuseConnection;
75
+ private attachConnection;
76
+ private notifyActivity;
77
+ }