@open-conduit/sdk 7.0.0 → 7.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.
- package/dist/actions.d.ts +145 -0
- package/dist/actions.js +281 -0
- package/dist/actiontest.d.ts +80 -0
- package/dist/actiontest.js +190 -0
- package/dist/artifactstore.d.ts +133 -0
- package/dist/artifactstore.js +364 -0
- package/dist/backup.d.ts +99 -0
- package/dist/backup.js +178 -0
- package/dist/containertest.d.ts +71 -0
- package/dist/containertest.js +294 -0
- package/dist/errors.d.ts +28 -0
- package/dist/errors.js +37 -0
- package/dist/executor.d.ts +374 -0
- package/dist/executor.js +556 -0
- package/dist/executortest.d.ts +183 -0
- package/dist/executortest.js +534 -0
- package/dist/extension.d.ts +496 -1
- package/dist/extension.js +1152 -4
- package/dist/feed.d.ts +20 -0
- package/dist/feed.js +88 -0
- package/dist/forward.d.ts +38 -0
- package/dist/forward.js +163 -0
- package/dist/forwardca.d.ts +21 -0
- package/dist/forwardca.js +144 -0
- package/dist/hooks.d.ts +108 -0
- package/dist/hooks.js +13 -0
- package/dist/host.d.ts +166 -2
- package/dist/host.js +235 -2
- package/dist/index.d.ts +27 -3
- package/dist/index.js +14 -2
- package/dist/probe.d.ts +61 -0
- package/dist/probe.js +92 -0
- package/dist/providertest.d.ts +59 -0
- package/dist/providertest.js +168 -0
- package/dist/resources.d.ts +208 -0
- package/dist/resources.js +303 -0
- package/dist/sandbox.d.ts +84 -0
- package/dist/sandbox.js +85 -0
- package/dist/setup.d.ts +145 -0
- package/dist/setup.js +179 -0
- package/dist/setuptest.d.ts +90 -0
- package/dist/setuptest.js +319 -0
- package/dist/storetest.d.ts +64 -0
- package/dist/storetest.js +740 -0
- package/dist/telemetry.d.ts +86 -0
- package/dist/telemetry.js +46 -0
- package/dist/testing.d.ts +591 -2
- package/dist/testing.js +1460 -6
- package/dist/toolbelt.d.ts +91 -0
- package/dist/toolbelt.js +216 -0
- package/dist/tunnel.d.ts +62 -0
- package/dist/tunnel.js +93 -0
- package/dist/wire.d.ts +4060 -348
- package/dist/wire.js +1583 -0
- package/package.json +1 -1
package/dist/testing.js
CHANGED
|
@@ -5,20 +5,38 @@
|
|
|
5
5
|
// ingress.deliver, the state.* reads of seeded scopes, Work and Events,
|
|
6
6
|
// secrets from options, artifacts and wait.progress. A test then calls into
|
|
7
7
|
// the extension (configure, operation, route, samples, reconcile, webhook,
|
|
8
|
-
// trigger, task, check, validate,
|
|
9
|
-
//
|
|
8
|
+
// trigger, task, check, validate, a secret scheme's serve, store and
|
|
9
|
+
// delete, a credential verifier's verify, a container provider's
|
|
10
|
+
// container_provider.* methods, a resource provider's provider.* methods
|
|
11
|
+
// with the provider.owner_status and site.run they call back, a sandbox
|
|
12
|
+
// provider's plan and adopt, a tunnel provider's tunnel.run with the URLs
|
|
13
|
+
// it publishes, an exporter's telemetry.export, telemetry.metrics,
|
|
14
|
+
// telemetry.sink, a run environment's run.environment checked as the host
|
|
15
|
+
// checks it, and call for any other method) and inspects what it wrote
|
|
16
|
+
// (kv, events, artifacts, progress, captured). The
|
|
17
|
+
// container provider checks (checkContainerProvider, checkContainerPlacer,
|
|
18
|
+
// checkContainerForwarder) hold a provider to the contract the Go
|
|
19
|
+
// conformance suite does, the forward's served under a CA of its own, and
|
|
20
|
+
// checkResourceProvider, checkSandboxProvider and checkTunnelProvider to
|
|
21
|
+
// the contract the host's adapters rely on.
|
|
10
22
|
//
|
|
11
23
|
// It is not the host: causal depth and rate limits, timers, Work control and
|
|
12
24
|
// config.* are not served (they answer unsupported). Nothing here reads a
|
|
13
25
|
// real clock, the network or the operator's config: the clock is a
|
|
14
26
|
// TestClock the test moves, fixed at testStart until it does.
|
|
15
|
-
import { createHash } from "node:crypto";
|
|
27
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
16
28
|
import { PassThrough } from "node:stream";
|
|
17
|
-
import { Code, ProtocolError } from "./errors.js";
|
|
29
|
+
import { Code, CredentialRefusal, OperationError, ProtocolError, SecretRefusal, } from "./errors.js";
|
|
30
|
+
import { ContainerLabel } from "./extension.js";
|
|
31
|
+
import { checkPublicURL } from "./tunnel.js";
|
|
32
|
+
import { appliedEnv, checkRunFiles } from "./telemetry.js";
|
|
33
|
+
import { candidateOf } from "./setup.js";
|
|
34
|
+
import { TestConfigService, TestSetupSession, } from "./setuptest.js";
|
|
35
|
+
import { testExecutor, } from "./executortest.js";
|
|
18
36
|
import { base64, toBytes } from "./host.js";
|
|
19
|
-
import { Conn } from "./jsonrpc.js";
|
|
37
|
+
import { Conn, MaxChunkBytes } from "./jsonrpc.js";
|
|
20
38
|
import { matches, t } from "./schema.js";
|
|
21
|
-
import { ConfigureResult, EmitCommit, EmitPlan, EventAcceptParams, IngressDeliverParams, KVCommitParams, KVGetParams, KVListParams, OperationResult, PushResult, RouteDecision, RouteSample, SecretResolveParams, Snapshot, StateParams, WaitPlan, WebhookHandleResult, } from "./wire.js";
|
|
39
|
+
import { BackupFilesResult, BackupListResult, BackupReadResult, ConfigureResult, ContainerCreated, ContainerForward, ContainerList, ContainerPlan, ContainerState, EmitCommit, EmitPlan, EventAcceptParams, ExecutorKnownParams, PersistRecoveryParams, OwnerStatusParams, ProviderUnsavedResult, ResourceAcquireParams, ResourceReport, ResourceResult, ResourceSweepReport, RunEnvironmentResult, ConfigCandidateResult, SetupRunResult, SandboxPlan, SiteRunParams, TunnelURLParams, ValidateResult, ResourceLookupParams, IngressDeliverParams, KVCommitParams, KVGetParams, KVListParams, OperationResult, Placement, PushResult, RouteDecision, RouteSample, LaunchParams, SandboxAdoptParams, ContainerAdoptParams, ContainerReattachParams, CredentialVerifyResult, SecretDeleteResult, SecretResolveParams, SecretServeResult, SecretStoreResult, SiteResult, Snapshot, StateParams, WaitPlan, WebhookHandleResult, ProbeRunResult, ViewRenderResult, WorkActResult, WorkActionsResult, WorkAnnotateResult, WorkRequestsResult, ActionListParams, ActionSubmitParams, DependencyFilterResult, EventRenderOwnedParams, EventRenderResult, OperationGateResult, RecurrenceNextResult, RequestListParams, ScopeAuthorizeParams, TargetResolveParams, TargetResolveResult, TimerArmParams, TimerCancelParams, WorkAdmitResult, WorkCancelParams, WorkSettleHoldParams, } from "./wire.js";
|
|
22
40
|
/** The test clock's start (sdktest.Start, conformance.NewClock's start). */
|
|
23
41
|
export const testStart = "2026-10-24T12:00:00.000Z";
|
|
24
42
|
/** The host's clock. It moves only when the test moves it. */
|
|
@@ -40,6 +58,25 @@ export class TestClock {
|
|
|
40
58
|
this.#ms = new Date(at).getTime();
|
|
41
59
|
}
|
|
42
60
|
}
|
|
61
|
+
/** Reads exactly n bytes from it, or fewer at its end. */
|
|
62
|
+
async function readUpTo(it, held, n) {
|
|
63
|
+
const out = new Uint8Array(n);
|
|
64
|
+
let got = 0;
|
|
65
|
+
while (got < n) {
|
|
66
|
+
if (held.rest.length === 0) {
|
|
67
|
+
const r = await it.next();
|
|
68
|
+
if (r.done)
|
|
69
|
+
break;
|
|
70
|
+
held.rest = r.value;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
const take = Math.min(n - got, held.rest.length);
|
|
74
|
+
out.set(held.rest.subarray(0, take), got);
|
|
75
|
+
held.rest = held.rest.subarray(take);
|
|
76
|
+
got += take;
|
|
77
|
+
}
|
|
78
|
+
return out.subarray(0, got);
|
|
79
|
+
}
|
|
43
80
|
/** A KV value's version: a digest of its content, as sdktest.Version. */
|
|
44
81
|
export function kvVersion(value) {
|
|
45
82
|
return createHash("sha256").update(value).digest("hex").slice(0, 32);
|
|
@@ -94,16 +131,38 @@ export class TestHost {
|
|
|
94
131
|
#writers = new Map();
|
|
95
132
|
#artifacts = [];
|
|
96
133
|
#progress = new Map();
|
|
134
|
+
#captured = [];
|
|
135
|
+
#config;
|
|
136
|
+
#setups = new Map();
|
|
137
|
+
#timers = new Map();
|
|
138
|
+
/** The Work the extension's start gate holds, by ID: the hold's reason. */
|
|
139
|
+
#holds = new Map();
|
|
140
|
+
#settled = new Map();
|
|
141
|
+
/** The settlements by key, as the runtime dedupes them. */
|
|
142
|
+
#settleKeys = new Map();
|
|
143
|
+
#cancelled = new Map();
|
|
144
|
+
/** The probe runs in progress through a connection, by grant: what secret.resolve may read under it. */
|
|
145
|
+
#probeGrants = new Map();
|
|
97
146
|
/** The webhook paths the last configure registered. */
|
|
98
147
|
#paths = [];
|
|
99
148
|
#kvVersion;
|
|
100
149
|
#calls = 0;
|
|
150
|
+
/** The runs executor.* calls started, by run ID: where their persist_recovery goes. */
|
|
151
|
+
#runs = new Map();
|
|
152
|
+
#sweeps = new Map();
|
|
153
|
+
/** The reconciles and sweeps in progress, by ID: what provider.owner_status quoting it answers. */
|
|
154
|
+
#reconciles = new Map();
|
|
155
|
+
/** The acquisitions in progress at a site, by call ID: where site.run quoting it runs. */
|
|
156
|
+
#siteCalls = new Map();
|
|
157
|
+
/** The tunnel runs the host holds open, by run ID: where tunnel.url quoting it goes. */
|
|
158
|
+
#tunnelRuns = new Map();
|
|
101
159
|
constructor(ext, o) {
|
|
102
160
|
this.#ext = ext;
|
|
103
161
|
this.#o = o;
|
|
104
162
|
this.clock = o.clock ?? new TestClock();
|
|
105
163
|
this.stateDir = o.stateDir ?? "/sdktest/state";
|
|
106
164
|
this.#kvVersion = o.kvVersion ?? 0;
|
|
165
|
+
this.#config = new TestConfigService(o.config);
|
|
107
166
|
this.#works = [...(o.works ?? [])];
|
|
108
167
|
for (const s of o.scopes ?? [])
|
|
109
168
|
this.#scopes.add(s);
|
|
@@ -128,8 +187,50 @@ export class TestHost {
|
|
|
128
187
|
protocol_versions: [1],
|
|
129
188
|
host: { name: "sdktest", version: "0" },
|
|
130
189
|
state_dir: this.stateDir,
|
|
190
|
+
...(this.#o.configDir ? { config_dir: this.#o.configDir } : {}),
|
|
191
|
+
...this.#containerInit(),
|
|
192
|
+
...this.#executorInit(),
|
|
193
|
+
...this.#resourceInit(),
|
|
131
194
|
});
|
|
132
195
|
}
|
|
196
|
+
#executorInit() {
|
|
197
|
+
const names = (this.#ext.manifest.provides.executors ?? []).map((x) => x.name);
|
|
198
|
+
if (names.length === 0)
|
|
199
|
+
return {};
|
|
200
|
+
return {
|
|
201
|
+
executor_dirs: Object.fromEntries(names.map((n) => [
|
|
202
|
+
n,
|
|
203
|
+
this.#o.executorDirs?.[n] ?? `${this.stateDir}/executors/${n}`,
|
|
204
|
+
])),
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
#resourceInit() {
|
|
208
|
+
const types = (this.#ext.manifest.provides.resources ?? []).map((r) => r.type);
|
|
209
|
+
if (types.length === 0)
|
|
210
|
+
return {};
|
|
211
|
+
return {
|
|
212
|
+
resource_dirs: Object.fromEntries(types.map((typ) => [
|
|
213
|
+
typ,
|
|
214
|
+
this.#o.resourceDirs?.[typ] ?? `${this.stateDir}/resources/${typ}`,
|
|
215
|
+
])),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
#containerInit() {
|
|
219
|
+
const o = this.#o;
|
|
220
|
+
if (!this.#ext.manifest.provides.containers?.length)
|
|
221
|
+
return {};
|
|
222
|
+
return {
|
|
223
|
+
...(o.containerDirs ? { container_dirs: o.containerDirs } : {}),
|
|
224
|
+
container_host: this.containerHost,
|
|
225
|
+
...(o.containerFormerHosts?.length
|
|
226
|
+
? { container_former_hosts: o.containerFormerHosts }
|
|
227
|
+
: {}),
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
/** The host's container label the extension was given. */
|
|
231
|
+
get containerHost() {
|
|
232
|
+
return this.#o.containerHost ?? "sdktest-host";
|
|
233
|
+
}
|
|
133
234
|
/** Ends the served connection. */
|
|
134
235
|
close() {
|
|
135
236
|
this.#toExt.end();
|
|
@@ -154,6 +255,7 @@ export class TestHost {
|
|
|
154
255
|
entries,
|
|
155
256
|
...(o.disabled ? { disabled: o.disabled } : {}),
|
|
156
257
|
...(o.publicUrl ? { public_url: o.publicUrl } : {}),
|
|
258
|
+
...(o.containers?.length ? { containers: o.containers } : {}),
|
|
157
259
|
kv: {
|
|
158
260
|
stored: this.#kvVersion,
|
|
159
261
|
declared: this.#ext.manifest.kv_version ?? 0,
|
|
@@ -297,6 +399,998 @@ export class TestHost {
|
|
|
297
399
|
config: o.config ?? {},
|
|
298
400
|
}));
|
|
299
401
|
}
|
|
402
|
+
/**
|
|
403
|
+
* Asks the extension's secret scheme for the value reference names
|
|
404
|
+
* (secret.serve), as the host's resolver does: the value, or the code it
|
|
405
|
+
* refused with. An answer with both, or neither, fails the call.
|
|
406
|
+
*/
|
|
407
|
+
async serveSecret(scheme, reference) {
|
|
408
|
+
const out = result(SecretServeResult, "secret.serve", await this.#conn.call("secret.serve", { scheme, reference }));
|
|
409
|
+
if (!out.value === !out.code)
|
|
410
|
+
throw invalid("secret.serve answered both a value and a code, or neither");
|
|
411
|
+
return out;
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Asks a writable secret scheme to store value under name for owner
|
|
415
|
+
* (secret.store): the reference that reads it back, or the code it
|
|
416
|
+
* refused with. Unless given, owner is "sdktest-store" and there is no
|
|
417
|
+
* config.
|
|
418
|
+
*/
|
|
419
|
+
async storeSecret(scheme, name, value, o = {}) {
|
|
420
|
+
const out = result(SecretStoreResult, "secret.store", await this.#conn.call("secret.store", {
|
|
421
|
+
scheme,
|
|
422
|
+
name,
|
|
423
|
+
value,
|
|
424
|
+
...(o.config === undefined ? {} : { config: o.config }),
|
|
425
|
+
owner: o.owner ?? "sdktest-store",
|
|
426
|
+
}));
|
|
427
|
+
if (!out.reference === !out.code)
|
|
428
|
+
throw invalid("secret.store answered both a reference and a code, or neither");
|
|
429
|
+
return out;
|
|
430
|
+
}
|
|
431
|
+
/** Asks a writable secret scheme to remove what reference names (secret.delete): empty, or the code it refused with. */
|
|
432
|
+
async deleteSecret(scheme, reference, o = {}) {
|
|
433
|
+
return result(SecretDeleteResult, "secret.delete", await this.#conn.call("secret.delete", {
|
|
434
|
+
scheme,
|
|
435
|
+
reference,
|
|
436
|
+
owner: o.owner ?? "sdktest-store",
|
|
437
|
+
}));
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* The extension's secret scheme as the host reaches it over the wire
|
|
441
|
+
* (sdktest.Host.SecretProvider): each call is one secret.serve,
|
|
442
|
+
* secret.store or secret.delete, a refused one throwing SecretRefusal
|
|
443
|
+
* with its code.
|
|
444
|
+
*/
|
|
445
|
+
secretProvider(scheme) {
|
|
446
|
+
const refuse = (code) => {
|
|
447
|
+
if (code)
|
|
448
|
+
throw new SecretRefusal(code);
|
|
449
|
+
};
|
|
450
|
+
return {
|
|
451
|
+
serve: async (reference) => {
|
|
452
|
+
const out = await this.serveSecret(scheme, reference);
|
|
453
|
+
refuse(out.code);
|
|
454
|
+
return out.value;
|
|
455
|
+
},
|
|
456
|
+
store: async (name, value, o = {}) => {
|
|
457
|
+
const out = await this.storeSecret(scheme, name, value, o);
|
|
458
|
+
refuse(out.code);
|
|
459
|
+
return out.reference;
|
|
460
|
+
},
|
|
461
|
+
delete: async (reference, o = {}) => {
|
|
462
|
+
refuse((await this.deleteSecret(scheme, reference, o)).code);
|
|
463
|
+
},
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Asks the extension's credential verifier of type about token
|
|
468
|
+
* (credential.verify) under a trusted issuer's config, as the host does
|
|
469
|
+
* (sdktest.Host.Verify): the answer, or the ProtocolError it refused
|
|
470
|
+
* with. Unless given, the issuer's ID is "sdktest-issuer" and its config
|
|
471
|
+
* empty. The answer must name a subject and a valid expires_at.
|
|
472
|
+
*/
|
|
473
|
+
async verify(type, token, o = {}) {
|
|
474
|
+
const out = result(CredentialVerifyResult, "credential.verify", await this.#conn.call("credential.verify", {
|
|
475
|
+
type,
|
|
476
|
+
issuer: o.issuer ?? "sdktest-issuer",
|
|
477
|
+
config: {
|
|
478
|
+
schema: "core.auth.issuer.v1",
|
|
479
|
+
data: o.config ?? {},
|
|
480
|
+
},
|
|
481
|
+
token,
|
|
482
|
+
}));
|
|
483
|
+
if (Number.isNaN(Date.parse(out.expires_at)))
|
|
484
|
+
throw invalid("credential.verify answered without a valid expires_at");
|
|
485
|
+
return out;
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* The extension's credential verifier of type, under one trusted
|
|
489
|
+
* issuer's config, as the host reaches it over the wire: each verify is
|
|
490
|
+
* one credential.verify, a refusal or failure thrown as
|
|
491
|
+
* CredentialRefusal.
|
|
492
|
+
*/
|
|
493
|
+
/**
|
|
494
|
+
* The extension's actions, requests and panels as the host reaches them
|
|
495
|
+
* over the wire (extproc's remoteActions): each call one work.actions,
|
|
496
|
+
* work.act, work.requests or view.render, its answer checked as the host
|
|
497
|
+
* reads it. An invocation's refusal throws the OperationError (or
|
|
498
|
+
* ProtocolError) it crossed as. An extension that serves no requests or
|
|
499
|
+
* no panels shows none, as the host treats it.
|
|
500
|
+
*/
|
|
501
|
+
actionProvider() {
|
|
502
|
+
const provides = this.#ext.manifest.provides;
|
|
503
|
+
return {
|
|
504
|
+
actions: async (target) => {
|
|
505
|
+
if (!provides.actions)
|
|
506
|
+
return [];
|
|
507
|
+
const out = result(WorkActionsResult, "work.actions", await this.#conn.call("work.actions", { target }));
|
|
508
|
+
const actions = out.actions ?? [];
|
|
509
|
+
if (!provides.secret_actions && actions.some((a) => a.secret))
|
|
510
|
+
throw new ProtocolError("undeclared_secret_action", "an action asks for a secret without secret_actions");
|
|
511
|
+
return actions;
|
|
512
|
+
},
|
|
513
|
+
invoke: async (c) => {
|
|
514
|
+
if (!provides.actions)
|
|
515
|
+
throw invalid("the extension declares no actions");
|
|
516
|
+
const out = result(WorkActResult, "work.act", await this.#conn.call("work.act", {
|
|
517
|
+
target: c.target,
|
|
518
|
+
action: c.action,
|
|
519
|
+
...(c.input ? { input: c.input } : {}),
|
|
520
|
+
caller: c.caller,
|
|
521
|
+
}));
|
|
522
|
+
const e = out.event;
|
|
523
|
+
if (e.id ||
|
|
524
|
+
e.source ||
|
|
525
|
+
e.delivery_id ||
|
|
526
|
+
e.causation_id ||
|
|
527
|
+
e.execution_id ||
|
|
528
|
+
e.work_id)
|
|
529
|
+
throw invalid("work.act planned an Event with host-assigned fields");
|
|
530
|
+
if (!(provides.families ?? []).some((f) => f.type === e.type))
|
|
531
|
+
throw new ProtocolError(Code.Undeclared, "family not declared");
|
|
532
|
+
return {
|
|
533
|
+
event: {
|
|
534
|
+
type: e.type,
|
|
535
|
+
...(e.correlation_key
|
|
536
|
+
? { correlation_key: e.correlation_key }
|
|
537
|
+
: {}),
|
|
538
|
+
...(e.data === undefined ? {} : { data: e.data }),
|
|
539
|
+
},
|
|
540
|
+
...(out.message ? { message: out.message } : {}),
|
|
541
|
+
};
|
|
542
|
+
},
|
|
543
|
+
requests: async (target) => {
|
|
544
|
+
if (!provides.actions)
|
|
545
|
+
return [];
|
|
546
|
+
let raw;
|
|
547
|
+
try {
|
|
548
|
+
raw = await this.#conn.call("work.requests", { target });
|
|
549
|
+
}
|
|
550
|
+
catch (err) {
|
|
551
|
+
if (err instanceof ProtocolError && err.code === Code.MethodNotFound)
|
|
552
|
+
return [];
|
|
553
|
+
throw err;
|
|
554
|
+
}
|
|
555
|
+
const out = result(WorkRequestsResult, "work.requests", raw);
|
|
556
|
+
return (out.requests ?? []).map((r) => {
|
|
557
|
+
const { settled_at, ...rest } = r;
|
|
558
|
+
return {
|
|
559
|
+
...rest,
|
|
560
|
+
state: r.state,
|
|
561
|
+
...(settled_at ? { settledAt: new Date(settled_at) } : {}),
|
|
562
|
+
};
|
|
563
|
+
});
|
|
564
|
+
},
|
|
565
|
+
panels: async (target) => {
|
|
566
|
+
if (!provides.panels)
|
|
567
|
+
return [];
|
|
568
|
+
const out = result(ViewRenderResult, "view.render", await this.#conn.call("view.render", { target }));
|
|
569
|
+
return (out.panels ?? []).map((p) => ({
|
|
570
|
+
...p,
|
|
571
|
+
sections: p.sections.map(({ messages, ...s }) => ({
|
|
572
|
+
...s,
|
|
573
|
+
...(messages
|
|
574
|
+
? {
|
|
575
|
+
messages: messages.map((m) => {
|
|
576
|
+
const { at, ...line } = m;
|
|
577
|
+
return {
|
|
578
|
+
...line,
|
|
579
|
+
from: m.from,
|
|
580
|
+
...(at ? { at: new Date(at) } : {}),
|
|
581
|
+
};
|
|
582
|
+
}),
|
|
583
|
+
}
|
|
584
|
+
: {}),
|
|
585
|
+
})),
|
|
586
|
+
}));
|
|
587
|
+
},
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
/** Asks for the extension's annotations of work (work.annotate), as the host does. */
|
|
591
|
+
async annotate(work) {
|
|
592
|
+
const out = result(WorkAnnotateResult, "work.annotate", await this.#conn.call("work.annotate", { work }));
|
|
593
|
+
return out.annotations ?? [];
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Runs one of the extension's probes (probe.serve) as the host's
|
|
597
|
+
* probe.run does: arguments it doesn't declare, or a required one
|
|
598
|
+
* missing, are refused before the probe sees them. With connection, the
|
|
599
|
+
* run goes through that connection in scopeId, and the probe may read
|
|
600
|
+
* its values (default none) until the run ends.
|
|
601
|
+
*/
|
|
602
|
+
async probe(name, args = {}, o = {}) {
|
|
603
|
+
const decl = this.#ext.manifest.provides.probes?.find((p) => p.name === name);
|
|
604
|
+
if (decl === undefined)
|
|
605
|
+
throw new ProtocolError(Code.NotFound, "no such probe");
|
|
606
|
+
for (const a of decl.args ?? [])
|
|
607
|
+
if (a.required && !args[a.name])
|
|
608
|
+
throw invalid(`argument ${a.name} is required`);
|
|
609
|
+
for (const k of Object.keys(args))
|
|
610
|
+
if (!(decl.args ?? []).some((a) => a.name === k))
|
|
611
|
+
throw invalid(`the probe takes no argument ${k}`);
|
|
612
|
+
const grant = o.connection === undefined ? "" : randomBytes(8).toString("hex");
|
|
613
|
+
if (o.connection !== undefined)
|
|
614
|
+
this.#probeGrants.set(grant, {
|
|
615
|
+
scopeId: o.scopeId ?? "",
|
|
616
|
+
connection: o.connection.id,
|
|
617
|
+
values: o.values ?? {},
|
|
618
|
+
});
|
|
619
|
+
try {
|
|
620
|
+
return result(ProbeRunResult, "probe.serve", await this.#conn.call("probe.serve", {
|
|
621
|
+
name,
|
|
622
|
+
...(Object.keys(args).length ? { args } : {}),
|
|
623
|
+
...(o.scopeId ? { scope_id: o.scopeId } : {}),
|
|
624
|
+
...(o.connection ? { connection: o.connection, grant } : {}),
|
|
625
|
+
}));
|
|
626
|
+
}
|
|
627
|
+
finally {
|
|
628
|
+
this.#probeGrants.delete(grant);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
credentialVerifier(type, o = {}) {
|
|
632
|
+
return {
|
|
633
|
+
verify: async (token) => {
|
|
634
|
+
let out;
|
|
635
|
+
try {
|
|
636
|
+
out = await this.verify(type, token, o);
|
|
637
|
+
}
|
|
638
|
+
catch (err) {
|
|
639
|
+
if (err instanceof ProtocolError &&
|
|
640
|
+
(err.code === Code.Unauthorized || err.code === Code.Internal))
|
|
641
|
+
throw new CredentialRefusal(err.code);
|
|
642
|
+
throw err;
|
|
643
|
+
}
|
|
644
|
+
return {
|
|
645
|
+
subject: out.subject,
|
|
646
|
+
groups: out.groups ?? [],
|
|
647
|
+
expiresAt: new Date(out.expires_at),
|
|
648
|
+
};
|
|
649
|
+
},
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* The extension's container provider of type as the host reaches it over
|
|
654
|
+
* the wire (extproc's remoteContainer): each call one
|
|
655
|
+
* container_provider.* request, its answer checked as the host reads it.
|
|
656
|
+
*/
|
|
657
|
+
containerProvider(type) {
|
|
658
|
+
const call = async (schema, method, p) => result(schema, `container_provider.${method}`, await this.#conn.call(`container_provider.${method}`, { type, ...p }));
|
|
659
|
+
const done = t.object({}, { open: true });
|
|
660
|
+
return {
|
|
661
|
+
plan: (owner, policy, needs, launch) => call(ContainerPlan, "plan", {
|
|
662
|
+
owner,
|
|
663
|
+
config: containerPayload(policy.config),
|
|
664
|
+
paths: policy.paths ?? {},
|
|
665
|
+
needs,
|
|
666
|
+
launch,
|
|
667
|
+
...(policy.placement ? { placement: policy.placement } : {}),
|
|
668
|
+
}),
|
|
669
|
+
create: (plan, labels) => call(ContainerCreated, "create", { plan, labels }),
|
|
670
|
+
signal: async (ref, signal) => {
|
|
671
|
+
await call(done, "signal", { ref, signal });
|
|
672
|
+
},
|
|
673
|
+
stop: async (ref, graceMs) => {
|
|
674
|
+
await call(done, "stop", {
|
|
675
|
+
ref,
|
|
676
|
+
...(graceMs > 0 ? { grace_millis: Math.floor(graceMs) } : {}),
|
|
677
|
+
});
|
|
678
|
+
},
|
|
679
|
+
inspect: (ref) => call(ContainerState, "inspect", { ref }),
|
|
680
|
+
list: async (owner) => (await call(ContainerList, "list", { owner })).containers.filter((s) => hostLabelled(owner, s)),
|
|
681
|
+
remove: async (ref) => {
|
|
682
|
+
await call(done, "remove", { ref });
|
|
683
|
+
},
|
|
684
|
+
forward: async (config) => (await call(ContainerForward, "forward", {
|
|
685
|
+
config: containerPayload(config),
|
|
686
|
+
})).address ?? "",
|
|
687
|
+
place: (owner, config, prefer) => call(Placement, "place", {
|
|
688
|
+
owner,
|
|
689
|
+
config: containerPayload(config),
|
|
690
|
+
...(prefer ? { prefer } : {}),
|
|
691
|
+
}),
|
|
692
|
+
siteRun: async (placement, c) => {
|
|
693
|
+
const stdin = c.stdin === undefined ? undefined : toBytes(c.stdin);
|
|
694
|
+
const out = await call(SiteResult, "site_run", {
|
|
695
|
+
placement,
|
|
696
|
+
command: {
|
|
697
|
+
argv: c.argv,
|
|
698
|
+
...(c.dir ? { dir: c.dir } : {}),
|
|
699
|
+
...(c.env?.length ? { env: c.env } : {}),
|
|
700
|
+
...(stdin?.length ? { stdin: base64(stdin) } : {}),
|
|
701
|
+
...(c.timeoutMs ? { timeout_millis: Math.floor(c.timeoutMs) } : {}),
|
|
702
|
+
},
|
|
703
|
+
});
|
|
704
|
+
return {
|
|
705
|
+
exitCode: out.exit_code,
|
|
706
|
+
stdout: bytes(out.stdout),
|
|
707
|
+
stderr: bytes(out.stderr),
|
|
708
|
+
truncated: out.truncated === true,
|
|
709
|
+
};
|
|
710
|
+
},
|
|
711
|
+
collect: async (ref) => {
|
|
712
|
+
await call(done, "collect", { ref });
|
|
713
|
+
},
|
|
714
|
+
reattach: (ref, at) => call(ContainerCreated, "reattach", {
|
|
715
|
+
ref,
|
|
716
|
+
pin: at.pin,
|
|
717
|
+
paths: at.paths,
|
|
718
|
+
...(at.tokenFile ? { token_file: at.tokenFile } : {}),
|
|
719
|
+
...(at.sameHost ? { same_host: true } : {}),
|
|
720
|
+
}),
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* The extension's resource provider of type as the host reaches it over
|
|
725
|
+
* the wire (extproc's remoteProvider): each call one provider.* or
|
|
726
|
+
* validate request. reconcile and sweep answer the provider's
|
|
727
|
+
* provider.owner_status from status while they run, and an acquisition
|
|
728
|
+
* given a site runs its site.run there, as the host does.
|
|
729
|
+
*/
|
|
730
|
+
resourceProvider(type) {
|
|
731
|
+
const decl = this.#ext.manifest.provides.resources?.find((r) => r.type === type);
|
|
732
|
+
const call = async (schema, method, p) => result(schema, method, await this.#conn.call(method, { type, ...p }));
|
|
733
|
+
const passes = async (status, fn) => {
|
|
734
|
+
const id = randomBytes(8).toString("hex");
|
|
735
|
+
this.#reconciles.set(id, status);
|
|
736
|
+
try {
|
|
737
|
+
return await fn(id);
|
|
738
|
+
}
|
|
739
|
+
finally {
|
|
740
|
+
this.#reconciles.delete(id);
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
const validate = (kind, config, mode) => call(ValidateResult, "validate", {
|
|
744
|
+
kind,
|
|
745
|
+
config: config ?? {},
|
|
746
|
+
...(mode ? { mode } : {}),
|
|
747
|
+
});
|
|
748
|
+
return {
|
|
749
|
+
acquire: async (owner, config, r = {}) => {
|
|
750
|
+
let siteCall;
|
|
751
|
+
if (r.site !== undefined && decl?.sites) {
|
|
752
|
+
siteCall = randomBytes(8).toString("hex");
|
|
753
|
+
this.#siteCalls.set(siteCall, { type, site: r.site });
|
|
754
|
+
}
|
|
755
|
+
try {
|
|
756
|
+
const out = await call(ResourceResult, "provider.acquire", {
|
|
757
|
+
owner,
|
|
758
|
+
config: { schema: "core.config.resource.v1", data: config ?? {} },
|
|
759
|
+
...(r.mode ? { mode: r.mode } : {}),
|
|
760
|
+
params: r.params ?? {},
|
|
761
|
+
...(r.hostEnv && Object.keys(r.hostEnv).length > 0
|
|
762
|
+
? { host_env: r.hostEnv }
|
|
763
|
+
: {}),
|
|
764
|
+
...(r.files?.length ? { files: r.files } : {}),
|
|
765
|
+
...(siteCall ? { site: { id: r.site, call: siteCall } } : {}),
|
|
766
|
+
});
|
|
767
|
+
return {
|
|
768
|
+
resource: out.resource,
|
|
769
|
+
log: out.log ?? "",
|
|
770
|
+
setupFailed: out.setup_failed === true,
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
finally {
|
|
774
|
+
if (siteCall)
|
|
775
|
+
this.#siteCalls.delete(siteCall);
|
|
776
|
+
}
|
|
777
|
+
},
|
|
778
|
+
lookup: async (owner, ref) => (await call(ResourceResult, "provider.lookup", { owner, ref }))
|
|
779
|
+
.resource,
|
|
780
|
+
reconcile: (status) => passes(status, (id) => call(ResourceReport, "provider.reconcile", { reconcile: id })),
|
|
781
|
+
sweep: (status) => passes(status, (id) => call(ResourceSweepReport, "provider.sweep", { reconcile: id })),
|
|
782
|
+
unsaved: async () => (await call(ProviderUnsavedResult, "provider.unsaved", {})).resources ??
|
|
783
|
+
[],
|
|
784
|
+
modeDefault: async (config) => (await validate("resource_mode", config)).mode ?? "",
|
|
785
|
+
sandboxWorkspace: async (config, mode) => {
|
|
786
|
+
await validate("resource_sandbox", config, mode);
|
|
787
|
+
},
|
|
788
|
+
needsSite: async (config) => (await validate("resource_site", config)).site === true,
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* The extension's sandbox provider of type as the host reaches it over
|
|
793
|
+
* the wire (extproc's remoteSandbox): plan answers the plan with the
|
|
794
|
+
* digest the host pins (sandboxDigest), and adopt is one call.
|
|
795
|
+
*/
|
|
796
|
+
sandboxProvider(type) {
|
|
797
|
+
return {
|
|
798
|
+
plan: async (owner, policy, needs, launch) => {
|
|
799
|
+
const plan = result(SandboxPlan, "sandbox_provider.plan", await this.#conn.call("sandbox_provider.plan", {
|
|
800
|
+
type,
|
|
801
|
+
owner,
|
|
802
|
+
config: {
|
|
803
|
+
schema: "core.config.sandbox.v1",
|
|
804
|
+
data: policy.config ?? {},
|
|
805
|
+
},
|
|
806
|
+
paths: policy.paths ?? {},
|
|
807
|
+
needs,
|
|
808
|
+
launch,
|
|
809
|
+
}));
|
|
810
|
+
return { ...plan, digest: sandboxDigest(plan.argv ?? [], plan.data) };
|
|
811
|
+
},
|
|
812
|
+
adopt: async (plan, parent, root) => {
|
|
813
|
+
await this.#conn.call("sandbox_provider.adopt", {
|
|
814
|
+
type,
|
|
815
|
+
plan,
|
|
816
|
+
parent,
|
|
817
|
+
root,
|
|
818
|
+
});
|
|
819
|
+
},
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* The extension's tunnel provider of type as the host runs it (extproc's
|
|
824
|
+
* remoteTunnel): start holds one tunnel.run open, taking the URLs the
|
|
825
|
+
* run publishes as the host does (refusing one checkPublicURL refuses),
|
|
826
|
+
* until stop cancels it.
|
|
827
|
+
*/
|
|
828
|
+
tunnelProvider(type) {
|
|
829
|
+
return {
|
|
830
|
+
start: (addr, config) => {
|
|
831
|
+
const run = randomBytes(8).toString("hex");
|
|
832
|
+
const urls = [];
|
|
833
|
+
const refused = [];
|
|
834
|
+
// next hands out each URL the run publishes once, in order,
|
|
835
|
+
// refused ones included.
|
|
836
|
+
const published = [];
|
|
837
|
+
let read = 0;
|
|
838
|
+
const waiting = [];
|
|
839
|
+
this.#tunnelRuns.set(run, (url, refuse) => {
|
|
840
|
+
(refuse ? refused : urls).push(url);
|
|
841
|
+
published.push({ url, refused: refuse });
|
|
842
|
+
for (const w of waiting.splice(0))
|
|
843
|
+
w();
|
|
844
|
+
});
|
|
845
|
+
const abort = new AbortController();
|
|
846
|
+
const ended = this.#conn
|
|
847
|
+
.call("tunnel.run", {
|
|
848
|
+
type,
|
|
849
|
+
run,
|
|
850
|
+
addr,
|
|
851
|
+
config: { schema: "core.config.tunnel.v2", data: config ?? {} },
|
|
852
|
+
}, abort.signal)
|
|
853
|
+
.then(() => ({
|
|
854
|
+
stopped: abort.signal.aborted,
|
|
855
|
+
}), (err) => ({
|
|
856
|
+
stopped: abort.signal.aborted,
|
|
857
|
+
...(abort.signal.aborted ? {} : { error: err }),
|
|
858
|
+
}))
|
|
859
|
+
.finally(() => this.#tunnelRuns.delete(run));
|
|
860
|
+
const take = () => {
|
|
861
|
+
const got = published[read++];
|
|
862
|
+
if (got.refused)
|
|
863
|
+
throw new Error(`the host refused the URL ${JSON.stringify(got.url)}: a public URL is an http(s) URL with a host and no credentials`);
|
|
864
|
+
return got.url;
|
|
865
|
+
};
|
|
866
|
+
return {
|
|
867
|
+
urls,
|
|
868
|
+
refused,
|
|
869
|
+
next: async () => {
|
|
870
|
+
if (read < published.length)
|
|
871
|
+
return take();
|
|
872
|
+
const more = await Promise.race([
|
|
873
|
+
new Promise((resolve) => waiting.push(() => resolve(true))),
|
|
874
|
+
ended,
|
|
875
|
+
]);
|
|
876
|
+
if (more === true && read < published.length)
|
|
877
|
+
return take();
|
|
878
|
+
throw more === true
|
|
879
|
+
? new Error("the tunnel run published nothing")
|
|
880
|
+
: (more.error ??
|
|
881
|
+
new Error("the tunnel run ended before publishing a URL"));
|
|
882
|
+
},
|
|
883
|
+
ended,
|
|
884
|
+
stop: async () => {
|
|
885
|
+
abort.abort();
|
|
886
|
+
await ended;
|
|
887
|
+
},
|
|
888
|
+
};
|
|
889
|
+
},
|
|
890
|
+
validate: async (config) => {
|
|
891
|
+
await this.#conn.call("validate", { kind: "tunnel", type, config });
|
|
892
|
+
},
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
/**
|
|
896
|
+
* The extension's executor of name as the host reaches it over the wire
|
|
897
|
+
* (extproc's remoteExecutor): run, recover and resume each one call,
|
|
898
|
+
* their persist_recovery answered by the persist the call was given
|
|
899
|
+
* (refused without one), the handle's wait one executor.wait, and each
|
|
900
|
+
* control one call, refused without one when the manifest doesn't
|
|
901
|
+
* declare it.
|
|
902
|
+
*/
|
|
903
|
+
executor(name) {
|
|
904
|
+
const decl = this.#ext.manifest.provides.executors?.find((x) => x.name === name);
|
|
905
|
+
return testExecutor(name, {
|
|
906
|
+
call: (method, p, signal) => this.#conn.call(method, p, signal),
|
|
907
|
+
open: (run, persist, confine) => {
|
|
908
|
+
const r = { persist, err: undefined, confine };
|
|
909
|
+
this.#runs.set(run, r);
|
|
910
|
+
return { persistErr: () => r.err };
|
|
911
|
+
},
|
|
912
|
+
close: (run) => this.#runs.delete(run),
|
|
913
|
+
sweeps: this.#sweeps,
|
|
914
|
+
decl,
|
|
915
|
+
});
|
|
916
|
+
}
|
|
917
|
+
/**
|
|
918
|
+
* The extension's backup destination of type under one configured
|
|
919
|
+
* target, as the host reaches it over the wire (extproc's
|
|
920
|
+
* remoteBackupDestination). Unless given, the target's name is
|
|
921
|
+
* "sdktest-destination" and its config empty.
|
|
922
|
+
*/
|
|
923
|
+
backupDestination(type, o = {}) {
|
|
924
|
+
const target = {
|
|
925
|
+
type,
|
|
926
|
+
name: o.name ?? "sdktest-destination",
|
|
927
|
+
config: {
|
|
928
|
+
schema: "core.config.backup_destination.v1",
|
|
929
|
+
data: o.config ?? {},
|
|
930
|
+
},
|
|
931
|
+
};
|
|
932
|
+
const done = t.object({}, { open: true });
|
|
933
|
+
return {
|
|
934
|
+
put: async (bundle, file, body) => {
|
|
935
|
+
const upload = randomBytes(16).toString("hex");
|
|
936
|
+
const source = body instanceof Uint8Array
|
|
937
|
+
? (async function* () {
|
|
938
|
+
yield body;
|
|
939
|
+
})()
|
|
940
|
+
: body;
|
|
941
|
+
const it = source[Symbol.asyncIterator]();
|
|
942
|
+
const held = { rest: new Uint8Array() };
|
|
943
|
+
let started = false;
|
|
944
|
+
try {
|
|
945
|
+
for (let offset = 0;;) {
|
|
946
|
+
const want = Math.min(file.size - offset, MaxChunkBytes);
|
|
947
|
+
const chunk = await readUpTo(it, held, want);
|
|
948
|
+
if (chunk.length < want)
|
|
949
|
+
throw new Error(`reading ${file.path}: unexpected end`);
|
|
950
|
+
const final = offset + want === file.size;
|
|
951
|
+
started = true;
|
|
952
|
+
result(done, "backup_destination.write", await this.#conn.call("backup_destination.write", {
|
|
953
|
+
target,
|
|
954
|
+
bundle,
|
|
955
|
+
path: file.path,
|
|
956
|
+
size: file.size,
|
|
957
|
+
upload,
|
|
958
|
+
offset,
|
|
959
|
+
...(chunk.length > 0 ? { chunk: base64(chunk) } : {}),
|
|
960
|
+
...(final ? { final: true } : {}),
|
|
961
|
+
}));
|
|
962
|
+
offset += want;
|
|
963
|
+
if (final)
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
catch (err) {
|
|
968
|
+
if (started)
|
|
969
|
+
await this.#conn
|
|
970
|
+
.call("backup_destination.abort", { upload })
|
|
971
|
+
.catch(() => { });
|
|
972
|
+
throw err;
|
|
973
|
+
}
|
|
974
|
+
finally {
|
|
975
|
+
await it.return?.();
|
|
976
|
+
}
|
|
977
|
+
},
|
|
978
|
+
list: async () => result(BackupListResult, "backup_destination.list", await this.#conn.call("backup_destination.list", { target })).bundles ?? [],
|
|
979
|
+
files: async (bundle) => (result(BackupFilesResult, "backup_destination.files", await this.#conn.call("backup_destination.files", {
|
|
980
|
+
target,
|
|
981
|
+
bundle,
|
|
982
|
+
})).files ?? []).map((f) => ({ path: f.path, size: f.size })),
|
|
983
|
+
read: async (bundle, path, offset, length) => {
|
|
984
|
+
const out = result(BackupReadResult, "backup_destination.read", await this.#conn.call("backup_destination.read", {
|
|
985
|
+
target,
|
|
986
|
+
bundle,
|
|
987
|
+
path,
|
|
988
|
+
offset,
|
|
989
|
+
length: Math.min(length, MaxChunkBytes),
|
|
990
|
+
}));
|
|
991
|
+
return { chunk: bytes(out.chunk), eof: out.eof === true };
|
|
992
|
+
},
|
|
993
|
+
};
|
|
994
|
+
}
|
|
995
|
+
/** A run's brokers, as extproc's confine serves them. */
|
|
996
|
+
async #confine(method, raw) {
|
|
997
|
+
const runID = params(t.object({ run_id: t.string() }, { open: true }), raw).run_id;
|
|
998
|
+
const run = this.#runs.get(runID);
|
|
999
|
+
if (run === undefined)
|
|
1000
|
+
throw new ProtocolError(Code.Conflict, "run is not served by this process");
|
|
1001
|
+
const sandbox = method.startsWith("sandbox.");
|
|
1002
|
+
const broker = sandbox ? this.#o.sandbox : this.#o.container;
|
|
1003
|
+
if (!(sandbox ? run.confine.sandbox : run.confine.container) || !broker)
|
|
1004
|
+
throw new ProtocolError(Code.Unsupported, `the binding declares no ${sandbox ? "sandbox" : "container"}`);
|
|
1005
|
+
const plan = (p) => ({
|
|
1006
|
+
argv: p.argv,
|
|
1007
|
+
...(p.env?.length ? { env: p.env } : {}),
|
|
1008
|
+
...(p.signals ? { signals: p.signals } : {}),
|
|
1009
|
+
...(p.summary ? { summary: p.summary } : {}),
|
|
1010
|
+
...(p.data ? { data: p.data } : {}),
|
|
1011
|
+
...(p.dir ? { dir: p.dir } : {}),
|
|
1012
|
+
});
|
|
1013
|
+
switch (method) {
|
|
1014
|
+
case "sandbox.plan": {
|
|
1015
|
+
const p = params(LaunchParams, raw);
|
|
1016
|
+
return plan(await broker.plan(p.needs, p.launch, runID));
|
|
1017
|
+
}
|
|
1018
|
+
case "container.launch": {
|
|
1019
|
+
const p = params(LaunchParams, raw);
|
|
1020
|
+
return plan(await broker.launch(p.needs, p.launch, runID));
|
|
1021
|
+
}
|
|
1022
|
+
case "sandbox.adopt":
|
|
1023
|
+
await broker.adopt(params(SandboxAdoptParams, raw).parent, runID);
|
|
1024
|
+
return {};
|
|
1025
|
+
case "container.reattach": {
|
|
1026
|
+
const b = broker;
|
|
1027
|
+
if (b.reattach === undefined)
|
|
1028
|
+
throw new ProtocolError(Code.NotAdoptable, "no reattach");
|
|
1029
|
+
return plan(await b.reattach(params(ContainerReattachParams, raw).run, runID));
|
|
1030
|
+
}
|
|
1031
|
+
default: {
|
|
1032
|
+
const e = await broker.adopt(params(ContainerAdoptParams, raw).alive, runID);
|
|
1033
|
+
return {
|
|
1034
|
+
...(e.exited ? { exited: true } : {}),
|
|
1035
|
+
...(e.exitCode ? { exit_code: e.exitCode } : {}),
|
|
1036
|
+
...(e.interrupted ? { interrupted: true } : {}),
|
|
1037
|
+
};
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
/**
|
|
1042
|
+
* Sends the extension's exporter a batch of lifecycle records
|
|
1043
|
+
* (telemetry.export), as the host's telemetry pipeline does. Only an
|
|
1044
|
+
* extension that declares exporters is sent any.
|
|
1045
|
+
*/
|
|
1046
|
+
async exportTelemetry(records) {
|
|
1047
|
+
if (!this.#ext.manifest.provides.exporters)
|
|
1048
|
+
throw new Error("sdk: the extension declares no exporter (exporters)");
|
|
1049
|
+
await this.#conn.call("telemetry.export", { records });
|
|
1050
|
+
}
|
|
1051
|
+
/**
|
|
1052
|
+
* Sends the extension one collection of the host's meter
|
|
1053
|
+
* (telemetry.metrics), as the host does only for an extension with the
|
|
1054
|
+
* telemetry.metrics permission.
|
|
1055
|
+
*/
|
|
1056
|
+
async exportMetrics(metrics) {
|
|
1057
|
+
if (!this.#allows("telemetry.metrics"))
|
|
1058
|
+
throw new Error("sdk: the extension lacks the telemetry.metrics permission");
|
|
1059
|
+
await this.#conn.call("telemetry.metrics", { metrics });
|
|
1060
|
+
}
|
|
1061
|
+
/**
|
|
1062
|
+
* Hands the extension one of the host's named telemetry events
|
|
1063
|
+
* (telemetry.sink), as the host hands each to every extension with the
|
|
1064
|
+
* telemetry.sink permission, and returns whether it was sent: one
|
|
1065
|
+
* without the permission gets nothing. at defaults to the clock's now.
|
|
1066
|
+
*/
|
|
1067
|
+
async sink(e) {
|
|
1068
|
+
if (!this.#allows("telemetry.sink"))
|
|
1069
|
+
return false;
|
|
1070
|
+
await this.#conn.call("telemetry.sink", {
|
|
1071
|
+
...(e.scopeId ? { scope_id: e.scopeId } : {}),
|
|
1072
|
+
name: e.name,
|
|
1073
|
+
at: e.at ?? this.clock.now(),
|
|
1074
|
+
...(e.properties === undefined ? {} : { properties: e.properties }),
|
|
1075
|
+
});
|
|
1076
|
+
return true;
|
|
1077
|
+
}
|
|
1078
|
+
/**
|
|
1079
|
+
* Asks for the extension's environment layer for a run
|
|
1080
|
+
* (run.environment), as the host does: an extension that doesn't
|
|
1081
|
+
* declare run_environment has none; files for a run with no filesDir
|
|
1082
|
+
* are dropped; files checkRunFiles refuses fail the call as they fail
|
|
1083
|
+
* the run (ProtocolError invalid); and env is what the host applies,
|
|
1084
|
+
* without the variables it skips (appliedEnv).
|
|
1085
|
+
*/
|
|
1086
|
+
async runEnvironment(r) {
|
|
1087
|
+
if (!this.#ext.manifest.provides.run_environment)
|
|
1088
|
+
return {};
|
|
1089
|
+
const out = result(RunEnvironmentResult, "run.environment", await this.#conn.call("run.environment", {
|
|
1090
|
+
owner: r.owner,
|
|
1091
|
+
...(r.connection ? { connection: r.connection } : {}),
|
|
1092
|
+
...(r.binding ? { binding: r.binding } : {}),
|
|
1093
|
+
...(r.filesDir ? { files_dir: r.filesDir } : {}),
|
|
1094
|
+
}));
|
|
1095
|
+
const files = r.filesDir ? out.files : undefined;
|
|
1096
|
+
const refused = checkRunFiles(files);
|
|
1097
|
+
if (refused !== undefined)
|
|
1098
|
+
throw invalid(refused);
|
|
1099
|
+
const env = appliedEnv(out.env);
|
|
1100
|
+
return {
|
|
1101
|
+
...(Object.keys(env).length > 0 ? { env } : {}),
|
|
1102
|
+
...(files !== undefined && Object.keys(files).length > 0
|
|
1103
|
+
? { files: { ...files } }
|
|
1104
|
+
: {}),
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
/**
|
|
1108
|
+
* Asks what a Work proposes (config.candidate), as the host does: an
|
|
1109
|
+
* extension that doesn't declare config_candidate, or lacks the
|
|
1110
|
+
* config.read permission, is never asked and has none (undefined), as is
|
|
1111
|
+
* a Work it proposes nothing on. A candidate whose handle the host
|
|
1112
|
+
* doesn't hold is refused (ProtocolError not_found), as the daemon
|
|
1113
|
+
* refuses to serve it; configText(handle) is the text behind one it
|
|
1114
|
+
* does, as the operator is served it.
|
|
1115
|
+
*/
|
|
1116
|
+
async configCandidate(work) {
|
|
1117
|
+
if (!this.#ext.manifest.provides.config_candidate ||
|
|
1118
|
+
!this.#allows("config.read"))
|
|
1119
|
+
return undefined;
|
|
1120
|
+
const c = candidateOf(result(ConfigCandidateResult, "config.candidate", await this.#conn.call("config.candidate", { work })));
|
|
1121
|
+
if (c?.handle && this.#config.text(c.handle) === undefined)
|
|
1122
|
+
throw new ProtocolError(Code.NotFound, "the candidate's handle is not one the host holds");
|
|
1123
|
+
return c;
|
|
1124
|
+
}
|
|
1125
|
+
/** The config text behind a handle the host gave out, unredacted, as the operator is served it; undefined for one it doesn't hold. */
|
|
1126
|
+
configText(handle) {
|
|
1127
|
+
return this.#config.text(handle);
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1130
|
+
* Runs the extension's setup flow of type (setup.run), as `open-conduit
|
|
1131
|
+
* init <type>` does: its setup.* callbacks are answered from o for this
|
|
1132
|
+
* run alone, and any quoting another run ID is refused as conflict.
|
|
1133
|
+
* Returns what the flow answered and what the operator saw. A flow the
|
|
1134
|
+
* manifest doesn't declare is refused without a call.
|
|
1135
|
+
*/
|
|
1136
|
+
async setup(type, o = {}) {
|
|
1137
|
+
if (this.#ext.manifest.provides.setup?.type !== type)
|
|
1138
|
+
throw new Error(`sdk: the extension declares no setup ${type}`);
|
|
1139
|
+
const run = `setup-${++this.#calls}`;
|
|
1140
|
+
const session = new TestSetupSession(o);
|
|
1141
|
+
this.#setups.set(run, session);
|
|
1142
|
+
try {
|
|
1143
|
+
const out = result(SetupRunResult, "setup.run", await this.#conn.call("setup.run", {
|
|
1144
|
+
run,
|
|
1145
|
+
type,
|
|
1146
|
+
...(o.args !== undefined && o.args.length > 0
|
|
1147
|
+
? { args: o.args }
|
|
1148
|
+
: {}),
|
|
1149
|
+
...(o.config === undefined
|
|
1150
|
+
? {}
|
|
1151
|
+
: { config: Buffer.from(o.config).toString("base64") }),
|
|
1152
|
+
cwd: o.cwd ?? "/sdktest/work",
|
|
1153
|
+
state_dir: o.stateDir ?? this.stateDir,
|
|
1154
|
+
...(o.dryRun ? { dry_run: true } : {}),
|
|
1155
|
+
}));
|
|
1156
|
+
return { result: out, record: session.record };
|
|
1157
|
+
}
|
|
1158
|
+
finally {
|
|
1159
|
+
this.#setups.delete(run);
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
// In-transaction and routing hooks, asked as the host asks them.
|
|
1163
|
+
/** The timers the extension has armed, by ID. */
|
|
1164
|
+
timers() {
|
|
1165
|
+
return [...this.#timers.values()].map((x) => ({
|
|
1166
|
+
...x,
|
|
1167
|
+
timer: { ...x.timer },
|
|
1168
|
+
}));
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* Fires one of the extension's armed timers, as the host does at its
|
|
1172
|
+
* fire_at (the clock is not moved): it asks the timer's recurrence for
|
|
1173
|
+
* the occurrence and the next timer (recurrence.next), checks both as
|
|
1174
|
+
* the runtime does, accepts the occurrence in the timer's scope and
|
|
1175
|
+
* re-arms the next, or drops the timer when there is none. A refused
|
|
1176
|
+
* answer (ProtocolError invalid, unauthorized or schema) changes
|
|
1177
|
+
* nothing, and the timer stays due, as an aborted firing leaves it.
|
|
1178
|
+
*/
|
|
1179
|
+
async fireTimer(id) {
|
|
1180
|
+
const armed = this.#timers.get(id);
|
|
1181
|
+
if (armed === undefined)
|
|
1182
|
+
throw new ProtocolError(Code.NotFound, `no timer ${id} is armed`);
|
|
1183
|
+
const fired = armed.timer;
|
|
1184
|
+
const now = this.now();
|
|
1185
|
+
const out = result(RecurrenceNextResult, "recurrence.next", await this.#conn.call("recurrence.next", {
|
|
1186
|
+
kind: armed.kind,
|
|
1187
|
+
spec: armed.spec,
|
|
1188
|
+
fired,
|
|
1189
|
+
now,
|
|
1190
|
+
}));
|
|
1191
|
+
const occ = out.occurrence;
|
|
1192
|
+
if (occ !== undefined) {
|
|
1193
|
+
// As extproc's adapter, then the runtime's recurrence step.
|
|
1194
|
+
if (!this.#ownFamily(occ.type) ||
|
|
1195
|
+
!inNamespace(this.#ext.manifest.name, occ.source ?? "", "/"))
|
|
1196
|
+
throw unauthorized("occurrence is not the extension's");
|
|
1197
|
+
this.#checkWrite(occ.data);
|
|
1198
|
+
if (!occ.id ||
|
|
1199
|
+
!occ.delivery_id ||
|
|
1200
|
+
occ.source !== fired.event.source ||
|
|
1201
|
+
(occ.causation_id && occ.causation_id !== fired.event.causation_id))
|
|
1202
|
+
throw invalid("an occurrence needs an ID and delivery ID, and keeps the timer's source and causal parent");
|
|
1203
|
+
}
|
|
1204
|
+
const next = out.next;
|
|
1205
|
+
if (next !== undefined) {
|
|
1206
|
+
if (next.id !== fired.id ||
|
|
1207
|
+
!(Date.parse(next.fire_at) > Date.parse(fired.fire_at)) ||
|
|
1208
|
+
!(Date.parse(next.fire_at) > Date.parse(now)) ||
|
|
1209
|
+
next.event.id === fired.event.id ||
|
|
1210
|
+
(next.event.source === fired.event.source &&
|
|
1211
|
+
next.event.delivery_id === fired.event.delivery_id))
|
|
1212
|
+
throw invalid("the next timer keeps the timer's ID, fires later and carries a new event identity");
|
|
1213
|
+
this.#checkTimerEvent(next.event);
|
|
1214
|
+
}
|
|
1215
|
+
const firing = {};
|
|
1216
|
+
if (occ !== undefined)
|
|
1217
|
+
firing.occurrence = this.#accept(armed.scopeId, occ, "").accepted;
|
|
1218
|
+
if (next === undefined)
|
|
1219
|
+
this.#timers.delete(id);
|
|
1220
|
+
else {
|
|
1221
|
+
const rearmed = { ...next, revision: (fired.revision ?? 0) + 1 };
|
|
1222
|
+
this.#timers.set(id, { ...armed, timer: rearmed });
|
|
1223
|
+
firing.next = rearmed;
|
|
1224
|
+
}
|
|
1225
|
+
return firing;
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* Asks the extension's dependency filter whether event matches filter
|
|
1229
|
+
* (dependency.filter), as core does for an Event on a wait's
|
|
1230
|
+
* dependency. An extension that doesn't declare dependency_filter
|
|
1231
|
+
* matches everything, as core matches without a filter; one that
|
|
1232
|
+
* refuses the call (unreadable or undeclared) does not match.
|
|
1233
|
+
*/
|
|
1234
|
+
async dependencyFilter(filter, event) {
|
|
1235
|
+
if (!this.#ext.manifest.provides.dependency_filter)
|
|
1236
|
+
return true;
|
|
1237
|
+
try {
|
|
1238
|
+
return result(DependencyFilterResult, "dependency.filter", await this.#conn.call("dependency.filter", { filter, event })).match;
|
|
1239
|
+
}
|
|
1240
|
+
catch (err) {
|
|
1241
|
+
if (err instanceof ProtocolError &&
|
|
1242
|
+
(err.code === Code.Schema ||
|
|
1243
|
+
err.code === Code.Undeclared ||
|
|
1244
|
+
err.code === Code.NotFound))
|
|
1245
|
+
return false;
|
|
1246
|
+
throw err;
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
/**
|
|
1250
|
+
* Asks the extension's operation gate about a call to another
|
|
1251
|
+
* extension's operation (operation.gate), as the toolbelt does:
|
|
1252
|
+
* undefined lets it through, a plan parks the caller. An extension
|
|
1253
|
+
* without the declaration or the operation.gate permission is never
|
|
1254
|
+
* asked, nor about a call outside its scopes. The host fails closed: an
|
|
1255
|
+
* OperationError reaches the caller as it is, and anything else (a
|
|
1256
|
+
* protocol error, an unreadable plan) refuses the call as gate_failed.
|
|
1257
|
+
*/
|
|
1258
|
+
async gate(call) {
|
|
1259
|
+
if (!this.#ext.manifest.provides.operation_gate ||
|
|
1260
|
+
!this.#allows("operation.gate"))
|
|
1261
|
+
return undefined;
|
|
1262
|
+
const a = this.#authority(call.authority ?? {});
|
|
1263
|
+
if (!this.#scopes.has(a.scope_id))
|
|
1264
|
+
return undefined;
|
|
1265
|
+
try {
|
|
1266
|
+
const out = result(OperationGateResult, "operation.gate", await this.#conn.call("operation.gate", {
|
|
1267
|
+
operation: call.operation,
|
|
1268
|
+
owner: call.owner,
|
|
1269
|
+
authority: a,
|
|
1270
|
+
input: call.input ?? { data: {} },
|
|
1271
|
+
...(call.capability ? { capability: call.capability } : {}),
|
|
1272
|
+
...(call.wants ? { wants: call.wants } : {}),
|
|
1273
|
+
}));
|
|
1274
|
+
if (out.wait !== undefined)
|
|
1275
|
+
this.#checkWrite(out.wait.output);
|
|
1276
|
+
return out.wait;
|
|
1277
|
+
}
|
|
1278
|
+
catch (err) {
|
|
1279
|
+
if (err instanceof OperationError)
|
|
1280
|
+
throw err;
|
|
1281
|
+
throw new OperationError("gate_failed", `${this.#ext.manifest.name} could not decide whether this call may proceed, so it was refused`);
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* Asks the extension's start gate about a Work's first attempt
|
|
1286
|
+
* (work.admit), as the runtime does: undefined lets the start through,
|
|
1287
|
+
* a hold holds the Work until host.settleHold settles it (holds()). An
|
|
1288
|
+
* extension without the declaration or the work.start_gate permission
|
|
1289
|
+
* is never asked, nor about Work outside its scopes; what it throws
|
|
1290
|
+
* refuses the start for now.
|
|
1291
|
+
*/
|
|
1292
|
+
async admit(call) {
|
|
1293
|
+
if (!this.#ext.manifest.provides.start_gate ||
|
|
1294
|
+
!this.#allows("work.start_gate") ||
|
|
1295
|
+
!this.#scopes.has(call.work.scope_id))
|
|
1296
|
+
return undefined;
|
|
1297
|
+
const out = result(WorkAdmitResult, "work.admit", await this.#conn.call("work.admit", {
|
|
1298
|
+
work: call.work,
|
|
1299
|
+
binding: call.binding ?? "sdktest",
|
|
1300
|
+
event: call.event,
|
|
1301
|
+
}));
|
|
1302
|
+
if (out.hold === undefined)
|
|
1303
|
+
return undefined;
|
|
1304
|
+
const reason = out.hold.reason ?? "";
|
|
1305
|
+
this.#holds.set(call.work.id, reason);
|
|
1306
|
+
if (!this.#works.some((w) => w.id === call.work.id))
|
|
1307
|
+
this.#works.push(call.work);
|
|
1308
|
+
return { reason };
|
|
1309
|
+
}
|
|
1310
|
+
/** The Work the extension's start gate holds now, by ID, with each hold's reason. */
|
|
1311
|
+
holds() {
|
|
1312
|
+
return Object.fromEntries(this.#holds);
|
|
1313
|
+
}
|
|
1314
|
+
/** How each hold the extension settled ended, by Work ID: "admitted" or "cancelled". */
|
|
1315
|
+
settled() {
|
|
1316
|
+
return Object.fromEntries(this.#settled);
|
|
1317
|
+
}
|
|
1318
|
+
/** The Work the extension cancelled (work.cancel), by ID, with each reason. */
|
|
1319
|
+
cancelled() {
|
|
1320
|
+
return Object.fromEntries(this.#cancelled);
|
|
1321
|
+
}
|
|
1322
|
+
/**
|
|
1323
|
+
* Resolves a wait target of kind in a scope through the extension
|
|
1324
|
+
* (target.resolve), as the host does: only a kind it declares, only in
|
|
1325
|
+
* its scopes, and nothing when it answers a type that isn't one of its
|
|
1326
|
+
* families or the call fails.
|
|
1327
|
+
*/
|
|
1328
|
+
async resolveTarget(scopeId, kind, name) {
|
|
1329
|
+
if (!(this.#ext.manifest.provides.targets ?? []).includes(kind) ||
|
|
1330
|
+
!this.#scopes.has(scopeId))
|
|
1331
|
+
return undefined;
|
|
1332
|
+
let out;
|
|
1333
|
+
try {
|
|
1334
|
+
out = result(TargetResolveResult, "target.resolve", await this.#conn.call("target.resolve", {
|
|
1335
|
+
scope_id: scopeId,
|
|
1336
|
+
kind,
|
|
1337
|
+
name,
|
|
1338
|
+
}));
|
|
1339
|
+
}
|
|
1340
|
+
catch {
|
|
1341
|
+
return undefined;
|
|
1342
|
+
}
|
|
1343
|
+
const types = out.types ?? [];
|
|
1344
|
+
if (!out.ok || !types.every((x) => this.#ownFamily(x)))
|
|
1345
|
+
return undefined;
|
|
1346
|
+
return { key: out.key, types };
|
|
1347
|
+
}
|
|
1348
|
+
/**
|
|
1349
|
+
* Tells the extension an execution's container segment ended
|
|
1350
|
+
* (segment.ended), and waits for it, though the host doesn't: what it
|
|
1351
|
+
* throws is returned rather than thrown, as the host ignores it. An
|
|
1352
|
+
* extension without segment_end is never told.
|
|
1353
|
+
*/
|
|
1354
|
+
async segmentEnded(executionId) {
|
|
1355
|
+
if (!this.#ext.manifest.provides.segment_end)
|
|
1356
|
+
return undefined;
|
|
1357
|
+
try {
|
|
1358
|
+
await this.#conn.call("segment.ended", { execution_id: executionId });
|
|
1359
|
+
return undefined;
|
|
1360
|
+
}
|
|
1361
|
+
catch (err) {
|
|
1362
|
+
return err;
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
/**
|
|
1366
|
+
* Renders an Event for an agent's prompt through the extension
|
|
1367
|
+
* (event.render), as the host does: undefined, the host's generic
|
|
1368
|
+
* rendering, for an extension without render, an Event of a family it
|
|
1369
|
+
* doesn't own or a payload it can't read, a failed call, or no answer.
|
|
1370
|
+
*/
|
|
1371
|
+
async render(event) {
|
|
1372
|
+
if (!this.#ext.manifest.provides.render || !this.#ownFamily(event.type))
|
|
1373
|
+
return undefined;
|
|
1374
|
+
try {
|
|
1375
|
+
this.#checkWrite(event.data);
|
|
1376
|
+
const out = result(EventRenderResult, "event.render", await this.#conn.call("event.render", { event }));
|
|
1377
|
+
return out.ok ? (out.text ?? "") : undefined;
|
|
1378
|
+
}
|
|
1379
|
+
catch {
|
|
1380
|
+
return undefined;
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
#checkTimerEvent(e) {
|
|
1384
|
+
if (!this.#ownFamily(e.type) ||
|
|
1385
|
+
!inNamespace(this.#ext.manifest.name, e.source ?? "", "/"))
|
|
1386
|
+
throw unauthorized("timer event is not the extension's");
|
|
1387
|
+
this.#checkWrite(e.data);
|
|
1388
|
+
if (!e.id || !e.delivery_id)
|
|
1389
|
+
throw invalid("a timer's Event needs an ID and a delivery ID");
|
|
1390
|
+
}
|
|
1391
|
+
#allows(permission) {
|
|
1392
|
+
return this.#ext.manifest.permissions?.includes(permission) ?? false;
|
|
1393
|
+
}
|
|
300
1394
|
// What the extension wrote.
|
|
301
1395
|
/** A KV value, or undefined. */
|
|
302
1396
|
kv(namespace, key) {
|
|
@@ -323,6 +1417,10 @@ export class TestHost {
|
|
|
323
1417
|
progress(workId) {
|
|
324
1418
|
return this.#progress.get(workId) ?? "";
|
|
325
1419
|
}
|
|
1420
|
+
/** The telemetry events the extension captured (telemetry.capture), in order, each at the time the host recorded. */
|
|
1421
|
+
captured() {
|
|
1422
|
+
return this.#captured.map((e) => ({ ...e }));
|
|
1423
|
+
}
|
|
326
1424
|
// Serving the extension's calls.
|
|
327
1425
|
#authority(a) {
|
|
328
1426
|
const scope = a.scope_id ?? [...this.#scopes][0] ?? "";
|
|
@@ -422,6 +1520,17 @@ export class TestHost {
|
|
|
422
1520
|
return this.#deliver(params(IngressDeliverParams, raw));
|
|
423
1521
|
case "secret.resolve": {
|
|
424
1522
|
const p = params(SecretResolveParams, raw);
|
|
1523
|
+
if (p.probe_grant) {
|
|
1524
|
+
// A probe run's grant reads its one connection, until the run ends.
|
|
1525
|
+
const g = this.#probeGrants.get(p.probe_grant);
|
|
1526
|
+
if (g === undefined ||
|
|
1527
|
+
g.scopeId !== p.scope_id ||
|
|
1528
|
+
g.connection !== p.connection)
|
|
1529
|
+
throw unauthorized("no such probe grant");
|
|
1530
|
+
return {
|
|
1531
|
+
values: Object.fromEntries(p.names.filter((n) => n in g.values).map((n) => [n, g.values[n]])),
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
425
1534
|
if (!this.#scopes.has(p.scope_id))
|
|
426
1535
|
throw unauthorized("scope is not configured for this extension");
|
|
427
1536
|
let values;
|
|
@@ -430,6 +1539,11 @@ export class TestHost {
|
|
|
430
1539
|
if (values === undefined)
|
|
431
1540
|
throw unauthorized("connection is not bound to the extension in the scope");
|
|
432
1541
|
}
|
|
1542
|
+
else if (p.binding) {
|
|
1543
|
+
values = this.#o.bindingSecrets?.find((b) => b.scopeId === p.scope_id && b.binding === p.binding)?.values;
|
|
1544
|
+
if (values === undefined)
|
|
1545
|
+
throw unauthorized("binding's executor is not one of the extension's in the scope");
|
|
1546
|
+
}
|
|
433
1547
|
else
|
|
434
1548
|
values = this.#o.secrets?.[p.scope_id] ?? {};
|
|
435
1549
|
return {
|
|
@@ -460,6 +1574,274 @@ export class TestHost {
|
|
|
460
1574
|
throw new ProtocolError(Code.NotFound, "not found");
|
|
461
1575
|
return this.#o.pending?.[w.id] ?? [];
|
|
462
1576
|
}
|
|
1577
|
+
case "execution.persist_recovery": {
|
|
1578
|
+
const p = params(PersistRecoveryParams, raw);
|
|
1579
|
+
const run = this.#runs.get(p.run_id);
|
|
1580
|
+
if (run === undefined)
|
|
1581
|
+
throw new ProtocolError(Code.NotFound, "unknown run");
|
|
1582
|
+
if (run.persist === undefined)
|
|
1583
|
+
throw new ProtocolError(Code.Unsupported, "no persistence");
|
|
1584
|
+
try {
|
|
1585
|
+
await run.persist(p.state);
|
|
1586
|
+
}
|
|
1587
|
+
catch (err) {
|
|
1588
|
+
run.err = err;
|
|
1589
|
+
throw new ProtocolError(Code.Conflict, "persistence refused");
|
|
1590
|
+
}
|
|
1591
|
+
return {};
|
|
1592
|
+
}
|
|
1593
|
+
case "executor.known": {
|
|
1594
|
+
const p = params(ExecutorKnownParams, raw);
|
|
1595
|
+
const known = this.#sweeps.get(p.sweep);
|
|
1596
|
+
if (known === undefined)
|
|
1597
|
+
throw new ProtocolError(Code.NotFound, "unknown sweep");
|
|
1598
|
+
if (p.executions.length > 256)
|
|
1599
|
+
throw invalid("more than MaxKnownBatch executions");
|
|
1600
|
+
const got = new Set(await known(p.executions));
|
|
1601
|
+
return { known: p.executions.filter((id) => got.has(id)) };
|
|
1602
|
+
}
|
|
1603
|
+
case "resource.acquire":
|
|
1604
|
+
case "resource.lookup": {
|
|
1605
|
+
const run = params(t.object({ run_id: t.string() }, { open: true }), raw);
|
|
1606
|
+
if (!this.#runs.has(run.run_id))
|
|
1607
|
+
throw new ProtocolError(Code.NotFound, "unknown run");
|
|
1608
|
+
const r = this.#o.resources;
|
|
1609
|
+
const got = method === "resource.acquire"
|
|
1610
|
+
? r?.acquire?.(params(ResourceAcquireParams, raw))
|
|
1611
|
+
: r?.lookup?.(params(ResourceLookupParams, raw).ref);
|
|
1612
|
+
if (got === undefined)
|
|
1613
|
+
throw new ProtocolError(Code.ResourceNotFound, "the binding declares no resource provider");
|
|
1614
|
+
return { resource: got };
|
|
1615
|
+
}
|
|
1616
|
+
case "sandbox.plan":
|
|
1617
|
+
case "sandbox.adopt":
|
|
1618
|
+
case "container.launch":
|
|
1619
|
+
case "container.adopt":
|
|
1620
|
+
case "container.reattach":
|
|
1621
|
+
return this.#confine(method, raw);
|
|
1622
|
+
case "provider.owner_status": {
|
|
1623
|
+
const p = params(OwnerStatusParams, raw);
|
|
1624
|
+
const status = this.#reconciles.get(p.reconcile);
|
|
1625
|
+
if (status === undefined)
|
|
1626
|
+
throw new ProtocolError(Code.Conflict, "no provider.reconcile in progress under that ID");
|
|
1627
|
+
const st = await status(p.owner);
|
|
1628
|
+
return {
|
|
1629
|
+
known: st.known ?? false,
|
|
1630
|
+
execution_done: st.executionDone ?? false,
|
|
1631
|
+
execution_succeeded: st.executionSucceeded ?? false,
|
|
1632
|
+
work_done: st.workDone ?? false,
|
|
1633
|
+
work_succeeded: st.workSucceeded ?? false,
|
|
1634
|
+
...(st.mounts?.length ? { mounts: st.mounts } : {}),
|
|
1635
|
+
};
|
|
1636
|
+
}
|
|
1637
|
+
case "site.run": {
|
|
1638
|
+
const p = params(SiteRunParams, raw);
|
|
1639
|
+
const declared = this.#ext.manifest.provides.resources?.some((r) => r.type === p.type && r.sites);
|
|
1640
|
+
if (!declared)
|
|
1641
|
+
throw new ProtocolError(Code.Unauthorized, "the extension declares no resource type with sites by that name");
|
|
1642
|
+
let id = p.site ?? "";
|
|
1643
|
+
if (p.call) {
|
|
1644
|
+
const at = this.#siteCalls.get(p.call);
|
|
1645
|
+
if (at === undefined || at.type !== p.type)
|
|
1646
|
+
throw new ProtocolError(Code.Conflict, "no provider.acquire in progress under that call");
|
|
1647
|
+
if (id !== "" && id !== at.site)
|
|
1648
|
+
throw new ProtocolError(Code.Unauthorized, "the call's acquisition is at another site");
|
|
1649
|
+
id = at.site;
|
|
1650
|
+
}
|
|
1651
|
+
else if (id === "")
|
|
1652
|
+
throw new ProtocolError(Code.Invalid, "site.run names no call and no site");
|
|
1653
|
+
const site = this.#o.sites?.[id];
|
|
1654
|
+
if (site === undefined)
|
|
1655
|
+
throw new ProtocolError(Code.SiteUnavailable, "no such site");
|
|
1656
|
+
const c = p.command;
|
|
1657
|
+
const out = await site({
|
|
1658
|
+
argv: [...(c.argv ?? [])],
|
|
1659
|
+
dir: c.dir ?? "",
|
|
1660
|
+
env: [...(c.env ?? [])],
|
|
1661
|
+
stdin: bytes(c.stdin),
|
|
1662
|
+
timeoutMs: c.timeout_millis ?? 0,
|
|
1663
|
+
});
|
|
1664
|
+
const stdout = toBytes(out.stdout ?? "");
|
|
1665
|
+
const stderr = toBytes(out.stderr ?? "");
|
|
1666
|
+
return {
|
|
1667
|
+
exit_code: out.exitCode,
|
|
1668
|
+
...(stdout.length ? { stdout: base64(stdout) } : {}),
|
|
1669
|
+
...(stderr.length ? { stderr: base64(stderr) } : {}),
|
|
1670
|
+
};
|
|
1671
|
+
}
|
|
1672
|
+
case "tunnel.url": {
|
|
1673
|
+
const p = params(TunnelURLParams, raw);
|
|
1674
|
+
const publish = this.#tunnelRuns.get(p.run);
|
|
1675
|
+
if (publish === undefined)
|
|
1676
|
+
throw new ProtocolError(Code.Conflict, "no tunnel.run in progress under that ID");
|
|
1677
|
+
// Webhooks are pointed at it: only what a public_url could be.
|
|
1678
|
+
if (p.url !== "" && !checkPublicURL(p.url)) {
|
|
1679
|
+
publish(p.url, true);
|
|
1680
|
+
throw new ProtocolError(Code.Invalid, "a public URL is an http(s) URL with a host and no credentials");
|
|
1681
|
+
}
|
|
1682
|
+
publish(p.url, false);
|
|
1683
|
+
return {};
|
|
1684
|
+
}
|
|
1685
|
+
case "config.base":
|
|
1686
|
+
case "config.edit":
|
|
1687
|
+
case "config.validate":
|
|
1688
|
+
case "config.trace":
|
|
1689
|
+
// As the host's catalogue refuses config.* without the permission.
|
|
1690
|
+
if (!this.#allows("config.read"))
|
|
1691
|
+
throw new ProtocolError(Code.Undeclared, `${method} needs the config.read permission`);
|
|
1692
|
+
return this.#config.serve(method, raw);
|
|
1693
|
+
case "setup.print":
|
|
1694
|
+
case "setup.prompt":
|
|
1695
|
+
case "setup.choose":
|
|
1696
|
+
case "setup.open_url":
|
|
1697
|
+
case "setup.store_secret":
|
|
1698
|
+
case "setup.look_path":
|
|
1699
|
+
case "setup.run_command": {
|
|
1700
|
+
const p = params(t.object({ run: t.string() }, { open: true }), raw);
|
|
1701
|
+
const session = this.#setups.get(p.run);
|
|
1702
|
+
if (session === undefined)
|
|
1703
|
+
throw new ProtocolError(Code.Conflict, "no setup run in progress under that ID");
|
|
1704
|
+
return session.serve(method, raw);
|
|
1705
|
+
}
|
|
1706
|
+
case "telemetry.capture": {
|
|
1707
|
+
// As the host's catalogue and extproc's capture check it.
|
|
1708
|
+
if (!this.#allows("telemetry.capture"))
|
|
1709
|
+
throw new ProtocolError(Code.Undeclared, "telemetry.capture needs the telemetry.capture permission");
|
|
1710
|
+
const p = params(t.object({
|
|
1711
|
+
scope_id: t.optional(t.string()),
|
|
1712
|
+
name: t.string(),
|
|
1713
|
+
at: t.optional(t.string()),
|
|
1714
|
+
properties: t.optional(t.record(t.any())),
|
|
1715
|
+
}, { open: true }), raw);
|
|
1716
|
+
if (p.scope_id && !this.#scopes.has(p.scope_id))
|
|
1717
|
+
throw new ProtocolError(Code.Unauthorized, "scope is not configured for this extension");
|
|
1718
|
+
if (p.name === "" ||
|
|
1719
|
+
Buffer.byteLength(p.name, "utf8") > 128 ||
|
|
1720
|
+
/[\0\n]/.test(p.name))
|
|
1721
|
+
throw invalid("an event name of at most 128 bytes");
|
|
1722
|
+
if (p.properties !== undefined && "scope" in p.properties)
|
|
1723
|
+
throw invalid("the scope goes in scope_id, not the properties");
|
|
1724
|
+
if (Buffer.byteLength(JSON.stringify(p.properties ?? null), "utf8") >
|
|
1725
|
+
64 << 10)
|
|
1726
|
+
throw invalid("properties of at most 64 KiB");
|
|
1727
|
+
const zero = p.at === undefined || p.at.startsWith("0001-01-01");
|
|
1728
|
+
this.#captured.push({
|
|
1729
|
+
...(p.scope_id ? { scope_id: p.scope_id } : {}),
|
|
1730
|
+
name: p.name,
|
|
1731
|
+
at: zero ? this.clock.now() : p.at,
|
|
1732
|
+
...(p.properties === undefined ? {} : { properties: p.properties }),
|
|
1733
|
+
});
|
|
1734
|
+
return {};
|
|
1735
|
+
}
|
|
1736
|
+
case "timer.arm": {
|
|
1737
|
+
const p = params(TimerArmParams, raw);
|
|
1738
|
+
if (!this.#scopes.has(p.scope_id))
|
|
1739
|
+
throw unauthorized("scope is not configured for this extension");
|
|
1740
|
+
if (!(this.#ext.manifest.provides.recurrences ?? []).includes(p.kind))
|
|
1741
|
+
throw new ProtocolError(Code.Undeclared, "recurrence not declared");
|
|
1742
|
+
this.#checkTimerEvent(p.timer.event);
|
|
1743
|
+
if (p.timer.event.causation_id)
|
|
1744
|
+
throw invalid("a recurring timer's Event has no causal parent");
|
|
1745
|
+
if (p.spec === undefined || p.spec === null)
|
|
1746
|
+
throw invalid("a recurrence spec is a JSON value");
|
|
1747
|
+
if (Buffer.byteLength(JSON.stringify(p.spec), "utf8") > 64 << 10)
|
|
1748
|
+
throw invalid("a recurrence spec of at most 64 KiB");
|
|
1749
|
+
const old = this.#timers.get(p.timer.id);
|
|
1750
|
+
if ((old?.timer.revision ?? 0) !== p.expected ||
|
|
1751
|
+
(old === undefined && p.expected !== 0))
|
|
1752
|
+
throw new ProtocolError(Code.Conflict, "timer revision changed");
|
|
1753
|
+
this.#timers.set(p.timer.id, {
|
|
1754
|
+
scopeId: p.scope_id,
|
|
1755
|
+
timer: { ...p.timer, revision: p.expected + 1 },
|
|
1756
|
+
kind: p.kind,
|
|
1757
|
+
spec: p.spec,
|
|
1758
|
+
});
|
|
1759
|
+
return {};
|
|
1760
|
+
}
|
|
1761
|
+
case "timer.cancel": {
|
|
1762
|
+
const p = params(TimerCancelParams, raw);
|
|
1763
|
+
const old = this.#timers.get(p.id);
|
|
1764
|
+
if (old === undefined)
|
|
1765
|
+
return {};
|
|
1766
|
+
if (!this.#ownFamily(old.timer.event.type))
|
|
1767
|
+
throw unauthorized("timer is not the extension's");
|
|
1768
|
+
if ((old.timer.revision ?? 0) !== p.expected)
|
|
1769
|
+
throw new ProtocolError(Code.Conflict, "timer revision changed");
|
|
1770
|
+
this.#timers.delete(p.id);
|
|
1771
|
+
return {};
|
|
1772
|
+
}
|
|
1773
|
+
case "work.cancel": {
|
|
1774
|
+
const p = params(WorkCancelParams, raw);
|
|
1775
|
+
const w = this.#works.find((x) => x.id === p.work_id);
|
|
1776
|
+
if (w === undefined)
|
|
1777
|
+
throw new ProtocolError(Code.NotFound, "no such Work");
|
|
1778
|
+
if (!(this.#ext.manifest.provides.work_kinds ?? []).some((k) => k.kind === w.kind))
|
|
1779
|
+
throw unauthorized("work is not of the extension's kinds");
|
|
1780
|
+
if (p.expected !== 0 && p.expected !== w.revision)
|
|
1781
|
+
throw new ProtocolError(Code.Conflict, "work revision changed");
|
|
1782
|
+
if (!this.#cancelled.has(w.id))
|
|
1783
|
+
this.#cancelled.set(w.id, p.reason);
|
|
1784
|
+
return { event_id: `sdktest-cancel/${w.id}` };
|
|
1785
|
+
}
|
|
1786
|
+
case "work.settle_hold": {
|
|
1787
|
+
if (!this.#allows("work.start_gate"))
|
|
1788
|
+
throw new ProtocolError(Code.Undeclared, "work.settle_hold needs the work.start_gate permission");
|
|
1789
|
+
const p = params(WorkSettleHoldParams, raw);
|
|
1790
|
+
// As Control.SettleGateHold: idempotent per key, a key reused
|
|
1791
|
+
// for another Work a conflict, and a Work the gate doesn't hold
|
|
1792
|
+
// (never held, or settled under another key) not_found, as the
|
|
1793
|
+
// host answers it.
|
|
1794
|
+
const prior = this.#settleKeys.get(p.key);
|
|
1795
|
+
if (prior !== undefined) {
|
|
1796
|
+
if (prior.work !== p.work_id)
|
|
1797
|
+
throw new ProtocolError(Code.Conflict, "the key settled another Work");
|
|
1798
|
+
return { event_id: prior.event };
|
|
1799
|
+
}
|
|
1800
|
+
if (!this.#holds.has(p.work_id))
|
|
1801
|
+
throw new ProtocolError(Code.NotFound, "the Work is not held by this extension's start gate");
|
|
1802
|
+
const id = `sdktest-settle/${p.key}`;
|
|
1803
|
+
this.#settleKeys.set(p.key, { work: p.work_id, event: id });
|
|
1804
|
+
this.#holds.delete(p.work_id);
|
|
1805
|
+
this.#settled.set(p.work_id, p.admit ? "admitted" : "cancelled");
|
|
1806
|
+
if (!p.admit)
|
|
1807
|
+
this.#cancelled.set(p.work_id, p.reason ?? "");
|
|
1808
|
+
return { event_id: id };
|
|
1809
|
+
}
|
|
1810
|
+
case "event.render_owned": {
|
|
1811
|
+
const p = params(EventRenderOwnedParams, raw);
|
|
1812
|
+
const text = this.#o.renderOwned?.(p.event);
|
|
1813
|
+
return text === undefined ? { ok: false } : { text, ok: true };
|
|
1814
|
+
}
|
|
1815
|
+
case "wait.target": {
|
|
1816
|
+
const p = params(TargetResolveParams, raw);
|
|
1817
|
+
if (!this.#scopes.has(p.scope_id))
|
|
1818
|
+
throw unauthorized("scope is not configured for this extension");
|
|
1819
|
+
const fn = this.#o.waitTargets;
|
|
1820
|
+
if (fn === undefined)
|
|
1821
|
+
throw new ProtocolError(Code.Unsupported, "wait.target");
|
|
1822
|
+
const found = fn(p.scope_id, p.kind, p.name);
|
|
1823
|
+
return found === undefined
|
|
1824
|
+
? { key: { source: "", external_id: "" }, ok: false }
|
|
1825
|
+
: { key: found.key, types: found.types, ok: true };
|
|
1826
|
+
}
|
|
1827
|
+
case "scope.authorize": {
|
|
1828
|
+
const p = params(ScopeAuthorizeParams, raw);
|
|
1829
|
+
if (!this.#scopes.has(p.from))
|
|
1830
|
+
throw unauthorized("scope is not configured for this extension");
|
|
1831
|
+
if (p.kind !== "read" && p.kind !== "file")
|
|
1832
|
+
throw invalid("kind is read or file");
|
|
1833
|
+
const fn = this.#o.authorize;
|
|
1834
|
+
if (fn === undefined)
|
|
1835
|
+
throw new ProtocolError(Code.Unsupported, "scope.authorize");
|
|
1836
|
+
const reason = fn(p.kind, p.from, p.to);
|
|
1837
|
+
return reason === undefined
|
|
1838
|
+
? { allowed: true }
|
|
1839
|
+
: { allowed: false, reason };
|
|
1840
|
+
}
|
|
1841
|
+
case "action.list":
|
|
1842
|
+
case "request.list":
|
|
1843
|
+
case "action.submit":
|
|
1844
|
+
return this.#act(method, raw);
|
|
463
1845
|
case "wait.progress": {
|
|
464
1846
|
const p = params(t.object({ work_id: t.string(), progress: t.string() }, { open: true }), raw);
|
|
465
1847
|
this.#progress.set(p.work_id, p.progress);
|
|
@@ -499,6 +1881,53 @@ export class TestHost {
|
|
|
499
1881
|
}
|
|
500
1882
|
throw new ProtocolError(Code.Unsupported, `${method} is not served by the test host`);
|
|
501
1883
|
}
|
|
1884
|
+
#act(method, raw) {
|
|
1885
|
+
// As the host's permission catalogue checks it.
|
|
1886
|
+
if (!this.#allows("action.submit"))
|
|
1887
|
+
throw new ProtocolError(Code.Undeclared, `${method} needs the action.submit permission`);
|
|
1888
|
+
const a = this.#o.actions;
|
|
1889
|
+
if (method === "action.list") {
|
|
1890
|
+
const p = params(ActionListParams, raw);
|
|
1891
|
+
if (!this.#scopes.has(p.scope_id))
|
|
1892
|
+
throw unauthorized("scope is not configured for this extension");
|
|
1893
|
+
if (a?.offers === undefined)
|
|
1894
|
+
throw new ProtocolError(Code.Unsupported, "action.list");
|
|
1895
|
+
return { actions: a.offers(p.scope_id, p.work_id ?? "") };
|
|
1896
|
+
}
|
|
1897
|
+
if (method === "request.list") {
|
|
1898
|
+
const p = params(RequestListParams, raw);
|
|
1899
|
+
if (!this.#scopes.has(p.scope_id))
|
|
1900
|
+
throw unauthorized("scope is not configured for this extension");
|
|
1901
|
+
if (a?.requests === undefined)
|
|
1902
|
+
throw new ProtocolError(Code.Unsupported, "request.list");
|
|
1903
|
+
return { requests: a.requests(p.scope_id, p.work_id) };
|
|
1904
|
+
}
|
|
1905
|
+
const p = params(ActionSubmitParams, raw);
|
|
1906
|
+
if (!this.#scopes.has(p.scope_id))
|
|
1907
|
+
throw unauthorized("scope is not configured for this extension");
|
|
1908
|
+
if (a?.submit === undefined)
|
|
1909
|
+
throw new ProtocolError(Code.Unsupported, "action.submit");
|
|
1910
|
+
const name = this.#ext.manifest.name;
|
|
1911
|
+
const r = a.submit({
|
|
1912
|
+
scopeId: p.scope_id,
|
|
1913
|
+
workId: p.work_id ?? "",
|
|
1914
|
+
provider: p.provider ?? "",
|
|
1915
|
+
action: p.action,
|
|
1916
|
+
input: p.input ?? "",
|
|
1917
|
+
caller: { kind: name, id: p.caller },
|
|
1918
|
+
key: p.key,
|
|
1919
|
+
});
|
|
1920
|
+
const { accepted, added } = this.#accept(p.scope_id, {
|
|
1921
|
+
source: "sdktest.actions",
|
|
1922
|
+
delivery_id: `${name}/${p.key}`,
|
|
1923
|
+
...r.event,
|
|
1924
|
+
}, "");
|
|
1925
|
+
return {
|
|
1926
|
+
event: accepted,
|
|
1927
|
+
added,
|
|
1928
|
+
...(r.message ? { message: r.message } : {}),
|
|
1929
|
+
};
|
|
1930
|
+
}
|
|
502
1931
|
/** state.works as the host answers it (StateParams.Query, storage.SelectWorks). */
|
|
503
1932
|
#queryWorks(p) {
|
|
504
1933
|
if (p.scope_id && !this.#scopes.has(p.scope_id))
|
|
@@ -709,3 +2138,28 @@ function workSource(w) {
|
|
|
709
2138
|
function inNamespace(name, ns, sep) {
|
|
710
2139
|
return (ns === name || (ns.startsWith(name + sep) && ns.length > name.length + 1));
|
|
711
2140
|
}
|
|
2141
|
+
/** A sandbox plan's digest as the host pins it (extension.SandboxDigest). */
|
|
2142
|
+
export function sandboxDigest(argv, data) {
|
|
2143
|
+
return ("sha256:" +
|
|
2144
|
+
createHash("sha256").update(JSON.stringify({ argv, data })).digest("hex"));
|
|
2145
|
+
}
|
|
2146
|
+
/** A plan's digest as the host pins it (extension.ContainerDigest). */
|
|
2147
|
+
export function containerDigest(image, data) {
|
|
2148
|
+
return ("sha256:" +
|
|
2149
|
+
createHash("sha256").update(JSON.stringify({ image, data })).digest("hex"));
|
|
2150
|
+
}
|
|
2151
|
+
const containerPayload = (config) => ({
|
|
2152
|
+
schema: "core.config.container.v1",
|
|
2153
|
+
data: config ?? {},
|
|
2154
|
+
});
|
|
2155
|
+
function hostLabelled(owner, s) {
|
|
2156
|
+
return (owner.execution_id === "" ||
|
|
2157
|
+
s.ref.labels?.[ContainerLabel.Execution] === owner.execution_id);
|
|
2158
|
+
}
|
|
2159
|
+
export { checkResourceProvider, checkSandboxProvider, checkTunnelProvider, } from "./providertest.js";
|
|
2160
|
+
export { checkContainerForwarder, checkContainerPlacer, checkContainerProvider, } from "./containertest.js";
|
|
2161
|
+
export { ForwardAuthority } from "./forwardca.js";
|
|
2162
|
+
export { checkActions, checkPanels, checkRequests, testScope, testWork, } from "./actiontest.js";
|
|
2163
|
+
export { TestToolbelt, checkExecutor, checkInjectExecutor, checkStateSweeper, checkTurnEnds, testRunRequest, } from "./executortest.js";
|
|
2164
|
+
export { artifactCases, backupCases, checkArtifactStore, checkBackupDestination, testArtifactProvider, } from "./storetest.js";
|
|
2165
|
+
export { Redacted, configHash, redactConfig, } from "./setuptest.js";
|