@open-conduit/sdk 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +12 -2
- 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 +127 -0
- package/dist/errors.js +180 -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 +855 -0
- package/dist/extension.js +1822 -0
- 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 +295 -0
- package/dist/host.js +486 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.js +31 -0
- package/dist/jsonrpc.d.ts +39 -0
- package/dist/jsonrpc.js +350 -0
- 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/schema.d.ts +71 -0
- package/dist/schema.js +252 -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 +756 -0
- package/dist/testing.js +2165 -0
- 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 +5359 -0
- package/dist/wire.js +2211 -0
- package/package.json +29 -4
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// The resource, sandbox and tunnel provider checks, for a TypeScript
|
|
2
|
+
// provider reached through the test host (TestHost.resourceProvider,
|
|
3
|
+
// sandboxProvider, tunnelProvider). Each resolves when the provider keeps
|
|
4
|
+
// the contract the host relies on (extension.ResourceProvider,
|
|
5
|
+
// SandboxProvider and TunnelProvider, and the resources.workspace,
|
|
6
|
+
// sandboxes.policy and tunnels.policy criteria `extension certify` runs)
|
|
7
|
+
// and rejects with what it broke, so a package's own tests hold it there
|
|
8
|
+
// before certify does.
|
|
9
|
+
import { randomBytes } from "node:crypto";
|
|
10
|
+
import { createServer, } from "node:http";
|
|
11
|
+
import { Code, ProtocolError } from "./errors.js";
|
|
12
|
+
import { checkPublicURL } from "./tunnel.js";
|
|
13
|
+
const fail = (message) => {
|
|
14
|
+
throw new Error(message);
|
|
15
|
+
};
|
|
16
|
+
const show = (v) => JSON.stringify(v);
|
|
17
|
+
const code = (err) => err instanceof ProtocolError ? err.code : String(err);
|
|
18
|
+
async function refused(what, p, want) {
|
|
19
|
+
const err = await p.then(() => undefined, (e) => e ?? new Error("refused"));
|
|
20
|
+
if (err === undefined)
|
|
21
|
+
fail(`${what}: answered, want a refusal`);
|
|
22
|
+
if (want !== undefined && code(err) !== want)
|
|
23
|
+
fail(`${what}: refused with ${code(err)}, want ${want}`);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Checks the lease contract the host relies on
|
|
27
|
+
* (extension.ResourceProvider): acquiring again for the same owner and
|
|
28
|
+
* mode returns the same lease; lookup returns it to its owner and refuses
|
|
29
|
+
* another Work's lookup (and, for a fresh lease, which is its execution's
|
|
30
|
+
* alone, another execution's of the same Work), and an unknown reference,
|
|
31
|
+
* with resource_not_found, never creating one; reconcile keeps the lease of an
|
|
32
|
+
* owner still running, and runs again, once the owner is done, without
|
|
33
|
+
* failing.
|
|
34
|
+
*/
|
|
35
|
+
export async function checkResourceProvider(f) {
|
|
36
|
+
const p = f.provider;
|
|
37
|
+
const owner = {
|
|
38
|
+
scope_id: "conformance-scope",
|
|
39
|
+
work_id: "conformance-work",
|
|
40
|
+
execution_id: "conformance-execution",
|
|
41
|
+
};
|
|
42
|
+
const other = {
|
|
43
|
+
scope_id: "conformance-scope",
|
|
44
|
+
work_id: "conformance-other-work",
|
|
45
|
+
execution_id: "conformance-other-execution",
|
|
46
|
+
};
|
|
47
|
+
const request = f.mode ? { mode: f.mode } : {};
|
|
48
|
+
const first = await p
|
|
49
|
+
.acquire(owner, f.config, request)
|
|
50
|
+
.catch((err) => fail(`acquire: ${String(err)}`));
|
|
51
|
+
if (first.setupFailed)
|
|
52
|
+
fail("acquire: the fixture's setup failed");
|
|
53
|
+
if (!first.resource.ref || !first.resource.kind)
|
|
54
|
+
fail(`acquire: a resource needs a kind and a ref: ${show(first.resource)}`);
|
|
55
|
+
const again = await p
|
|
56
|
+
.acquire(owner, f.config, request)
|
|
57
|
+
.catch((err) => fail(`acquire again: ${String(err)}`));
|
|
58
|
+
if (again.resource.ref !== first.resource.ref ||
|
|
59
|
+
again.resource.dir !== first.resource.dir)
|
|
60
|
+
fail(`acquiring again for the same owner and mode made another lease: ${show(again.resource.ref)}, first ${show(first.resource.ref)}`);
|
|
61
|
+
const ref = first.resource.ref;
|
|
62
|
+
const found = await p
|
|
63
|
+
.lookup(owner, ref)
|
|
64
|
+
.catch((err) => fail(`lookup of the owner's lease: ${String(err)}`));
|
|
65
|
+
if (found.ref !== ref || found.dir !== first.resource.dir)
|
|
66
|
+
fail(`lookup answered ${show(found)}, not the acquired lease`);
|
|
67
|
+
await refused("lookup of a lease by another Work", p.lookup(other, ref), Code.ResourceNotFound);
|
|
68
|
+
if (f.mode === "fresh")
|
|
69
|
+
await refused("lookup of a fresh lease by another execution of its Work", p.lookup({ ...owner, execution_id: "conformance-next-execution" }, ref), Code.ResourceNotFound);
|
|
70
|
+
const unknown = `conformance-unknown-${randomBytes(4).toString("hex")}`;
|
|
71
|
+
await refused("lookup of a reference no lease has", p.lookup(owner, unknown), Code.ResourceNotFound);
|
|
72
|
+
await refused("lookup of a reference no lease has, asked again", p.lookup(owner, unknown), Code.ResourceNotFound);
|
|
73
|
+
const running = (o) => o.execution_id === owner.execution_id ? { known: true } : {};
|
|
74
|
+
await p
|
|
75
|
+
.reconcile(running)
|
|
76
|
+
.catch((err) => fail(`reconcile while the owner runs: ${String(err)}`));
|
|
77
|
+
const kept = await p
|
|
78
|
+
.lookup(owner, ref)
|
|
79
|
+
.catch((err) => fail(`reconcile released a running owner's lease: ${String(err)}`));
|
|
80
|
+
if (kept.ref !== ref)
|
|
81
|
+
fail(`after reconcile, lookup answered ${show(kept.ref)}, not ${show(ref)}`);
|
|
82
|
+
const done = () => ({
|
|
83
|
+
known: true,
|
|
84
|
+
executionDone: true,
|
|
85
|
+
executionSucceeded: true,
|
|
86
|
+
workDone: true,
|
|
87
|
+
workSucceeded: true,
|
|
88
|
+
});
|
|
89
|
+
for (const pass of ["once the owner is done", "again"]) {
|
|
90
|
+
const r = await p
|
|
91
|
+
.reconcile(done)
|
|
92
|
+
.catch((err) => fail(`reconcile ${pass}: ${String(err)}`));
|
|
93
|
+
for (const n of [r.active, r.released, r.removed, r.retained])
|
|
94
|
+
if (!Number.isInteger(n) || n < 0)
|
|
95
|
+
fail(`reconcile ${pass}: counts must be whole numbers: ${show(r)}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Checks the sandbox contract the host relies on
|
|
100
|
+
* (extension.SandboxProvider, sandboxes.policy): a launch inside the
|
|
101
|
+
* policy is planned to a command; a need outside the policy is denied,
|
|
102
|
+
* never widened into it;
|
|
103
|
+
* and adopt refuses a plan the provider never made, so a restarted host
|
|
104
|
+
* never adopts a segment it can't prove is confined.
|
|
105
|
+
*/
|
|
106
|
+
export async function checkSandboxProvider(f) {
|
|
107
|
+
const p = f.provider;
|
|
108
|
+
const owner = {
|
|
109
|
+
scope_id: "conformance-scope",
|
|
110
|
+
work_id: "conformance-work",
|
|
111
|
+
execution_id: "conformance-execution",
|
|
112
|
+
};
|
|
113
|
+
const plan = await p
|
|
114
|
+
.plan(owner, f.policy, f.needs, f.launch)
|
|
115
|
+
.catch((err) => fail(`plan: ${String(err)}`));
|
|
116
|
+
if (!plan.argv?.length)
|
|
117
|
+
fail("plan: no command");
|
|
118
|
+
await refused("plan with a need outside the policy", p.plan(owner, f.policy, f.denied, f.launch), Code.SandboxDenied);
|
|
119
|
+
await refused("adopt of a plan the provider never made", p.adopt({
|
|
120
|
+
argv: ["true"],
|
|
121
|
+
digest: "certify-unknown",
|
|
122
|
+
data: { schema: "certify.unknown.v1", data: {} },
|
|
123
|
+
}, 0, 0));
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Checks the tunnel contract the host relies on (extension.TunnelProvider,
|
|
127
|
+
* tunnels.policy): validate accepts the config and refuses the refused
|
|
128
|
+
* one; a run publishes a URL the host can point webhooks at; and, for a
|
|
129
|
+
* reachable tunnel, a request to it reaches the address the host gave and
|
|
130
|
+
* nothing else.
|
|
131
|
+
*/
|
|
132
|
+
export async function checkTunnelProvider(f) {
|
|
133
|
+
const p = f.provider;
|
|
134
|
+
await p
|
|
135
|
+
.validate(f.config)
|
|
136
|
+
.catch((err) => fail(`validate refused the config: ${String(err)}`));
|
|
137
|
+
await refused("validate of the refused config", p.validate(f.refused));
|
|
138
|
+
const token = randomBytes(8).toString("hex");
|
|
139
|
+
const listener = createServer((req, res) => {
|
|
140
|
+
// Plain text: the echoed path is never read as markup.
|
|
141
|
+
res.writeHead(200, {
|
|
142
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
143
|
+
"X-Content-Type-Options": "nosniff",
|
|
144
|
+
});
|
|
145
|
+
res.end(`${token} ${req.url ?? ""}`);
|
|
146
|
+
});
|
|
147
|
+
await new Promise((resolve) => listener.listen(0, "127.0.0.1", () => resolve()));
|
|
148
|
+
const addr = `127.0.0.1:${listener.address().port}`;
|
|
149
|
+
const run = p.start(addr, f.config);
|
|
150
|
+
try {
|
|
151
|
+
const next = () => run.next().catch((err) => fail(`the run's URL: ${String(err)}`));
|
|
152
|
+
let url = await next();
|
|
153
|
+
while (url === "")
|
|
154
|
+
url = await next();
|
|
155
|
+
if (!checkPublicURL(url))
|
|
156
|
+
fail(`the run published ${show(url)}, which the host refuses`);
|
|
157
|
+
if (f.reachable) {
|
|
158
|
+
const got = await fetch(new URL("/conformance/hook", url)).then((r) => r.text(), (err) => fail(`a request to ${url}: ${String(err)}`));
|
|
159
|
+
if (got !== `${token} /conformance/hook`)
|
|
160
|
+
fail(`a request through the tunnel reached ${show(got)}, not the listener at ${addr}`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
await run.stop();
|
|
165
|
+
listener.closeAllConnections();
|
|
166
|
+
await new Promise((resolve) => listener.close(() => resolve()));
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import type { Context } from "./extension.js";
|
|
2
|
+
import { type Value } from "./host.js";
|
|
3
|
+
import { type Infer, type Type } from "./schema.js";
|
|
4
|
+
import { type FieldDecl, type Payload, type ResourceDecl, type ResourceOwner, type ResourceSweepReport, type ResourceUnsaved, type SandboxNeeds, type SettingDecl, type ValidateParams } from "./wire.js";
|
|
5
|
+
/** The resource modes (extension.ResourceShared, ResourceWork, ResourceFresh). */
|
|
6
|
+
export declare const ResourceMode: {
|
|
7
|
+
/** One long-lived resource shared by concurrent users, never reset on a user's behalf. */
|
|
8
|
+
readonly Shared: "shared";
|
|
9
|
+
/** Private to one Work and reused by each of its attempts until the Work is terminal. */
|
|
10
|
+
readonly Work: "work";
|
|
11
|
+
/** Private to one execution, created for it and cleaned up after it finishes. */
|
|
12
|
+
readonly Fresh: "fresh";
|
|
13
|
+
};
|
|
14
|
+
export type ResourceModeName = (typeof ResourceMode)[keyof typeof ResourceMode];
|
|
15
|
+
/** A command to run at a site (extension.SiteCommand). */
|
|
16
|
+
export interface SiteCommandInput {
|
|
17
|
+
argv: string[];
|
|
18
|
+
dir?: string;
|
|
19
|
+
env?: string[];
|
|
20
|
+
stdin?: Value;
|
|
21
|
+
/** 0 or absent for none. */
|
|
22
|
+
timeoutMs?: number;
|
|
23
|
+
}
|
|
24
|
+
/** What a command run at a site did (extension.SiteResult). A command that ran and failed is its exit code, not an error. */
|
|
25
|
+
export interface SiteRunResult {
|
|
26
|
+
exitCode: number;
|
|
27
|
+
stdout: Uint8Array;
|
|
28
|
+
stderr: Uint8Array;
|
|
29
|
+
truncated: boolean;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* A placement a resource provider may act at (extension.Site): id names
|
|
33
|
+
* it stably, for the provider's own records, and run runs one command
|
|
34
|
+
* there within the same boundary and grant as a launch at that site. A
|
|
35
|
+
* site the host can't run at throws Code.SiteUnavailable.
|
|
36
|
+
*/
|
|
37
|
+
export interface Site {
|
|
38
|
+
readonly id: string;
|
|
39
|
+
run(cmd: SiteCommandInput, signal?: AbortSignal): Promise<SiteRunResult>;
|
|
40
|
+
}
|
|
41
|
+
/** The trusted request a provider receives (extension.ResourceAcquisition). */
|
|
42
|
+
export interface ResourceAcquisition<C> {
|
|
43
|
+
type: string;
|
|
44
|
+
/** The owner the host bound, never one an executor supplied. */
|
|
45
|
+
owner: ResourceOwner;
|
|
46
|
+
/** The binding's resource config, decoded by the provider's schema. */
|
|
47
|
+
config: C;
|
|
48
|
+
/** The mode the executor asks for, or "" for the config's default. */
|
|
49
|
+
mode: string;
|
|
50
|
+
/** The executor's request: provider-defined and opaque to the host. */
|
|
51
|
+
params: Payload;
|
|
52
|
+
/** Paths relative to the resource's directory to read at acquisition; a provider at a site returns their contents in files. */
|
|
53
|
+
files: string[];
|
|
54
|
+
/** The host's values of the variables the binding's resource names in its pass_env: the only host environment a provider adds to its own. */
|
|
55
|
+
hostEnv: Record<string, string>;
|
|
56
|
+
/** Where the attempt's launch will run, for a provider declared with sites when the launch is placed off the host. */
|
|
57
|
+
site?: Site;
|
|
58
|
+
/** Writes human-readable progress (setup output, how far a shared resource is behind), never a secret. */
|
|
59
|
+
log(text: string): void;
|
|
60
|
+
}
|
|
61
|
+
/** An acquired resource (extension.Resource). */
|
|
62
|
+
export interface ResourceOut {
|
|
63
|
+
kind: string;
|
|
64
|
+
/** The opaque lease reference an executor may keep. */
|
|
65
|
+
ref: string;
|
|
66
|
+
dir?: string;
|
|
67
|
+
/** The provider's environment layer; never persisted by the provider. */
|
|
68
|
+
env?: Record<string, string>;
|
|
69
|
+
/** What the acquisition did, for history. */
|
|
70
|
+
data: Payload;
|
|
71
|
+
summary?: string;
|
|
72
|
+
/** What a sandbox must allow to use the resource; absent, it can't be used in one. */
|
|
73
|
+
sandbox?: SandboxNeeds;
|
|
74
|
+
/** The site the resource was made at; dir is then a path there. */
|
|
75
|
+
site?: string;
|
|
76
|
+
/** The contents of the request's files that exist at the site, by path. */
|
|
77
|
+
files?: Record<string, string>;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The resource exists but its setup failed (extension.ErrResourceSetup):
|
|
81
|
+
* throw it from acquire with the resource, which the host keeps for
|
|
82
|
+
* inspection under the provider's failure policy.
|
|
83
|
+
*/
|
|
84
|
+
export declare class ResourceSetupError extends Error {
|
|
85
|
+
readonly resource: ResourceOut;
|
|
86
|
+
constructor(resource: ResourceOut, message?: string);
|
|
87
|
+
}
|
|
88
|
+
/** A lease owner's durable status, as the host reports it (extension.ResourceOwnerStatus). */
|
|
89
|
+
export interface ResourceOwnerStatus {
|
|
90
|
+
known: boolean;
|
|
91
|
+
/** The attempt is terminal and nothing still runs in its resources. */
|
|
92
|
+
executionDone: boolean;
|
|
93
|
+
executionSucceeded: boolean;
|
|
94
|
+
workDone: boolean;
|
|
95
|
+
workSucceeded: boolean;
|
|
96
|
+
/** Host paths a live container holds: a resource beneath or holding one is in use. */
|
|
97
|
+
mounts: string[];
|
|
98
|
+
}
|
|
99
|
+
/** Reads an owner's status from the host's durable state, while a reconcile or sweep runs. */
|
|
100
|
+
export type ResourceStatusFn = (owner: ResourceOwner) => Promise<ResourceOwnerStatus>;
|
|
101
|
+
/** One lease that needs operator attention (extension.ResourceLeaseReport). */
|
|
102
|
+
export interface LeaseAttention {
|
|
103
|
+
ref: string;
|
|
104
|
+
mode: string;
|
|
105
|
+
state: string;
|
|
106
|
+
code?: string;
|
|
107
|
+
/** Until when it is kept; absent for none. */
|
|
108
|
+
retainUntil?: Date | string;
|
|
109
|
+
}
|
|
110
|
+
/** What one reconcile pass did (extension.ResourceReport). */
|
|
111
|
+
export interface ReconcileReport {
|
|
112
|
+
active: number;
|
|
113
|
+
released: number;
|
|
114
|
+
removed: number;
|
|
115
|
+
retained: number;
|
|
116
|
+
attention?: LeaseAttention[];
|
|
117
|
+
}
|
|
118
|
+
/** The context of a resource provider's call. */
|
|
119
|
+
export interface ResourceContext extends Context {
|
|
120
|
+
/**
|
|
121
|
+
* The type's state directory the host named at initialize ("" when it
|
|
122
|
+
* named none): keep leases and workspaces there, so they outlive a move
|
|
123
|
+
* of the provider in or out of process.
|
|
124
|
+
*/
|
|
125
|
+
dir: string;
|
|
126
|
+
/** The extension's private state directory, from initialize. */
|
|
127
|
+
stateDir: string;
|
|
128
|
+
/**
|
|
129
|
+
* A site the host resolves for the type: one it gave the type in an
|
|
130
|
+
* acquisition, of a container provider a binding still pairs with it.
|
|
131
|
+
* Only a type declared with sites may run there; the host refuses the
|
|
132
|
+
* rest.
|
|
133
|
+
*/
|
|
134
|
+
site(id: string): Site;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* A resource provider type (extension.ResourceProvider), which a binding's
|
|
138
|
+
* resource config names. The host never inspects resources: it binds the
|
|
139
|
+
* provider to an attempt and drives reconcile from durable owner state.
|
|
140
|
+
*
|
|
141
|
+
* acquire is idempotent per owner and mode: acquiring again (a resumed
|
|
142
|
+
* segment, a retried launch) returns the same lease and never duplicates
|
|
143
|
+
* the resource. Record a lease durably before creating anything, so a
|
|
144
|
+
* crash at any point leaves one reconcile can find. lookup returns a lease
|
|
145
|
+
* the owner already holds and never creates one; reconcile releases leases
|
|
146
|
+
* whose owners finished, applies retention, retries failed cleanup, and is
|
|
147
|
+
* safe to call repeatedly and after a restart.
|
|
148
|
+
*
|
|
149
|
+
* Refuse with a ProtocolError: Code.ResourceNotFound for a lease the
|
|
150
|
+
* owner doesn't hold, Code.ResourceExhausted (saying what to free) when a
|
|
151
|
+
* capacity the provider guards is too low, Code.Unsupported for a mode it
|
|
152
|
+
* doesn't serve. Throw ResourceSetupError when the resource exists but its
|
|
153
|
+
* setup failed. Anything else crosses as internal.
|
|
154
|
+
*
|
|
155
|
+
* The optional capabilities are declared by being given: modeDefault and
|
|
156
|
+
* sandboxWorkspace answer config check, sweep removes spare resources no
|
|
157
|
+
* release covers, unsaved says which hold work a move would lose, and
|
|
158
|
+
* needsSite declares sites.
|
|
159
|
+
*/
|
|
160
|
+
export interface ResourceProviderSpec<S extends Type<unknown>> {
|
|
161
|
+
/** The modes it serves; a request for another is refused as unsupported before acquire runs. */
|
|
162
|
+
modes: ResourceModeName[];
|
|
163
|
+
/** The resource config's schema: validate (kind resource) refuses a config it doesn't match. */
|
|
164
|
+
config?: S;
|
|
165
|
+
/** The resource config's fields, for adapters and the config editor. */
|
|
166
|
+
fields?: FieldDecl[];
|
|
167
|
+
/** The resource config fields safe to show the operator. */
|
|
168
|
+
settings?: SettingDecl[];
|
|
169
|
+
/**
|
|
170
|
+
* Checks the schema can't express; throw to refuse the config. A
|
|
171
|
+
* ConfigError says which field is wrong and why; anything else thrown is
|
|
172
|
+
* reported only as invalid.
|
|
173
|
+
*/
|
|
174
|
+
validate?: (config: Infer<S>) => void | Promise<void>;
|
|
175
|
+
/** The mode a resource config itself writes as its default, "" for none (manifest mode_default). */
|
|
176
|
+
modeDefault?: (config: Infer<S>) => string;
|
|
177
|
+
/**
|
|
178
|
+
* Refuses, by throwing, a resource config whose workspace an executor in
|
|
179
|
+
* a sandbox could only use by writing outside it, or that runs setup
|
|
180
|
+
* outside it; mode is the executor's request ("" for the config's
|
|
181
|
+
* default). The thrown message is what the operator reads: a fixed
|
|
182
|
+
* reason that never quotes the config (manifest sandbox).
|
|
183
|
+
*/
|
|
184
|
+
sandboxWorkspace?: (config: Infer<S>, mode: string) => void;
|
|
185
|
+
/** Whether a resource config can only be made at a site (manifest sites): the acquisition is then given its site. */
|
|
186
|
+
needsSite?: (config: Infer<S>) => boolean;
|
|
187
|
+
acquire: (a: ResourceAcquisition<Infer<S>>, ctx: ResourceContext) => ResourceOut | Promise<ResourceOut>;
|
|
188
|
+
lookup: (owner: ResourceOwner, ref: string, ctx: ResourceContext) => ResourceOut | Promise<ResourceOut>;
|
|
189
|
+
reconcile: (status: ResourceStatusFn, ctx: ResourceContext) => ReconcileReport | Promise<ReconcileReport>;
|
|
190
|
+
/** Removes spare resources no lease release covers, never one with unsaved work or one in use (manifest sweep). */
|
|
191
|
+
sweep?: (status: ResourceStatusFn, ctx: ResourceContext) => ResourceSweepReport | Promise<ResourceSweepReport>;
|
|
192
|
+
/** The resources holding work a move of this host would lose; it reads and changes nothing (manifest unsaved). */
|
|
193
|
+
unsaved?: (ctx: ResourceContext) => ResourceUnsaved[] | Promise<ResourceUnsaved[]>;
|
|
194
|
+
}
|
|
195
|
+
/** @internal */
|
|
196
|
+
export interface ResourceHandler {
|
|
197
|
+
decl: Omit<ResourceDecl, "type">;
|
|
198
|
+
/** Answers validate of kind resource, resource_mode, resource_sandbox and resource_site. */
|
|
199
|
+
validate: (p: ValidateParams) => Promise<unknown>;
|
|
200
|
+
serve: (method: string, raw: unknown, ctx: ResourceContext) => Promise<unknown>;
|
|
201
|
+
}
|
|
202
|
+
/** @internal */
|
|
203
|
+
export declare function resourceHandler<S extends Type<unknown>>(type: string, spec: ResourceProviderSpec<S>, params: <T extends Type<unknown>>(schema: T, raw: unknown) => Infer<T>): ResourceHandler;
|
|
204
|
+
/**
|
|
205
|
+
* A site as site.run reaches it: at the acquisition's site under call, or
|
|
206
|
+
* (without one) a site the host resolves for the type.
|
|
207
|
+
*/
|
|
208
|
+
export declare function site(ctx: Context, type: string, id: string, call?: string): Site;
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
// Resource providers: provider.* and the resource config check kinds, as
|
|
2
|
+
// protocol/sdk serves sdk.Extension.Providers (protocol/sdk/surfaces.go).
|
|
3
|
+
// The host binds a provider to an attempt (extension.BindResources), so a
|
|
4
|
+
// provider only ever sees the trusted owner the host bound, never one an
|
|
5
|
+
// executor names; it drives reconcile and sweep from the host's durable
|
|
6
|
+
// owner state, which the provider reads back through provider.owner_status
|
|
7
|
+
// while the pass runs. A provider declared with sites makes resources at
|
|
8
|
+
// the site a launch is placed at, running commands there through site.run.
|
|
9
|
+
import { Code, ConfigError, ProtocolError } from "./errors.js";
|
|
10
|
+
import { base64, toBytes } from "./host.js";
|
|
11
|
+
import { diagnose, isRecord, matches, } from "./schema.js";
|
|
12
|
+
import { OwnerStatus, ProviderAcquireParams, ProviderLookupParams, ProviderReconcileParams, SiteResult, } from "./wire.js";
|
|
13
|
+
/** The resource modes (extension.ResourceShared, ResourceWork, ResourceFresh). */
|
|
14
|
+
export const ResourceMode = {
|
|
15
|
+
/** One long-lived resource shared by concurrent users, never reset on a user's behalf. */
|
|
16
|
+
Shared: "shared",
|
|
17
|
+
/** Private to one Work and reused by each of its attempts until the Work is terminal. */
|
|
18
|
+
Work: "work",
|
|
19
|
+
/** Private to one execution, created for it and cleaned up after it finishes. */
|
|
20
|
+
Fresh: "fresh",
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* The resource exists but its setup failed (extension.ErrResourceSetup):
|
|
24
|
+
* throw it from acquire with the resource, which the host keeps for
|
|
25
|
+
* inspection under the provider's failure policy.
|
|
26
|
+
*/
|
|
27
|
+
export class ResourceSetupError extends Error {
|
|
28
|
+
resource;
|
|
29
|
+
constructor(resource, message = "resource setup failed") {
|
|
30
|
+
super(message);
|
|
31
|
+
this.name = "ResourceSetupError";
|
|
32
|
+
this.resource = resource;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const modes = new Set(Object.values(ResourceMode));
|
|
36
|
+
/** @internal */
|
|
37
|
+
export function resourceHandler(type, spec, params) {
|
|
38
|
+
if (spec.modes.length === 0)
|
|
39
|
+
throw new Error(`sdk: resource provider type ${type} must list its modes`);
|
|
40
|
+
for (const [i, m] of spec.modes.entries())
|
|
41
|
+
if (!modes.has(m) || spec.modes.indexOf(m) !== i)
|
|
42
|
+
throw new Error(`sdk: resource provider type ${type} mode ${m} must be a distinct shared, work or fresh`);
|
|
43
|
+
const schema = spec.config;
|
|
44
|
+
// A stored binding passed validate; one whose config no longer matches
|
|
45
|
+
// (a package upgrade changed the schema) acquires nothing.
|
|
46
|
+
const config = (raw) => {
|
|
47
|
+
const c = raw ?? {};
|
|
48
|
+
if (schema !== undefined && !matches(schema, c))
|
|
49
|
+
throw new ProtocolError(Code.Invalid, "the binding's resource config doesn't match the provider's");
|
|
50
|
+
return c;
|
|
51
|
+
};
|
|
52
|
+
// For config check: a config that doesn't decode names no mode, needs
|
|
53
|
+
// no site, and is refused for a sandbox with a fixed reason.
|
|
54
|
+
const decoded = (raw) => {
|
|
55
|
+
const c = raw ?? {};
|
|
56
|
+
return schema === undefined || matches(schema, c)
|
|
57
|
+
? c
|
|
58
|
+
: undefined;
|
|
59
|
+
};
|
|
60
|
+
return {
|
|
61
|
+
decl: {
|
|
62
|
+
modes: [...spec.modes],
|
|
63
|
+
...(spec.modeDefault ? { mode_default: true } : {}),
|
|
64
|
+
...(spec.sandboxWorkspace ? { sandbox: true } : {}),
|
|
65
|
+
...(spec.sweep ? { sweep: true } : {}),
|
|
66
|
+
...(spec.unsaved ? { unsaved: true } : {}),
|
|
67
|
+
...(spec.needsSite ? { sites: true } : {}),
|
|
68
|
+
...(spec.settings?.length ? { settings: spec.settings } : {}),
|
|
69
|
+
...(spec.fields?.length ? { fields: spec.fields } : {}),
|
|
70
|
+
},
|
|
71
|
+
validate: async (p) => {
|
|
72
|
+
switch (p.kind) {
|
|
73
|
+
case "resource": {
|
|
74
|
+
const c = p.config ?? {};
|
|
75
|
+
if (schema !== undefined && !matches(schema, c)) {
|
|
76
|
+
const diagnostics = diagnose(schema, c);
|
|
77
|
+
if (diagnostics.length > 0)
|
|
78
|
+
throw new ConfigError(diagnostics);
|
|
79
|
+
throw new ProtocolError(Code.Invalid, "invalid resource config");
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
await spec.validate?.(c);
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
if (err instanceof ConfigError)
|
|
86
|
+
throw err;
|
|
87
|
+
throw new ProtocolError(Code.Invalid, "invalid resource config");
|
|
88
|
+
}
|
|
89
|
+
return {};
|
|
90
|
+
}
|
|
91
|
+
case "resource_mode": {
|
|
92
|
+
const c = decoded(p.config);
|
|
93
|
+
const mode = c === undefined ? "" : (spec.modeDefault?.(c) ?? "");
|
|
94
|
+
return mode ? { mode } : {};
|
|
95
|
+
}
|
|
96
|
+
case "resource_sandbox": {
|
|
97
|
+
if (spec.sandboxWorkspace === undefined)
|
|
98
|
+
return {};
|
|
99
|
+
const c = decoded(p.config);
|
|
100
|
+
if (c === undefined)
|
|
101
|
+
throw new ProtocolError(Code.Invalid, "the resource config doesn't match the provider's");
|
|
102
|
+
try {
|
|
103
|
+
spec.sandboxWorkspace(c, p.mode ?? "");
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
// The reason is what the operator reads.
|
|
107
|
+
throw new ProtocolError(Code.Invalid, err instanceof Error ? err.message : String(err));
|
|
108
|
+
}
|
|
109
|
+
return {};
|
|
110
|
+
}
|
|
111
|
+
case "resource_site": {
|
|
112
|
+
if (spec.needsSite === undefined)
|
|
113
|
+
return {};
|
|
114
|
+
const c = decoded(p.config);
|
|
115
|
+
// One that doesn't decode can't be made anywhere, so a binding
|
|
116
|
+
// that doesn't place is refused rather than passed.
|
|
117
|
+
return c === undefined || spec.needsSite(c) ? { site: true } : {};
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return {};
|
|
121
|
+
},
|
|
122
|
+
serve: async (method, raw, ctx) => {
|
|
123
|
+
switch (method) {
|
|
124
|
+
case "provider.acquire": {
|
|
125
|
+
const p = params(ProviderAcquireParams, raw);
|
|
126
|
+
const mode = p.mode ?? "";
|
|
127
|
+
if (mode !== "" && !spec.modes.includes(mode))
|
|
128
|
+
throw new ProtocolError(Code.Unsupported, `resource provider ${type} doesn't serve mode ${mode}`);
|
|
129
|
+
let log = "";
|
|
130
|
+
const a = {
|
|
131
|
+
type,
|
|
132
|
+
owner: p.owner,
|
|
133
|
+
config: config(p.config.data),
|
|
134
|
+
mode,
|
|
135
|
+
params: p.params,
|
|
136
|
+
files: [...(p.files ?? [])],
|
|
137
|
+
hostEnv: { ...(p.host_env ?? {}) },
|
|
138
|
+
log: (text) => {
|
|
139
|
+
log += text;
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
// Only a type declared with sites is given one, as the host gives it.
|
|
143
|
+
if (p.site !== undefined && spec.needsSite !== undefined)
|
|
144
|
+
a.site = site(ctx, type, p.site.id, p.site.call);
|
|
145
|
+
let out;
|
|
146
|
+
try {
|
|
147
|
+
out = { resource: resourceOut(await spec.acquire(a, ctx)) };
|
|
148
|
+
}
|
|
149
|
+
catch (err) {
|
|
150
|
+
if (!(err instanceof ResourceSetupError))
|
|
151
|
+
throw err;
|
|
152
|
+
out = { resource: resourceOut(err.resource), setup_failed: true };
|
|
153
|
+
}
|
|
154
|
+
if (log !== "")
|
|
155
|
+
out.log = log;
|
|
156
|
+
return out;
|
|
157
|
+
}
|
|
158
|
+
case "provider.lookup": {
|
|
159
|
+
const p = params(ProviderLookupParams, raw);
|
|
160
|
+
return {
|
|
161
|
+
resource: resourceOut(await spec.lookup(p.owner, p.ref, ctx)),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
case "provider.reconcile": {
|
|
165
|
+
const p = params(ProviderReconcileParams, raw);
|
|
166
|
+
return reportOut(await spec.reconcile(ownerStatus(ctx, p.reconcile), ctx));
|
|
167
|
+
}
|
|
168
|
+
case "provider.sweep": {
|
|
169
|
+
if (spec.sweep === undefined)
|
|
170
|
+
break;
|
|
171
|
+
const p = params(ProviderReconcileParams, raw);
|
|
172
|
+
return sweepOut(await spec.sweep(ownerStatus(ctx, p.reconcile), ctx));
|
|
173
|
+
}
|
|
174
|
+
case "provider.unsaved": {
|
|
175
|
+
if (spec.unsaved === undefined)
|
|
176
|
+
break;
|
|
177
|
+
const found = await spec.unsaved(ctx);
|
|
178
|
+
return found.length > 0
|
|
179
|
+
? {
|
|
180
|
+
resources: found.map((r) => ({
|
|
181
|
+
ref: r.ref,
|
|
182
|
+
...(r.mode ? { mode: r.mode } : {}),
|
|
183
|
+
...(r.path ? { path: r.path } : {}),
|
|
184
|
+
...(r.site ? { site: r.site } : {}),
|
|
185
|
+
kept: r.kept,
|
|
186
|
+
})),
|
|
187
|
+
}
|
|
188
|
+
: {};
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
throw new ProtocolError(Code.MethodNotFound, `no such method ${method}`);
|
|
192
|
+
},
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* A site as site.run reaches it: at the acquisition's site under call, or
|
|
197
|
+
* (without one) a site the host resolves for the type.
|
|
198
|
+
*/
|
|
199
|
+
export function site(ctx, type, id, call) {
|
|
200
|
+
return {
|
|
201
|
+
id,
|
|
202
|
+
run: async (cmd, signal) => {
|
|
203
|
+
const stdin = cmd.stdin === undefined ? undefined : toBytes(cmd.stdin);
|
|
204
|
+
const out = await ctx.host.call("site.run", {
|
|
205
|
+
type,
|
|
206
|
+
...(call ? { call } : {}),
|
|
207
|
+
site: id,
|
|
208
|
+
command: {
|
|
209
|
+
argv: [...cmd.argv],
|
|
210
|
+
...(cmd.dir ? { dir: cmd.dir } : {}),
|
|
211
|
+
...(cmd.env?.length ? { env: [...cmd.env] } : {}),
|
|
212
|
+
...(stdin?.length ? { stdin: base64(stdin) } : {}),
|
|
213
|
+
...(cmd.timeoutMs
|
|
214
|
+
? { timeout_millis: Math.floor(cmd.timeoutMs) }
|
|
215
|
+
: {}),
|
|
216
|
+
},
|
|
217
|
+
}, SiteResult, signal ?? ctx.signal);
|
|
218
|
+
return {
|
|
219
|
+
exitCode: out.exit_code,
|
|
220
|
+
stdout: bytes(out.stdout),
|
|
221
|
+
stderr: bytes(out.stderr),
|
|
222
|
+
truncated: out.truncated === true,
|
|
223
|
+
};
|
|
224
|
+
},
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
function ownerStatus(ctx, reconcile) {
|
|
228
|
+
return async (owner) => {
|
|
229
|
+
const s = await ctx.host.call("provider.owner_status", { reconcile, owner }, OwnerStatus, ctx.signal);
|
|
230
|
+
return {
|
|
231
|
+
known: s.known,
|
|
232
|
+
executionDone: s.execution_done,
|
|
233
|
+
executionSucceeded: s.execution_succeeded,
|
|
234
|
+
workDone: s.work_done,
|
|
235
|
+
workSucceeded: s.work_succeeded,
|
|
236
|
+
mounts: [...(s.mounts ?? [])],
|
|
237
|
+
};
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
function resourceOut(r) {
|
|
241
|
+
if (!isRecord(r) || typeof r.kind !== "string" || typeof r.ref !== "string")
|
|
242
|
+
throw new Error("sdk: a resource needs a kind and a ref");
|
|
243
|
+
return {
|
|
244
|
+
kind: r.kind,
|
|
245
|
+
ref: r.ref,
|
|
246
|
+
...(r.dir ? { dir: r.dir } : {}),
|
|
247
|
+
...(r.env && Object.keys(r.env).length > 0 ? { env: { ...r.env } } : {}),
|
|
248
|
+
data: r.data ?? {},
|
|
249
|
+
...(r.summary ? { summary: r.summary } : {}),
|
|
250
|
+
...(r.sandbox ? { sandbox: r.sandbox } : {}),
|
|
251
|
+
...(r.site ? { site: r.site } : {}),
|
|
252
|
+
...(r.files && Object.keys(r.files).length > 0
|
|
253
|
+
? { files: { ...r.files } }
|
|
254
|
+
: {}),
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
/** Go's zero time, which a lease report without a retention carries. */
|
|
258
|
+
const zeroTime = "0001-01-01T00:00:00Z";
|
|
259
|
+
function reportOut(r) {
|
|
260
|
+
return {
|
|
261
|
+
active: r.active,
|
|
262
|
+
released: r.released,
|
|
263
|
+
removed: r.removed,
|
|
264
|
+
retained: r.retained,
|
|
265
|
+
...(r.attention?.length
|
|
266
|
+
? {
|
|
267
|
+
attention: r.attention.map((a) => ({
|
|
268
|
+
ref: a.ref,
|
|
269
|
+
mode: a.mode,
|
|
270
|
+
state: a.state,
|
|
271
|
+
...(a.code ? { code: a.code } : {}),
|
|
272
|
+
retain_until: time(a.retainUntil),
|
|
273
|
+
})),
|
|
274
|
+
}
|
|
275
|
+
: {}),
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
function sweepOut(r) {
|
|
279
|
+
const spares = (in_) => (in_ ?? []).map((s) => ({
|
|
280
|
+
ref: s.ref,
|
|
281
|
+
...(s.mode ? { mode: s.mode } : {}),
|
|
282
|
+
spare: s.spare,
|
|
283
|
+
...(s.kept ? { kept: s.kept } : {}),
|
|
284
|
+
}));
|
|
285
|
+
const removed = spares(r.removed);
|
|
286
|
+
const kept = spares(r.kept);
|
|
287
|
+
return {
|
|
288
|
+
...(removed.length > 0 ? { removed } : {}),
|
|
289
|
+
...(kept.length > 0 ? { kept } : {}),
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
function time(t) {
|
|
293
|
+
if (t === undefined || t === "")
|
|
294
|
+
return zeroTime;
|
|
295
|
+
if (t instanceof Date)
|
|
296
|
+
return Number.isNaN(t.getTime()) ? zeroTime : t.toISOString();
|
|
297
|
+
return t;
|
|
298
|
+
}
|
|
299
|
+
function bytes(b64) {
|
|
300
|
+
return b64 === undefined
|
|
301
|
+
? new Uint8Array()
|
|
302
|
+
: new Uint8Array(Buffer.from(b64, "base64"));
|
|
303
|
+
}
|