@operad-io/engine 0.0.0-stage → 0.1.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.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -2
  3. package/config.schema.json +188 -0
  4. package/keys.schema.json +12 -0
  5. package/package.json +22 -4
  6. package/src/config/config.ts +627 -0
  7. package/src/config/index.ts +1 -0
  8. package/src/flow/define-flow.ts +57 -0
  9. package/src/flow/index.ts +5 -0
  10. package/src/flow/load.ts +41 -0
  11. package/src/flow/types.ts +107 -0
  12. package/src/flow/validate.ts +296 -0
  13. package/src/http/address.ts +142 -0
  14. package/src/http/index.ts +25 -0
  15. package/src/http/link.ts +20 -0
  16. package/src/http/server.ts +920 -0
  17. package/src/http/token.ts +90 -0
  18. package/src/index.ts +18 -0
  19. package/src/kernel/decide.ts +689 -0
  20. package/src/kernel/index.ts +3 -0
  21. package/src/kernel/state.ts +275 -0
  22. package/src/kernel/types.ts +366 -0
  23. package/src/log/errors.ts +77 -0
  24. package/src/log/facts.ts +50 -0
  25. package/src/log/index.ts +6 -0
  26. package/src/log/json-value.ts +67 -0
  27. package/src/log/open-log.ts +17 -0
  28. package/src/log/schema.ts +5 -0
  29. package/src/log/secret.ts +30 -0
  30. package/src/log/sqlite.ts +1011 -0
  31. package/src/log/types.ts +230 -0
  32. package/src/loop/code-watch.ts +486 -0
  33. package/src/loop/index.ts +3 -0
  34. package/src/loop/older-code.ts +58 -0
  35. package/src/loop/serve.ts +483 -0
  36. package/src/markdown.ts +451 -0
  37. package/src/notify/index.ts +10 -0
  38. package/src/notify/notify.ts +256 -0
  39. package/src/platform/file-lock.ts +385 -0
  40. package/src/platform/index.ts +13 -0
  41. package/src/platform/load.ts +18 -0
  42. package/src/platform/process-group.ts +675 -0
  43. package/src/platform/process-watch.ts +152 -0
  44. package/src/platform/sqlite-open.ts +104 -0
  45. package/src/platform/step-reap.ts +668 -0
  46. package/src/platform/watch.ts +158 -0
  47. package/src/platform/worker-reports.ts +34 -0
  48. package/src/plugin/action-schema.ts +550 -0
  49. package/src/plugin/declared-flows.ts +74 -0
  50. package/src/plugin/define-plugin.ts +12 -0
  51. package/src/plugin/errors.ts +73 -0
  52. package/src/plugin/filters.ts +46 -0
  53. package/src/plugin/harness.ts +50 -0
  54. package/src/plugin/home.ts +13 -0
  55. package/src/plugin/index.ts +65 -0
  56. package/src/plugin/install.ts +268 -0
  57. package/src/plugin/keys.ts +63 -0
  58. package/src/plugin/load.ts +256 -0
  59. package/src/plugin/logger.ts +30 -0
  60. package/src/plugin/object-facts.ts +132 -0
  61. package/src/plugin/open-store.ts +32 -0
  62. package/src/plugin/paging.ts +133 -0
  63. package/src/plugin/registry.ts +1786 -0
  64. package/src/plugin/secrets.ts +141 -0
  65. package/src/plugin/semver.ts +110 -0
  66. package/src/plugin/settings.ts +64 -0
  67. package/src/plugin/sqlite-store.ts +756 -0
  68. package/src/plugin/store.ts +318 -0
  69. package/src/plugin/types.ts +1243 -0
  70. package/src/plugin/usage.ts +157 -0
  71. package/src/plugin/validate.ts +1028 -0
  72. package/src/runner/answer.ts +156 -0
  73. package/src/runner/ask.ts +483 -0
  74. package/src/runner/cancel.ts +51 -0
  75. package/src/runner/errors.ts +20 -0
  76. package/src/runner/grants.ts +92 -0
  77. package/src/runner/index.ts +33 -0
  78. package/src/runner/limits.ts +403 -0
  79. package/src/runner/lock.ts +140 -0
  80. package/src/runner/runner.ts +1175 -0
  81. package/src/runner/service.ts +184 -0
  82. package/src/runner/step-worker.ts +303 -0
  83. package/src/testing/clock.ts +67 -0
  84. package/src/testing/index.ts +90 -0
  85. package/src/testing/types.ts +116 -0
  86. package/src/testing/world.ts +369 -0
  87. package/src/trigger/cron.ts +193 -0
  88. package/src/trigger/index.ts +32 -0
  89. package/src/trigger/kernel.ts +1221 -0
  90. package/src/trigger/rules.ts +300 -0
  91. package/src/trigger/store.ts +233 -0
  92. package/src/trigger/types.ts +156 -0
  93. package/src/util.ts +50 -0
  94. package/src/views/history.ts +634 -0
  95. package/src/views/index.ts +7 -0
  96. package/src/views/pending.ts +209 -0
  97. package/src/views/presentation.ts +2609 -0
  98. package/src/views/running.ts +255 -0
  99. package/src/views/settings.ts +452 -0
  100. package/src/views/types.ts +72 -0
  101. package/src/views/uploads.ts +228 -0
  102. package/triggers.schema.json +48 -0
