@open-conduit/sdk 0.0.0-bootstrap.0 → 0.0.0-stage

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/dist/extension.js DELETED
@@ -1,674 +0,0 @@
1
- // Declaring each surface once, and serving it.
2
- //
3
- // extension() starts an Extension whose manifest is derived from what is
4
- // registered on it, as the Go SDK's sdk.New does: operation, check, task,
5
- // entryType and family each register a handler and the declaration that
6
- // enables it, so the two cannot disagree. main() answers the packaging
7
- // subcommands (package-manifest, package-certification) and otherwise
8
- // serves protocol version 1 on stdin and stdout until stdin closes.
9
- import { randomBytes } from "node:crypto";
10
- import { Writable } from "node:stream";
11
- import { Code, ConfigError, OperationError, ProtocolError } from "./errors.js";
12
- import { Host, base64, toBytes } from "./host.js";
13
- import { Conn } from "./jsonrpc.js";
14
- import { check, diagnose, isRecord, matches, } from "./schema.js";
15
- import { CheckRunParams, ConfigureParams, EmitCommitParams, IngressPushParams, IngressReconcileParams, InitializeParams, OperationParams, RouteMatchParams, RouteSamplesParams, TaskRunParams, ValidateParams, WebhookHandleParams, WorkKindTriggerParams, } from "./wire.js";
16
- /** The protocol versions this SDK speaks. */
17
- export const ProtocolVersions = [1];
18
- /** Decodes config through schema, reporting what it refuses at each field. */
19
- async function validateConfig(schema, config, extra) {
20
- const c = config ?? {};
21
- if (!matches(schema, c)) {
22
- const diagnostics = diagnose(schema, c);
23
- if (diagnostics.length > 0)
24
- throw new ConfigError(diagnostics);
25
- throw new ProtocolError(Code.Invalid, "invalid extension config");
26
- }
27
- try {
28
- await extra?.(c);
29
- }
30
- catch (err) {
31
- if (err instanceof ConfigError)
32
- throw err;
33
- throw new ProtocolError(Code.Invalid, "invalid extension config");
34
- }
35
- }
36
- /** Starts an extension named name whose manifest its registrations fill in. */
37
- export function extension(name, o) {
38
- return new Extension(name, o);
39
- }
40
- export class Extension {
41
- manifest;
42
- #operations = new Map();
43
- #checks = new Map();
44
- #tasks = new Map();
45
- #entryTypes = new Map();
46
- #routes = new Map();
47
- #triggers = new Map();
48
- #migrate;
49
- #certification;
50
- constructor(name, o) {
51
- // In the Go manifest's field order, so the written file reads the same.
52
- this.manifest = {
53
- protocol: [...ProtocolVersions],
54
- name,
55
- version: o.version,
56
- ...(o.title === undefined ? {} : { title: o.title }),
57
- ...(o.summary === undefined ? {} : { summary: o.summary }),
58
- command: o.command ?? [`${name}-extension`],
59
- ...(o.kvVersion ? { kv_version: o.kvVersion } : {}),
60
- ...(o.permissions?.length ? { permissions: [...o.permissions] } : {}),
61
- provides: o.playbooks ? { playbooks: o.playbooks } : {},
62
- };
63
- }
64
- /** Registers a request/response toolbelt operation and declares it. */
65
- operation(name, spec) {
66
- const output = spec.output ?? `${name}.v1`;
67
- return this.#operation(name, "handler", spec, async (input, ctx) => ({
68
- schema: output,
69
- data: (await spec.handler(input, ctx)) ?? null,
70
- }), spec.serves === undefined ? {} : { serves: spec.serves });
71
- }
72
- /**
73
- * Registers an operation that suspends the calling Work until an Event
74
- * (or a time) comes, and declares it with kind wait: "wait until this
75
- * ticket is resolved".
76
- */
77
- wait(name, spec) {
78
- const output = spec.output ?? `${name}.v1`;
79
- return this.#operation(name, "wait", spec, async (input, ctx) => {
80
- const plan = await spec.handler(input, ctx);
81
- return {
82
- wait: plan.wait,
83
- ...(plan.dependencies?.length
84
- ? { dependencies: plan.dependencies }
85
- : {}),
86
- output: { schema: output, data: plan.output ?? null },
87
- };
88
- });
89
- }
90
- /**
91
- * Registers an operation that emits one Event of a family the extension
92
- * declares, and declares it with kind emit (and commit, when spec.commit).
93
- */
94
- emit(name, spec) {
95
- const output = spec.output ?? `${name}.v1`;
96
- return this.#operation(name, "emit", spec, async (input, ctx) => {
97
- const plan = await spec.handler(input, ctx);
98
- if (plan.commit !== undefined && !spec.commit)
99
- throw new Error(`sdk: operation ${name} returned a commit but is not declared with commit: true`);
100
- return {
101
- plan: {
102
- event: plan.event,
103
- ...(plan.cause ? { cause: plan.cause } : {}),
104
- ...(plan.once ? { once: plan.once } : {}),
105
- },
106
- commit: plan.commit === undefined
107
- ? undefined
108
- : (emitted) => {
109
- const c = plan.commit(emitted);
110
- return {
111
- ...(c.records?.length
112
- ? {
113
- records: c.records.map((r) => ({
114
- namespace: r.namespace,
115
- key: r.key,
116
- value: base64(toBytes(r.value)),
117
- })),
118
- }
119
- : {}),
120
- output: { schema: output, data: c.output ?? null },
121
- };
122
- },
123
- };
124
- }, spec.commit ? { commit: true } : {});
125
- }
126
- #operation(name, kind, spec, run, extra = {}) {
127
- if (this.#operations.has(name))
128
- throw new Error(`sdk: operation ${name} is registered twice`);
129
- const input = spec.input;
130
- this.#operations.set(name, {
131
- kind,
132
- run: async (data, ctx) => {
133
- // Refused before the handler runs, so it only ever sees what its type says.
134
- if (!matches(input, data))
135
- throw new OperationError("bad_request", `${name}: ${check(input, data)}`);
136
- return run(data, ctx);
137
- },
138
- });
139
- // In the Go declaration's field order, so the written manifest reads the same.
140
- const decl = {
141
- name,
142
- kind,
143
- ...(extra.commit ? { commit: true } : {}),
144
- ...(spec.summary === undefined ? {} : { summary: spec.summary }),
145
- ...(spec.guidance === undefined ? {} : { guidance: spec.guidance }),
146
- input: json(input),
147
- ...(spec.wants === undefined ? {} : { wants: spec.wants }),
148
- ...(extra.serves === undefined ? {} : { serves: extra.serves }),
149
- };
150
- (this.manifest.provides.operations ??= []).push(decl);
151
- return this;
152
- }
153
- /** Declares a scope entry type: an "extensions" entry in a scope's config. */
154
- entryType(type, spec) {
155
- return this.#entryType(type, spec.config, spec.validate, async (entries, ctx) => {
156
- await spec.configure?.(entries, ctx);
157
- return [];
158
- });
159
- }
160
- /**
161
- * Declares a scope entry type whose entries own event sources, with the
162
- * families they observe. Each configuration generation, sources names
163
- * the sources the entries register; the host then reconciles each every
164
- * intervalSeconds through reconcile, pushes deliveries to it through
165
- * push, and sends requests on its webhook path (/<source name>) to
166
- * webhook.
167
- */
168
- ingressType(type, spec) {
169
- const name = this.manifest.name;
170
- const families = spec.families.map((f) => ({
171
- type: f.type,
172
- re_derivable: f.re_derivable,
173
- ...(f.loss ? { loss: f.loss } : {}),
174
- }));
175
- const handlers = spec;
176
- this.#entryType(type, spec.config, spec.validate, async (entries, ctx) => {
177
- const sources = await spec.sources(entries, ctx);
178
- return sources.map((s) => {
179
- if (!inNamespace(name, s.name))
180
- throw new ProtocolError(Code.Invalid, `source ${s.name} must be named ${name} or begin with ${name}/`);
181
- if (!inNamespace(name, s.namespace))
182
- throw new ProtocolError(Code.Invalid, `source ${s.name}: namespace ${s.namespace} must be ${name} or begin with ${name}/`);
183
- if (!(s.intervalSeconds >= 1))
184
- throw new ProtocolError(Code.Invalid, `source ${s.name}: intervalSeconds must be at least one`);
185
- const webhook = spec.webhook !== undefined && s.webhook !== false;
186
- if (webhook && !s.name.startsWith(`${name}/`))
187
- throw new ProtocolError(Code.Invalid, `source ${s.name}: a source with a webhook must be named ${name}/<more>, so its path is under /${name}/`);
188
- return {
189
- spec: { ...s, webhook },
190
- type: handlers,
191
- decl: {
192
- name: s.name,
193
- source: { namespace: s.namespace, scope_id: s.scopeId },
194
- interval_seconds: Math.floor(s.intervalSeconds),
195
- families,
196
- },
197
- };
198
- });
199
- }, true);
200
- const provides = this.manifest.provides;
201
- // A family two ingress types share is declared once.
202
- for (const f of spec.families)
203
- if (!provides.families?.some((x) => x.type === f.type))
204
- (provides.families ??= []).push(f);
205
- if (spec.webhook !== undefined) {
206
- provides.webhooks = true;
207
- if (spec.webhookMaxBytes !== undefined)
208
- provides.webhook_max_bytes = Math.max(provides.webhook_max_bytes ?? 0, Math.floor(spec.webhookMaxBytes));
209
- }
210
- return this;
211
- }
212
- #entryType(type, config, validate, configure, ingress = false) {
213
- if (this.#entryTypes.has(type))
214
- throw new Error(`sdk: entry type ${type} is registered twice`);
215
- const decode = (e) => {
216
- // An absent config is an empty one, as Go reads it.
217
- const c = e.config ?? {};
218
- if (!matches(config, c))
219
- throw new ProtocolError(Code.Invalid, `${type} entry in scope ${e.scope_id}: ${check(config, c)}`);
220
- return {
221
- scopeId: e.scope_id,
222
- name: e.name ?? "",
223
- config: c,
224
- secrets: e.secrets ?? [],
225
- ...(e.connection ? { connection: e.connection } : {}),
226
- };
227
- };
228
- this.#entryTypes.set(type, {
229
- validate: (c) => validateConfig(config, c, validate),
230
- // Decoded even with no hook, so a bad config fails configure rather than passing silently.
231
- configure: (entries, ctx) => configure(entries.filter((e) => e.type === type).map(decode), ctx),
232
- });
233
- (this.manifest.provides.extensions ??= []).push(ingress ? { type, ingress: true } : { type });
234
- return this;
235
- }
236
- /**
237
- * Registers a route handler and declares it: what an Event does (open
238
- * Work, reach the Work it already has, or nothing). A spec with samples
239
- * is declared as offering them, so route traces and the routes.decisions
240
- * certification apply; one with config has its routes' config checked.
241
- */
242
- route(handler, spec) {
243
- if (this.#routes.has(handler))
244
- throw new Error(`sdk: route handler ${handler} is registered twice`);
245
- const schema = spec.config;
246
- const decode = (p) => {
247
- const c = p.data ?? {};
248
- if (schema !== undefined && !matches(schema, c))
249
- throw new ProtocolError(Code.Invalid, `route config: ${check(schema, c)}`);
250
- return c;
251
- };
252
- this.#routes.set(handler, {
253
- validate: async (c) => {
254
- if (schema !== undefined)
255
- await validateConfig(schema, c);
256
- },
257
- match: async (input, ctx) => spec.match({ ...input, config: decode(input.route.config) }, ctx),
258
- samples: async (p, ctx) => spec.samples === undefined
259
- ? []
260
- : spec.samples({
261
- scope: p.scope,
262
- route: p.route,
263
- now: p.now,
264
- config: decode(p.route.config),
265
- }, ctx),
266
- });
267
- (this.manifest.provides.routes ??= []).push({
268
- handler,
269
- ...(schema === undefined ? {} : { config: true }),
270
- ...(spec.samples === undefined ? {} : { samples: true }),
271
- });
272
- return this;
273
- }
274
- /** Declares a kind of Work the extension's routes create, with its lifecycle. */
275
- workKind(kind, spec = {}) {
276
- if (spec.trigger !== undefined)
277
- this.#triggers.set(kind, spec.trigger);
278
- (this.manifest.provides.work_kinds ??= []).push({
279
- kind,
280
- ...(spec.standing ? { standing: true } : {}),
281
- ...(spec.trigger ? { trigger: true } : {}),
282
- ...(spec.timed ? { timed: true } : {}),
283
- ...(spec.runOnce ? { run_once: true } : {}),
284
- });
285
- return this;
286
- }
287
- /** Registers a doctor check and declares it. */
288
- check(name, fn, o = {}) {
289
- this.#checks.set(name, fn);
290
- (this.manifest.provides.checks ??= []).push(o.deep ? { name, deep: true } : { name });
291
- return this;
292
- }
293
- /** Registers a task the host runs every intervalSeconds (at least one) and declares it. */
294
- task(name, intervalSeconds, fn) {
295
- this.#tasks.set(name, fn);
296
- (this.manifest.provides.tasks ??= []).push({
297
- name,
298
- interval_seconds: Math.floor(intervalSeconds),
299
- });
300
- return this;
301
- }
302
- /** Declares event families the extension derives through host.accept or emits (an ingress type's come with it). */
303
- family(...families) {
304
- (this.manifest.provides.families ??= []).push(...families);
305
- return this;
306
- }
307
- /**
308
- * Declares a payload schema the extension writes and reads, named
309
- * <extension>.<thing> and written as <name>.v<N>: the versions it can
310
- * read, ascending, the highest being the one it writes. The host refuses
311
- * an Event (ingress, event.accept or emitted) whose data names any other.
312
- */
313
- schema(name, ...versions) {
314
- if (versions.length === 0 ||
315
- versions.some((v, i) => !Number.isInteger(v) || v < 1 || (i > 0 && v <= versions[i - 1])))
316
- throw new Error(`sdk: schema ${name} needs positive, strictly increasing versions`);
317
- (this.manifest.provides.schemas ??= []).push({
318
- name,
319
- versions: [...versions],
320
- });
321
- return this;
322
- }
323
- /** Upgrades the extension's KV namespaces to kvVersion. It must be idempotent: a crash mid-way retries it. */
324
- onMigrate(fn) {
325
- this.#migrate = fn;
326
- return this;
327
- }
328
- /** Sets the package's certification.json content (package-certification). */
329
- certification(file) {
330
- this.#certification = file;
331
- return this;
332
- }
333
- /** Serves the extension on input and output (tests pass a pair of in-memory streams). */
334
- serve(input, output) {
335
- return new Server(this, input, output);
336
- }
337
- /**
338
- * The entry point of a packaged extension: `package-manifest` prints the
339
- * manifest, `package-certification` the certification file, and anything
340
- * else serves on stdin and stdout until stdin closes, then exits.
341
- */
342
- async main(argv = process.argv.slice(2)) {
343
- if (argv.length === 1 && argv[0] === "package-manifest")
344
- return print(this.manifest);
345
- if (argv.length === 1 && argv[0] === "package-certification")
346
- return this.#certification === undefined
347
- ? undefined
348
- : print(this.#certification);
349
- // stdout carries the protocol, so a stray console.log would corrupt it: send those to stderr.
350
- const stdout = process.stdout;
351
- const protocolWrite = stdout.write.bind(stdout);
352
- stdout.write = process.stderr.write.bind(process.stderr);
353
- const out = new Writable({
354
- write(chunk, _encoding, done) {
355
- protocolWrite(chunk, done);
356
- },
357
- });
358
- await this.serve(process.stdin, out).done;
359
- // An extension never outlives its host, whatever timers it left running.
360
- process.exit(0);
361
- }
362
- /** @internal */
363
- _served() {
364
- return {
365
- operations: this.#operations,
366
- checks: this.#checks,
367
- tasks: this.#tasks,
368
- entryTypes: this.#entryTypes,
369
- routes: this.#routes,
370
- triggers: this.#triggers,
371
- migrate: this.#migrate,
372
- };
373
- }
374
- }
375
- /** protocol.SourceNamespace: the name itself, or it and "/" and more. */
376
- function inNamespace(name, ns) {
377
- return (ns === name || (ns.startsWith(`${name}/`) && ns.length > name.length + 1));
378
- }
379
- function json(schema) {
380
- // A round trip through JSON gives the schema exactly as the manifest file holds it.
381
- const plain = JSON.parse(JSON.stringify(schema));
382
- return isRecord(plain) ? plain : {};
383
- }
384
- function print(v) {
385
- return new Promise((resolve) => process.stdout.write(JSON.stringify(v, null, 2) + "\n", () => resolve()));
386
- }
387
- function notFound(method) {
388
- return new ProtocolError(Code.MethodNotFound, `no such method ${method}`);
389
- }
390
- /** Decodes a request's params, refusing malformed ones as jsonrpc.Params does in Go. */
391
- function params(schema, raw) {
392
- const p = raw ?? {};
393
- if (!matches(schema, p))
394
- throw new ProtocolError(Code.Invalid, "malformed params");
395
- return p;
396
- }
397
- /** One served connection. */
398
- export class Server {
399
- host;
400
- #ext;
401
- #conn;
402
- #ready = false;
403
- #draining = false;
404
- #stateDir = "";
405
- /** The sources the last configure registered, by name. */
406
- #sources = new Map();
407
- /** Emissions' commits, by commit ID, until the host has had its chance to call them. */
408
- #commits = new Map();
409
- constructor(ext, input, output) {
410
- this.#ext = ext;
411
- this.#conn = new Conn(input, output, (method, raw, signal) => this.#handle(method, raw, signal), {
412
- onProtocolError: (reason) => process.stderr.write(`open-conduit sdk: ${reason}\n`),
413
- });
414
- this.host = new Host((method, p, signal) => this.#conn.call(method, p, signal));
415
- }
416
- /** Resolves when the connection ends. */
417
- get done() {
418
- return this.#conn.done;
419
- }
420
- /** The private state directory the host gave at initialize. */
421
- get stateDir() {
422
- return this.#stateDir;
423
- }
424
- /** Ends the connection. */
425
- close() {
426
- this.#conn.close();
427
- }
428
- async #handle(method, raw, signal) {
429
- if (method === "initialize")
430
- return this.#initialize(params(InitializeParams, raw));
431
- // The host must know the manifest before anything else is served.
432
- if (!this.#ready)
433
- throw new ProtocolError(Code.Invalid, "initialize first");
434
- if (this.#draining)
435
- throw new ProtocolError(Code.ShuttingDown, "shutting down");
436
- const served = this.#ext._served();
437
- switch (method) {
438
- case "configure":
439
- return this.#configure(params(ConfigureParams, raw), signal);
440
- case "shutdown":
441
- this.#draining = true;
442
- return {};
443
- case "validate": {
444
- const p = params(ValidateParams, raw);
445
- // The host shows the operator a ConfigError's diagnostics; of any
446
- // other refusal, only that the config is invalid.
447
- if (p.kind === "extension")
448
- await served.entryTypes.get(p.type)?.validate(p.config);
449
- if (p.kind === "route")
450
- await served.routes.get(p.type)?.validate(p.config);
451
- return {};
452
- }
453
- case "operation.call":
454
- case "operation.wait":
455
- case "operation.emit": {
456
- const p = params(OperationParams, raw);
457
- const op = served.operations.get(p.operation);
458
- if (op === undefined)
459
- throw new ProtocolError(Code.Undeclared, "unknown operation");
460
- if (method !== `operation.${op.kind === "handler" ? "call" : op.kind}`)
461
- throw new ProtocolError(Code.Undeclared, "operation kind mismatch");
462
- const out = await op.run(p.input.data ?? {}, {
463
- host: this.host,
464
- authority: p.authority,
465
- requestId: p.request_id ?? "",
466
- signal,
467
- });
468
- if (op.kind === "handler")
469
- return { output: out };
470
- if (op.kind === "wait")
471
- return out;
472
- const { plan, commit } = out;
473
- if (commit === undefined)
474
- return plan;
475
- // Random, as Go's newID: a restarted process must never answer an ID the host holds from before with another emission's commit.
476
- const id = randomBytes(12).toString("hex");
477
- this.#commits.set(id, commit);
478
- // Dropped oldest first, whether the host called them or never did
479
- // (its transaction failed before acceptance).
480
- for (const old of this.#commits.keys()) {
481
- if (this.#commits.size <= 1024)
482
- break;
483
- this.#commits.delete(old);
484
- }
485
- return { ...plan, commit_id: id };
486
- }
487
- case "emit.commit": {
488
- const p = params(EmitCommitParams, raw);
489
- // It stays callable: the host may ask again when its transaction
490
- // runs again, possibly over a different acceptance.
491
- const commit = this.#commits.get(p.commit_id);
492
- if (commit === undefined)
493
- throw new ProtocolError(Code.NotFound, "unknown commit");
494
- return commit(p.emitted);
495
- }
496
- case "ingress.push": {
497
- const p = params(IngressPushParams, raw);
498
- const s = this.#source(p.name);
499
- if (s.type.push === undefined)
500
- throw notFound(method);
501
- const d = p.delivery;
502
- return s.type.push(s.spec, {
503
- id: d.id,
504
- receivedAt: d.received_at,
505
- ...(d.content_type ? { contentType: d.content_type } : {}),
506
- body: bytes(d.body),
507
- }, { host: this.host, signal });
508
- }
509
- case "ingress.reconcile": {
510
- const p = params(IngressReconcileParams, raw);
511
- const s = this.#source(p.name);
512
- if (s.type.reconcile === undefined)
513
- return { scan_id: p.scan.scan_id || "none", complete: false };
514
- return s.type.reconcile(s.spec, p.scan, { host: this.host, signal });
515
- }
516
- case "webhook.handle":
517
- return this.#webhook(params(WebhookHandleParams, raw), signal);
518
- case "route.match": {
519
- const p = params(RouteMatchParams, raw);
520
- const route = served.routes.get(p.handler);
521
- if (route === undefined)
522
- throw notFound(method);
523
- return route.match(p.input, { host: this.host, signal });
524
- }
525
- case "route.samples": {
526
- const p = params(RouteSamplesParams, raw);
527
- const route = served.routes.get(p.handler);
528
- if (route === undefined)
529
- throw notFound(method);
530
- return { samples: await route.samples(p, { host: this.host, signal }) };
531
- }
532
- case "work_kind.trigger": {
533
- const p = params(WorkKindTriggerParams, raw);
534
- const trigger = served.triggers.get(p.kind);
535
- if (trigger === undefined)
536
- throw notFound(method);
537
- return { index: trigger(p.inputs ?? []) };
538
- }
539
- case "task.run": {
540
- const fn = served.tasks.get(params(TaskRunParams, raw).task);
541
- if (fn === undefined)
542
- throw notFound(method);
543
- await fn({ host: this.host, signal });
544
- return {};
545
- }
546
- case "check.run": {
547
- const p = params(CheckRunParams, raw);
548
- const fn = served.checks.get(p.check);
549
- if (fn === undefined)
550
- throw notFound(method);
551
- try {
552
- return result(true, await fn({
553
- host: this.host,
554
- deep: p.deep === true,
555
- config: p.config,
556
- signal,
557
- }));
558
- }
559
- catch (err) {
560
- return result(false, err instanceof Error ? err.message : String(err));
561
- }
562
- }
563
- }
564
- throw notFound(method);
565
- }
566
- #initialize(p) {
567
- const offered = p.protocol_versions ?? [];
568
- const common = offered.filter((v) => this.#ext.manifest.protocol.includes(v));
569
- if (common.length === 0)
570
- throw new ProtocolError(Code.UnsupportedVersion, "no common protocol version");
571
- this.#ready = true;
572
- this.#stateDir = p.state_dir;
573
- return {
574
- protocol_version: Math.max(...common),
575
- manifest: this.#ext.manifest,
576
- };
577
- }
578
- async #configure(p, signal) {
579
- const { entryTypes, migrate } = this.#ext._served();
580
- const ctx = { host: this.host, signal };
581
- if (p.kv.stored < p.kv.declared) {
582
- // From layout 0 there is nothing stored to migrate, so no migration is needed.
583
- if (migrate === undefined && p.kv.stored !== 0)
584
- throw new ProtocolError(Code.Unsupported, "no KV migration");
585
- await migrate?.(p.kv.stored, p.kv.declared, ctx);
586
- }
587
- const sources = new Map();
588
- const decls = [];
589
- const paths = [];
590
- for (const entryType of entryTypes.values())
591
- for (const r of await entryType.configure(p.entries ?? [], ctx)) {
592
- const { decl, ...registered } = r;
593
- if (sources.has(decl.name))
594
- throw new ProtocolError(Code.Invalid, `source ${decl.name} is registered twice`);
595
- sources.set(decl.name, registered);
596
- decls.push(decl);
597
- if (registered.spec.webhook)
598
- paths.push(`/${decl.name}`);
599
- }
600
- // Replaced only once the whole generation is read, so a refused one keeps the last.
601
- this.#sources = sources;
602
- const out = {
603
- kv_version: this.#ext.manifest.kv_version ?? 0,
604
- };
605
- if (decls.length > 0)
606
- out.sources = decls;
607
- if (paths.length > 0)
608
- out.webhook_paths = paths;
609
- return out;
610
- }
611
- #source(name) {
612
- const s = this.#sources.get(name);
613
- if (s === undefined)
614
- throw new ProtocolError(Code.NotFound, "unknown source");
615
- return s;
616
- }
617
- async #webhook(p, signal) {
618
- // The source whose path is the request's, or the deepest one above it.
619
- let found;
620
- for (const [name, s] of this.#sources) {
621
- const path = `/${name}`;
622
- if (s.spec.webhook &&
623
- s.type.webhook !== undefined &&
624
- (p.path === path || p.path.startsWith(`${path}/`)) &&
625
- (found === undefined || name.length > found.spec.name.length))
626
- found = s;
627
- }
628
- if (found === undefined)
629
- return { status: 404 };
630
- const source = found;
631
- const headers = new Headers();
632
- for (const [k, vs] of Object.entries(p.header ?? {}))
633
- for (const v of vs)
634
- headers.append(k, v);
635
- const request = {
636
- path: p.path,
637
- method: p.method,
638
- query: p.query ?? "",
639
- headers,
640
- body: bytes(p.body),
641
- receivedAt: p.received_at,
642
- forwardId: p.forward_id ?? "",
643
- };
644
- try {
645
- const r = await source.type.webhook(source.spec, request, {
646
- host: this.host,
647
- signal,
648
- deliver: (d) => this.host.deliver(source.spec.name, { ...d, receivedAt: d.receivedAt ?? p.received_at }, signal),
649
- });
650
- const out = { status: r.status ?? 200 };
651
- if (r.headers !== undefined)
652
- out.header = Object.fromEntries(Object.entries(r.headers).map(([k, v]) => [
653
- k,
654
- Array.isArray(v) ? v : [v],
655
- ]));
656
- if (r.body !== undefined)
657
- out.body = base64(toBytes(r.body));
658
- return out;
659
- }
660
- catch (err) {
661
- // The sender retries a 5xx; nothing is accepted until deliver answers.
662
- process.stderr.write(`open-conduit sdk: webhook ${p.path}: ${err instanceof Error ? err.message : String(err)}\n`);
663
- return { status: 500 };
664
- }
665
- }
666
- }
667
- function bytes(b64) {
668
- return b64 === undefined
669
- ? new Uint8Array()
670
- : new Uint8Array(Buffer.from(b64, "base64"));
671
- }
672
- function result(ok, detail) {
673
- return detail === "" ? { ok } : { ok, detail };
674
- }