@@ -0,0 +1,920 @@
1
+ /**
2
+ * The HTTP face of the presentation kernel: the same list, get, section,
3
+ * events and act a local client calls, behind one bearer token. Only `serve`
4
+ * starts this; no other command opens the port.
5
+ */
6
+
7
+ import { randomBytes } from "node:crypto";
8
+ import type { HttpConfig } from "../config/config.ts";
9
+ import type { LogBackend } from "../log/types.ts";
10
+ import { messageOf } from "../plugin/errors.ts";
11
+ import type { PluginRegistry } from "../plugin/registry.ts";
12
+ import type { Actor } from "../plugin/types.ts";
13
+ import type { Kernel } from "../trigger/kernel.ts";
14
+ import { listPending } from "../views/pending.ts";
15
+ import {
16
+ DEFAULT_MAX_EVENT_IDS,
17
+ ViewError,
18
+ type ViewEvent,
19
+ type Views,
20
+ } from "../views/presentation.ts";
21
+ import { listRunning } from "../views/running.ts";
22
+ import { findAttachment, Uploads, UploadTooLargeError, MAX_UPLOAD_BYTES } from "../views/uploads.ts";
23
+ import { listTypes } from "../views/types.ts";
24
+ import { validateListenAddresses } from "./address.ts";
25
+ import {
26
+ ensureHttpToken,
27
+ readHttpToken,
28
+ tokensEqual,
29
+ type HttpToken,
30
+ } from "./token.ts";
31
+ import { isRecord } from "../util.ts";
32
+
33
+ /** How long an idle event stream waits before a keep-alive comment. */
34
+ export const DEFAULT_KEEP_ALIVE_MS = 15_000;
35
+
36
+ /** The header a client names itself in; the name becomes the actor's `via`. */
37
+ export const CLIENT_HEADER = "x-operad-client";
38
+
39
+ /** The client's name when it is a short lowercase word; `http` when missing or not one. */
40
+ export function clientName(header: string | null): string {
41
+ const name = header?.trim() ?? "";
42
+ return /^[a-z][a-z0-9_-]{0,31}$/.test(name) ? name : "http";
43
+ }
44
+
45
+ /** How often a running server checks whether `http token rotate` replaced the token. */
46
+ export const DEFAULT_TOKEN_CHECK_MS = 1_000;
47
+
48
+ /** The largest JSON request body `serve` accepts, in bytes. */
49
+ export const MAX_REQUEST_BODY_BYTES = 1024 * 1024;
50
+
51
+ /** How often a running server removes the uploads no action used. */
52
+ export const DEFAULT_UPLOAD_SWEEP_MS = 10 * 60 * 1000;
53
+
54
+ export interface HttpServerOptions {
55
+ readonly home: string;
56
+ readonly config: HttpConfig;
57
+ readonly views: Views;
58
+ readonly log: LogBackend;
59
+ readonly registry: PluginRegistry;
60
+ readonly kernel?: Kernel | undefined;
61
+ readonly onLog?: ((message: string) => void) | undefined;
62
+ /** Called once per address with the URL it listens on. */
63
+ readonly onListen?: ((url: string) => void) | undefined;
64
+ readonly maxEventIds?: number | undefined;
65
+ readonly keepAliveMs?: number | undefined;
66
+ readonly tokenCheckMs?: number | undefined;
67
+ /** How long an upload no action used stays; default one hour. */
68
+ readonly uploadTtlMs?: number | undefined;
69
+ readonly uploadSweepMs?: number | undefined;
70
+ /** The largest upload in bytes; default 20 MB. */
71
+ readonly uploadLimitBytes?: number | undefined;
72
+ readonly clock?: (() => number) | undefined;
73
+ /** How long `stop` waits for the addresses to release; default 5 seconds. */
74
+ readonly stopTimeoutMs?: number | undefined;
75
+ /** Waits `ms`; tests inject it instead of a timer. */
76
+ readonly wait?: ((ms: number) => Promise<void>) | undefined;
77
+ /** Starts one listener; tests replace it to fake a listener that will not stop. */
78
+ readonly listener?: typeof Bun.serve | undefined;
79
+ }
80
+
81
+ /** How long `stop` waits for every listen address to be released. */
82
+ export const DEFAULT_STOP_TIMEOUT_MS = 5_000;
83
+
84
+ /** `stop` could not release an address in time; the process still holds it. */
85
+ export class HttpStopError extends Error {
86
+ readonly addresses: readonly string[];
87
+ constructor(addresses: readonly string[]) {
88
+ super(`http: ${addresses.join(", ")} did not release the port`);
89
+ this.name = "HttpStopError";
90
+ this.addresses = addresses;
91
+ }
92
+ }
93
+
94
+ export interface HttpServerHandle {
95
+ /** The URLs the server listens on, one per configured address. */
96
+ readonly urls: readonly string[];
97
+ readonly port: number;
98
+ stop(): Promise<void>;
99
+ }
100
+
101
+ export interface EventEntry {
102
+ /** The position inside this process's stream. */
103
+ readonly seq: number;
104
+ /** The SSE id: `<bootId>-<seq>`, opaque to the client. */
105
+ readonly event: string;
106
+ /** The object that changed. */
107
+ readonly id: string;
108
+ }
109
+
110
+ /** The bounded stream of ids every event client resumes from. */
111
+ export class EventHub {
112
+ private readonly entries: EventEntry[] = [];
113
+ private readonly max: number;
114
+ private readonly listeners = new Set<(entry: EventEntry) => void>();
115
+ private readonly iterator: AsyncIterator<ViewEvent>;
116
+ /** Random once per process: an id from another boot never resumes here. */
117
+ private readonly bootId = randomBytes(8).toString("hex");
118
+ private seq = 0;
119
+ private stopped = false;
120
+
121
+ constructor(
122
+ events: AsyncIterable<ViewEvent>,
123
+ max: number,
124
+ onLog: (message: string) => void,
125
+ ) {
126
+ this.max = Math.max(1, max);
127
+ this.iterator = events[Symbol.asyncIterator]();
128
+ void this.pump(onLog);
129
+ }
130
+
131
+ private async pump(onLog: (message: string) => void): Promise<void> {
132
+ try {
133
+ while (!this.stopped) {
134
+ const next = await this.iterator.next();
135
+ if (next.done) break;
136
+ this.seq += 1;
137
+ const entry: EventEntry = {
138
+ seq: this.seq,
139
+ event: `${this.bootId}-${this.seq}`,
140
+ id: next.value.id,
141
+ };
142
+ this.entries.push(entry);
143
+ if (this.entries.length > this.max) this.entries.shift();
144
+ for (const listener of [...this.listeners]) listener(entry);
145
+ }
146
+ } catch (error) {
147
+ if (!this.stopped) onLog(`http events: ${messageOf(error)}`);
148
+ }
149
+ }
150
+
151
+ snapshot(lastId: string | undefined): {
152
+ readonly reset: boolean;
153
+ readonly replay: readonly EventEntry[];
154
+ } {
155
+ if (lastId === undefined) return { reset: false, replay: [] };
156
+ const parsed = parseEventId(lastId);
157
+ // An id from another boot, or one that does not parse, cannot be resumed:
158
+ // the client refetches instead of silently missing changes.
159
+ if (parsed === undefined || parsed.bootId !== this.bootId) {
160
+ return { reset: true, replay: [] };
161
+ }
162
+ const oldest = this.entries[0]?.seq;
163
+ const latest = this.entries.at(-1)?.seq;
164
+ if (oldest === undefined || latest === undefined) {
165
+ return { reset: true, replay: [] };
166
+ }
167
+ if (parsed.seq < oldest - 1 || parsed.seq > latest) {
168
+ return { reset: true, replay: [] };
169
+ }
170
+ return {
171
+ reset: false,
172
+ replay: this.entries.filter((entry) => entry.seq > parsed.seq),
173
+ };
174
+ }
175
+
176
+ subscribe(listener: (entry: EventEntry) => void): () => void {
177
+ this.listeners.add(listener);
178
+ return () => {
179
+ this.listeners.delete(listener);
180
+ };
181
+ }
182
+
183
+ stop(): void {
184
+ this.stopped = true;
185
+ void this.iterator.return?.();
186
+ }
187
+ }
188
+
189
+ function parseEventId(value: string): { bootId: string; seq: number } | undefined {
190
+ const match = /^([0-9a-f]+)-([0-9]+)$/i.exec(value.trim());
191
+ if (match === null) return undefined;
192
+ const bootId = match[1];
193
+ const text = match[2];
194
+ if (bootId === undefined || text === undefined) return undefined;
195
+ const seq = Number(text);
196
+ if (!Number.isSafeInteger(seq) || seq < 0) return undefined;
197
+ return { bootId, seq };
198
+ }
199
+
200
+ /** One open event stream, closed when its token is no longer current. */
201
+ interface OpenStream {
202
+ readonly token: string;
203
+ readonly close: () => void;
204
+ }
205
+
206
+ /** The event streams a server has open, so a token rotation can end them. */
207
+ class StreamRegistry {
208
+ private readonly streams = new Set<OpenStream>();
209
+
210
+ track(token: string, close: () => void): () => void {
211
+ const stream: OpenStream = { token, close };
212
+ this.streams.add(stream);
213
+ return () => {
214
+ this.streams.delete(stream);
215
+ };
216
+ }
217
+
218
+ /** Ends every stream opened with a token other than `token`. */
219
+ closeStale(token: string): void {
220
+ for (const stream of [...this.streams]) {
221
+ if (stream.token === token) continue;
222
+ this.streams.delete(stream);
223
+ stream.close();
224
+ }
225
+ }
226
+
227
+ closeAll(): void {
228
+ for (const stream of [...this.streams]) {
229
+ this.streams.delete(stream);
230
+ stream.close();
231
+ }
232
+ }
233
+ }
234
+
235
+ const JSON_HEADERS = {
236
+ "content-type": "application/json; charset=utf-8",
237
+ "cache-control": "no-store",
238
+ } as const;
239
+
240
+ const SSE_HEADERS = {
241
+ "content-type": "text/event-stream; charset=utf-8",
242
+ "cache-control": "no-cache",
243
+ connection: "keep-alive",
244
+ } as const;
245
+
246
+ function json(value: unknown, status = 200): Response {
247
+ return new Response(JSON.stringify(value), {
248
+ status,
249
+ headers: JSON_HEADERS,
250
+ });
251
+ }
252
+
253
+ function errorResponse(status: number, kind: string, message: string): Response {
254
+ return json({ error: { kind, message } }, status);
255
+ }
256
+
257
+ function viewErrorStatus(kind: ViewError["kind"]): number {
258
+ switch (kind) {
259
+ case "args":
260
+ case "note":
261
+ case "where":
262
+ case "filter":
263
+ case "cursor":
264
+ case "ambiguous":
265
+ return 400;
266
+ case "not-found":
267
+ case "section":
268
+ case "no-views":
269
+ case "action":
270
+ return 404;
271
+ case "unavailable":
272
+ case "not-available":
273
+ case "confirm":
274
+ return 409;
275
+ case "timeout":
276
+ return 504;
277
+ default:
278
+ return 500;
279
+ }
280
+ }
281
+
282
+ function viewErrorResponse(error: ViewError): Response {
283
+ const status = viewErrorStatus(error.kind);
284
+ if (status === 500) {
285
+ return errorResponse(500, "internal", "the request failed");
286
+ }
287
+ return errorResponse(status, error.kind, error.message);
288
+ }
289
+
290
+ /** The name a type shows in a client: `task` becomes `Task`. */
291
+ export { displayNameOf } from "../views/types.ts";
292
+
293
+ function decodeSegment(value: string): string {
294
+ try {
295
+ return decodeURIComponent(value);
296
+ } catch {
297
+ throw new ViewError("args", "the request path is not valid percent-encoding");
298
+ }
299
+ }
300
+
301
+ function trueValue(value: string | null): boolean {
302
+ return value === "true" || value === "1";
303
+ }
304
+
305
+ function lastEventId(value: string | null): string | undefined {
306
+ return value === null ? undefined : value;
307
+ }
308
+
309
+ async function authenticate(
310
+ header: string | null,
311
+ home: string,
312
+ ): Promise<HttpToken | undefined> {
313
+ if (header === null) return undefined;
314
+ const match = /^Bearer\s+(\S+)$/i.exec(header.trim());
315
+ const provided = match?.[1];
316
+ if (provided === undefined) return undefined;
317
+ const expected = await readHttpToken(home);
318
+ if (expected === undefined) return undefined;
319
+ return tokensEqual(expected.token, provided) ? expected : undefined;
320
+ }
321
+
322
+ function urlFor(address: string, port: number): string {
323
+ return address.includes(":")
324
+ ? `http://[${address}]:${port}`
325
+ : `http://${address}:${port}`;
326
+ }
327
+
328
+ function formatEvent(entry: EventEntry): string {
329
+ return `id: ${entry.event}\ndata: ${JSON.stringify({ id: entry.id })}\n\n`;
330
+ }
331
+
332
+ const RESET_EVENT = "event: reset\ndata: {}\n\n";
333
+
334
+ export function eventResponse(
335
+ request: Request,
336
+ hub: EventHub,
337
+ keepAliveMs: number,
338
+ queueLimit: number,
339
+ token: string,
340
+ track: (token: string, close: () => void) => () => void,
341
+ ): Response {
342
+ const resumeFrom = lastEventId(request.headers.get("last-event-id"));
343
+ const encoder = new TextEncoder();
344
+ const queue: string[] = [];
345
+ let closed = false;
346
+ let finished = false;
347
+ let wake: (() => void) | undefined;
348
+ let unsubscribe: (() => void) | undefined;
349
+ let untrack: (() => void) | undefined;
350
+ let keepAlive: ReturnType<typeof setInterval> | undefined;
351
+ let controller: ReadableStreamDefaultController<Uint8Array> | undefined;
352
+
353
+ const close = (): void => {
354
+ if (closed) return;
355
+ closed = true;
356
+ unsubscribe?.();
357
+ unsubscribe = undefined;
358
+ untrack?.();
359
+ untrack = undefined;
360
+ if (keepAlive !== undefined) clearInterval(keepAlive);
361
+ keepAlive = undefined;
362
+ const resume = wake;
363
+ wake = undefined;
364
+ resume?.();
365
+ };
366
+
367
+ /** Ends the response; an overflowed client reconnects and gets a reset. */
368
+ const finish = (): void => {
369
+ if (finished) return;
370
+ finished = true;
371
+ close();
372
+ controller?.close();
373
+ };
374
+
375
+ const push = (text: string): void => {
376
+ if (closed) return;
377
+ if (queue.length >= queueLimit) {
378
+ // The client is not reading. Drop it rather than grow without bound.
379
+ finish();
380
+ return;
381
+ }
382
+ queue.push(text);
383
+ const resume = wake;
384
+ wake = undefined;
385
+ resume?.();
386
+ };
387
+
388
+ const stream = new ReadableStream<Uint8Array>({
389
+ start(started) {
390
+ controller = started;
391
+ // `start` is synchronous, so no event can land between the snapshot and
392
+ // the subscription.
393
+ const snapshot = hub.snapshot(resumeFrom);
394
+ if (snapshot.reset) push(RESET_EVENT);
395
+ else for (const entry of snapshot.replay) push(formatEvent(entry));
396
+ unsubscribe = hub.subscribe((entry) => push(formatEvent(entry)));
397
+ untrack = track(token, finish);
398
+ // An immediate comment flushes the response headers; the client then has
399
+ // a stream even when nothing changes for a while.
400
+ push(": keep-alive\n\n");
401
+ keepAlive = setInterval(() => push(": keep-alive\n\n"), keepAliveMs);
402
+ (keepAlive as { unref?: () => void }).unref?.();
403
+ request.signal.addEventListener("abort", close, { once: true });
404
+ },
405
+ async pull(started) {
406
+ while (!closed && queue.length === 0) {
407
+ await new Promise<void>((resolve) => {
408
+ wake = resolve;
409
+ });
410
+ }
411
+ if (finished) return;
412
+ const chunk = queue.shift();
413
+ if (chunk !== undefined) {
414
+ started.enqueue(encoder.encode(chunk));
415
+ return;
416
+ }
417
+ finish();
418
+ },
419
+ cancel() {
420
+ close();
421
+ },
422
+ });
423
+
424
+ return new Response(stream, { headers: SSE_HEADERS });
425
+ }
426
+
427
+ /** A request body over the limit: the status line is 413. */
428
+ class BodyTooLarge extends Error {}
429
+
430
+ async function readBody(request: Request): Promise<unknown> {
431
+ // The listener takes bodies as large as an upload, so a JSON body is held to its own limit here.
432
+ const declared = Number(request.headers.get("content-length") ?? "0");
433
+ if (declared > MAX_REQUEST_BODY_BYTES) throw new BodyTooLarge();
434
+ const chunks: Uint8Array[] = [];
435
+ let size = 0;
436
+ if (request.body !== null) {
437
+ const reader = request.body.getReader();
438
+ for (;;) {
439
+ const chunk = await reader.read();
440
+ if (chunk.done) break;
441
+ size += chunk.value.byteLength;
442
+ if (size > MAX_REQUEST_BODY_BYTES) {
443
+ await reader.cancel().catch(() => undefined);
444
+ throw new BodyTooLarge();
445
+ }
446
+ chunks.push(chunk.value);
447
+ }
448
+ }
449
+ try {
450
+ return JSON.parse(new TextDecoder().decode(Buffer.concat(chunks)));
451
+ } catch {
452
+ throw new ViewError("args", "the request body is not valid JSON");
453
+ }
454
+ }
455
+
456
+ function megabytes(bytes: number): string {
457
+ return `${Math.floor(bytes / (1024 * 1024))} MB`;
458
+ }
459
+
460
+ function createHandler(
461
+ options: HttpServerOptions,
462
+ uploads: Uploads,
463
+ hub: EventHub,
464
+ streams: StreamRegistry,
465
+ onLog: (message: string) => void,
466
+ ): (request: Request) => Promise<Response> {
467
+ const keepAliveMs = options.keepAliveMs ?? DEFAULT_KEEP_ALIVE_MS;
468
+ // One slot past the resume window so a full replay plus the greeting fits.
469
+ const queueLimit = Math.max(1, options.maxEventIds ?? DEFAULT_MAX_EVENT_IDS) + 1;
470
+
471
+ const handle = async (
472
+ request: Request,
473
+ token: HttpToken,
474
+ ): Promise<Response> => {
475
+ const url = new URL(request.url);
476
+ const path = url.pathname;
477
+ const method = request.method.toUpperCase();
478
+
479
+ if (method === "GET" && path === "/v1/events") {
480
+ return eventResponse(
481
+ request,
482
+ hub,
483
+ keepAliveMs,
484
+ queueLimit,
485
+ token.token,
486
+ (value, close) => streams.track(value, close),
487
+ );
488
+ }
489
+
490
+ if (method === "GET" && path === "/v1/types") {
491
+ return json({ types: listTypes(options.registry) });
492
+ }
493
+
494
+ if (method === "GET" && path === "/v1/keys") {
495
+ return json({
496
+ keys: options.registry.keyBindings().map((binding) => ({
497
+ key: binding.key,
498
+ action: binding.name,
499
+ source: binding.source,
500
+ })),
501
+ });
502
+ }
503
+
504
+ if (method === "GET" && path === "/v1/objects") {
505
+ const type = url.searchParams.get("type");
506
+ const cursor = url.searchParams.get("cursor") ?? undefined;
507
+ const parent = url.searchParams.get("parent") ?? undefined;
508
+ const root = url.searchParams.has("root");
509
+ const named = type !== null && type.trim().length > 0 ? type : undefined;
510
+ if (named === undefined && !root && parent === undefined) {
511
+ return errorResponse(400, "args", "the query needs a type, root or parent");
512
+ }
513
+ const filterName = url.searchParams.get("filter") ?? undefined;
514
+ if (root || parent !== undefined) {
515
+ return json(
516
+ await options.views.listTree(named, {
517
+ root,
518
+ ...(parent === undefined ? {} : { parent }),
519
+ ...(cursor === undefined ? {} : { cursor }),
520
+ ...(filterName === undefined ? {} : { filter: filterName }),
521
+ }),
522
+ );
523
+ }
524
+ if (named === undefined) {
525
+ return errorResponse(400, "args", "the query needs a type");
526
+ }
527
+ const filter = filterName ?? options.views.defaultFilterOf(named);
528
+ return json(
529
+ await options.views.list(named, {
530
+ ...(cursor === undefined ? {} : { cursor }),
531
+ ...(filter === undefined ? {} : { filter }),
532
+ }),
533
+ );
534
+ }
535
+
536
+ if (method === "GET" && path === "/v1/pending") {
537
+ return json(
538
+ await listPending(
539
+ options.log,
540
+ options.registry,
541
+ options.kernel,
542
+ options.views,
543
+ ),
544
+ );
545
+ }
546
+
547
+ if (method === "GET" && path === "/v1/running") {
548
+ return json(await listRunning(options.log, options.clock, options.views));
549
+ }
550
+
551
+ if (path === "/v1/settings") {
552
+ if (method === "GET") {
553
+ const scope = url.searchParams.get("scope") ?? undefined;
554
+ return json({ settings: await options.views.settings(scope) });
555
+ }
556
+ if (method !== "POST") {
557
+ return errorResponse(405, "method", "this endpoint takes GET or POST");
558
+ }
559
+ const body = await readBody(request);
560
+ if (!isRecord(body)) {
561
+ return errorResponse(400, "args", "the body must be an object");
562
+ }
563
+ const { name, scope, confirmed } = body;
564
+ if (typeof name !== "string" || name.length === 0) {
565
+ return errorResponse(400, "args", "the body needs a name");
566
+ }
567
+ if (!("value" in body)) {
568
+ return errorResponse(400, "args", "the body needs a value");
569
+ }
570
+ if (scope !== undefined && typeof scope !== "string") {
571
+ return errorResponse(400, "args", "scope must be a string");
572
+ }
573
+ if (confirmed !== undefined && typeof confirmed !== "boolean") {
574
+ return errorResponse(400, "args", "confirmed must be a boolean");
575
+ }
576
+ return json(
577
+ await options.views.set(name, body.value, {
578
+ ...(scope === undefined ? {} : { scope }),
579
+ confirmed: confirmed === true,
580
+ }),
581
+ );
582
+ }
583
+
584
+ if (path.startsWith("/v1/attachments/")) {
585
+ if (method !== "GET") {
586
+ return errorResponse(405, "method", "this endpoint takes GET");
587
+ }
588
+ const found = await findAttachment(
589
+ options.home,
590
+ path.slice("/v1/attachments/".length).split("/").map(decodeSegment),
591
+ );
592
+ if (found === undefined) return errorResponse(404, "not-found", "no such attachment");
593
+ return new Response(Bun.file(found.path), {
594
+ headers: {
595
+ "content-type": found.type,
596
+ "content-disposition": `inline; filename*=UTF-8''${encodeURIComponent(found.name)}`,
597
+ "cache-control": "private, no-store",
598
+ "x-content-type-options": "nosniff",
599
+ },
600
+ });
601
+ }
602
+
603
+ if (path === "/v1/uploads") {
604
+ if (method !== "POST") {
605
+ return errorResponse(405, "method", "this endpoint takes POST");
606
+ }
607
+ // The body is the file itself, streamed to disk; the name and the type travel beside it.
608
+ const name = url.searchParams.get("name") ?? "";
609
+ if (name.trim().length === 0) {
610
+ return errorResponse(400, "args", "the request needs a name query for the file");
611
+ }
612
+ const limit = uploads.limit;
613
+ const declared = Number(request.headers.get("content-length") ?? "0");
614
+ if (declared > limit) {
615
+ // The body is never read; the connection ends so its leftover bytes
616
+ // are not taken for the next request.
617
+ const refused = errorResponse(
618
+ 413,
619
+ "too-large",
620
+ `the file is larger than the ${megabytes(limit)} limit`,
621
+ );
622
+ refused.headers.set("connection", "close");
623
+ return refused;
624
+ }
625
+ try {
626
+ const info = await uploads.save(
627
+ request.body,
628
+ name,
629
+ request.headers.get("content-type") ?? "",
630
+ );
631
+ void uploads.sweep().catch(() => undefined);
632
+ return json(info, 201);
633
+ } catch (error) {
634
+ if (error instanceof UploadTooLargeError) {
635
+ return errorResponse(413, "too-large", error.message);
636
+ }
637
+ throw error;
638
+ }
639
+ }
640
+
641
+ if (method === "POST" && path === "/v1/answer") {
642
+ const body = await readBody(request);
643
+ if (!isRecord(body)) {
644
+ return errorResponse(400, "args", "the body must be an object");
645
+ }
646
+ const { runId, waitId, choice } = body;
647
+ if (typeof runId !== "string" || runId.length === 0) {
648
+ return errorResponse(400, "args", "the body needs a runId");
649
+ }
650
+ if (typeof waitId !== "string" || waitId.length === 0) {
651
+ return errorResponse(400, "args", "the body needs a waitId");
652
+ }
653
+ if (typeof choice !== "string" || choice.length === 0) {
654
+ return errorResponse(400, "args", "the body needs a choice");
655
+ }
656
+ const note = body.note;
657
+ if (note !== undefined && typeof note !== "string") {
658
+ return errorResponse(400, "args", "note must be a string");
659
+ }
660
+ const confirmed = body.confirmed;
661
+ if (confirmed !== undefined && typeof confirmed !== "boolean") {
662
+ return errorResponse(400, "args", "confirmed must be a boolean");
663
+ }
664
+ const actor: Actor = { via: clientName(request.headers.get(CLIENT_HEADER)), id: token.label };
665
+ try {
666
+ await options.views.answer({
667
+ runId,
668
+ waitId,
669
+ choice,
670
+ ...(note === undefined ? {} : { note }),
671
+ ...(confirmed === true ? { confirmed: true } : {}),
672
+ surface: "http",
673
+ actor,
674
+ });
675
+ return json({ runId, waitId, choice });
676
+ } catch (error) {
677
+ if (error instanceof ViewError) {
678
+ onLog(
679
+ `http: answer "${waitId}" refused (${viewErrorStatus(error.kind)}): ${error.message}`,
680
+ );
681
+ throw error;
682
+ }
683
+ onLog(`http: answer "${waitId}" refused (422): ${messageOf(error)}`);
684
+ return errorResponse(422, "refused", messageOf(error));
685
+ }
686
+ }
687
+
688
+ if (method === "POST" && path === "/v1/act") {
689
+ const body = await readBody(request);
690
+ if (!isRecord(body)) {
691
+ return errorResponse(400, "args", "the body must be an object");
692
+ }
693
+ const action = body.action;
694
+ if (typeof action !== "string" || action.length === 0) {
695
+ return errorResponse(400, "args", "the body needs an action");
696
+ }
697
+ // `id` is optional: an action that does not target an object names no
698
+ // object, and the views decide whether the action can run without one.
699
+ const id = body.id;
700
+ if (id !== undefined && typeof id !== "string") {
701
+ return errorResponse(400, "args", "id must be a string");
702
+ }
703
+ const args = body.args === undefined ? {} : body.args;
704
+ if (!isRecord(args)) {
705
+ return errorResponse(400, "args", "args must be an object");
706
+ }
707
+ const note = body.note;
708
+ if (note !== undefined && typeof note !== "string") {
709
+ return errorResponse(400, "args", "note must be a string");
710
+ }
711
+ const confirmed = body.confirmed;
712
+ if (confirmed !== undefined && typeof confirmed !== "boolean") {
713
+ return errorResponse(400, "args", "confirmed must be a boolean");
714
+ }
715
+ const actor: Actor = { via: clientName(request.headers.get(CLIENT_HEADER)), id: token.label };
716
+ try {
717
+ const result = await options.views.act(action, id, {
718
+ args,
719
+ ...(note === undefined ? {} : { note }),
720
+ yes: confirmed === true,
721
+ surface: "http",
722
+ actor,
723
+ });
724
+ return json(result);
725
+ } catch (error) {
726
+ // The status stays in the log; a client shows the line itself.
727
+ if (error instanceof ViewError) {
728
+ onLog(
729
+ `http: action "${action}" refused (${viewErrorStatus(error.kind)}): ${error.message}`,
730
+ );
731
+ throw error;
732
+ }
733
+ onLog(`http: action "${action}" refused (422): ${messageOf(error)}`);
734
+ return errorResponse(422, "refused", messageOf(error));
735
+ }
736
+ }
737
+
738
+ if (path.startsWith("/v1/objects/")) {
739
+ if (method !== "GET") {
740
+ return errorResponse(405, "method", "this endpoint takes GET");
741
+ }
742
+ const rest = path.slice("/v1/objects/".length);
743
+ const marker = "/sections/";
744
+ const at = rest.lastIndexOf(marker);
745
+ if (at >= 0) {
746
+ const rawId = rest.slice(0, at);
747
+ const rawSection = rest.slice(at + marker.length);
748
+ if (rawId.length === 0 || rawSection.length === 0) {
749
+ return errorResponse(404, "not-found", "no such section");
750
+ }
751
+ const id = decodeSegment(rawId);
752
+ const section = decodeSegment(rawSection);
753
+ const cursor = url.searchParams.get("cursor") ?? undefined;
754
+ const after = url.searchParams.get("after") ?? undefined;
755
+ return json(
756
+ await options.views.section(id, section, cursor, {
757
+ full: trueValue(url.searchParams.get("full")),
758
+ ...(after === undefined ? {} : { after }),
759
+ }),
760
+ );
761
+ }
762
+ if (rest.length === 0) {
763
+ return errorResponse(404, "not-found", "no such object");
764
+ }
765
+ return json(await options.views.get(decodeSegment(rest)));
766
+ }
767
+
768
+ if (path.startsWith("/v1/")) {
769
+ return errorResponse(404, "not-found", "no such endpoint");
770
+ }
771
+ return errorResponse(404, "not-found", "no such endpoint");
772
+ };
773
+
774
+ return async (request: Request): Promise<Response> => {
775
+ try {
776
+ const token = await authenticate(
777
+ request.headers.get("authorization"),
778
+ options.home,
779
+ );
780
+ if (token === undefined) {
781
+ return errorResponse(401, "unauthorized", "a bearer token is required");
782
+ }
783
+ return await handle(request, token);
784
+ } catch (error) {
785
+ if (error instanceof BodyTooLarge) {
786
+ return errorResponse(
787
+ 413,
788
+ "too-large",
789
+ `the request body is larger than the ${megabytes(MAX_REQUEST_BODY_BYTES)} limit`,
790
+ );
791
+ }
792
+ if (error instanceof ViewError) return viewErrorResponse(error);
793
+ onLog(`http: ${messageOf(error)}`);
794
+ return errorResponse(500, "internal", "the request failed");
795
+ }
796
+ };
797
+ }
798
+
799
+ /** Starts one Bun server per `http.listen` address. */
800
+ export async function startHttpServer(
801
+ options: HttpServerOptions,
802
+ ): Promise<HttpServerHandle> {
803
+ validateListenAddresses(options.config.listen);
804
+ const token = await ensureHttpToken(options.home);
805
+
806
+ const onLog = options.onLog ?? (() => undefined);
807
+ const hub = new EventHub(
808
+ options.views.events(),
809
+ options.maxEventIds ?? DEFAULT_MAX_EVENT_IDS,
810
+ onLog,
811
+ );
812
+ const streams = new StreamRegistry();
813
+ const uploads = new Uploads({
814
+ home: options.home,
815
+ ...(options.clock === undefined ? {} : { clock: options.clock }),
816
+ ...(options.uploadTtlMs === undefined ? {} : { ttlMs: options.uploadTtlMs }),
817
+ ...(options.uploadLimitBytes === undefined ? {} : { limit: options.uploadLimitBytes }),
818
+ });
819
+ void uploads.sweep().catch(() => undefined);
820
+ const uploadSweep = setInterval(() => {
821
+ void uploads.sweep().catch(() => undefined);
822
+ }, options.uploadSweepMs ?? DEFAULT_UPLOAD_SWEEP_MS);
823
+ (uploadSweep as { unref?: () => void }).unref?.();
824
+ const handler = createHandler(options, uploads, hub, streams, onLog);
825
+ const servers: { readonly address: string; readonly server: ReturnType<typeof Bun.serve> }[] = [];
826
+ const listener = options.listener ?? Bun.serve;
827
+ const wait =
828
+ options.wait ??
829
+ ((ms: number) =>
830
+ new Promise<void>((resolve) => {
831
+ // Unref'd: a stop that finished in time must not keep the process up.
832
+ (setTimeout(resolve, ms) as { unref?: () => void }).unref?.();
833
+ }));
834
+ const stopTimeoutMs = options.stopTimeoutMs ?? DEFAULT_STOP_TIMEOUT_MS;
835
+
836
+ /**
837
+ * Stops every listener at once, so one that will not stop (a peer that
838
+ * never reads its stream) cannot keep the others bound, and waits a bounded
839
+ * time. The addresses that did not release in time are named.
840
+ */
841
+ const stopAll = async (): Promise<readonly string[]> => {
842
+ const pending = new Set(servers.map(({ address }) => address));
843
+ const stops = servers.map(async ({ address, server }) => {
844
+ await Promise.resolve(server.stop(true)).catch(() => undefined);
845
+ pending.delete(address);
846
+ });
847
+ await Promise.race([Promise.all(stops), wait(stopTimeoutMs)]);
848
+ return [...pending];
849
+ };
850
+
851
+ // A rotation happens in another process (`operad http token rotate`), so the
852
+ // server notices it by reading the secret file again. A stream opened with the
853
+ // old token ends; the client reconnects and gets a reset.
854
+ let currentToken = token.token;
855
+ let checking = false;
856
+ const tokenCheck = setInterval(() => {
857
+ if (checking) return;
858
+ checking = true;
859
+ void readHttpToken(options.home)
860
+ .then((latest) => {
861
+ if (latest === undefined || latest.token === currentToken) return;
862
+ currentToken = latest.token;
863
+ streams.closeStale(currentToken);
864
+ })
865
+ .catch(() => undefined)
866
+ .finally(() => {
867
+ checking = false;
868
+ });
869
+ }, options.tokenCheckMs ?? DEFAULT_TOKEN_CHECK_MS);
870
+ (tokenCheck as { unref?: () => void }).unref?.();
871
+
872
+ try {
873
+ for (const address of options.config.listen) {
874
+ const server = listener({
875
+ hostname: address,
876
+ port: options.config.port,
877
+ // An event stream is quiet by design; the 15-second comment keeps it
878
+ // below this idle limit.
879
+ idleTimeout: 30,
880
+ // Room for an upload plus its framing; a JSON body is held to its own limit in `readBody`.
881
+ maxRequestBodySize: Math.max(MAX_UPLOAD_BYTES, options.uploadLimitBytes ?? 0) * 2,
882
+ fetch: handler,
883
+ error: (error) => {
884
+ onLog(`http: ${messageOf(error)}`);
885
+ return errorResponse(500, "internal", "the request failed");
886
+ },
887
+ });
888
+ servers.push({ address, server });
889
+ }
890
+ } catch (error) {
891
+ clearInterval(tokenCheck);
892
+ clearInterval(uploadSweep);
893
+ hub.stop();
894
+ streams.closeAll();
895
+ // An address this start already bound and could not release is still held
896
+ // by this process. A retry would run against it, so report that first.
897
+ const unreleased = await stopAll();
898
+ if (unreleased.length > 0) throw new HttpStopError(unreleased);
899
+ throw error;
900
+ }
901
+
902
+ const urls = servers.map(({ address, server }) =>
903
+ urlFor(address, server.port ?? options.config.port),
904
+ );
905
+ for (const url of urls) options.onListen?.(url);
906
+
907
+ const firstPort = servers[0]?.server.port ?? options.config.port;
908
+ return {
909
+ urls,
910
+ port: firstPort,
911
+ async stop() {
912
+ clearInterval(tokenCheck);
913
+ clearInterval(uploadSweep);
914
+ hub.stop();
915
+ streams.closeAll();
916
+ const unreleased = await stopAll();
917
+ if (unreleased.length > 0) throw new HttpStopError(unreleased);
918
+ },
919
+ };
920
+ }