@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
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// The action, panel and request contracts, as conformance.CheckActions,
|
|
2
|
+
// CheckPanels and CheckRequests hold a Go provider to them. Each takes a
|
|
3
|
+
// TestActionProvider, which TestHost.actionProvider gives as the host
|
|
4
|
+
// reaches the extension over the wire, and throws why it fails.
|
|
5
|
+
import { OperationError } from "./errors.js";
|
|
6
|
+
import { PanelLimits, RequestState, Tone, panelProblem, } from "./actions.js";
|
|
7
|
+
import { testStart } from "./testing.js";
|
|
8
|
+
/** A scope as the host sends it in a target (state.scope's shape), for tests. */
|
|
9
|
+
export function testScope(id, o = {}) {
|
|
10
|
+
return {
|
|
11
|
+
id,
|
|
12
|
+
name: id,
|
|
13
|
+
config: {},
|
|
14
|
+
revision: 1,
|
|
15
|
+
created_at: testStart,
|
|
16
|
+
updated_at: testStart,
|
|
17
|
+
...o,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/** A Work as the host sends it, for tests: of kind in scope, its context data data. */
|
|
21
|
+
export function testWork(id, o = {}) {
|
|
22
|
+
const { data, ...rest } = o;
|
|
23
|
+
return {
|
|
24
|
+
id,
|
|
25
|
+
kind: "sdktest.work",
|
|
26
|
+
scope_id: "s1",
|
|
27
|
+
state: "waiting",
|
|
28
|
+
correlation_keys: null,
|
|
29
|
+
context: { schema: "sdktest.work.v1", data: data ?? {} },
|
|
30
|
+
revision: 1,
|
|
31
|
+
created_at: testStart,
|
|
32
|
+
updated_at: testStart,
|
|
33
|
+
...rest,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
const actionId = /^[a-z][a-z0-9_]*$/;
|
|
37
|
+
/**
|
|
38
|
+
* Checks, as conformance.CheckActions does: listing is well formed and
|
|
39
|
+
* offers the action only where it is available; a granted invocation plans
|
|
40
|
+
* one Event of the expected family, the same each time, so a replay is
|
|
41
|
+
* safe; and an unavailable target, a caller it doesn't recognise, invalid
|
|
42
|
+
* input and an unknown action are each refused with an OperationError of
|
|
43
|
+
* an authored code, so the host accepts no Event.
|
|
44
|
+
*/
|
|
45
|
+
export async function checkActions(f) {
|
|
46
|
+
const listed = async (t) => {
|
|
47
|
+
const seen = new Set();
|
|
48
|
+
for (const a of await f.provider.actions(t)) {
|
|
49
|
+
if (!actionId.test(a.id) || a.label.trim() === "")
|
|
50
|
+
throw new Error(`malformed action ${JSON.stringify(a)}`);
|
|
51
|
+
if (seen.has(a.id))
|
|
52
|
+
throw new Error(`duplicate action ${a.id}`);
|
|
53
|
+
seen.add(a.id);
|
|
54
|
+
}
|
|
55
|
+
return seen.has(f.action);
|
|
56
|
+
};
|
|
57
|
+
if (!(await listed(f.available)))
|
|
58
|
+
throw new Error("action not offered where available");
|
|
59
|
+
if (await listed(f.unavailable))
|
|
60
|
+
throw new Error("action offered where nothing is outstanding");
|
|
61
|
+
const call = {
|
|
62
|
+
target: f.available,
|
|
63
|
+
action: f.action,
|
|
64
|
+
input: f.input,
|
|
65
|
+
caller: f.caller,
|
|
66
|
+
};
|
|
67
|
+
let plan;
|
|
68
|
+
try {
|
|
69
|
+
plan = await f.provider.invoke(call);
|
|
70
|
+
}
|
|
71
|
+
catch (err) {
|
|
72
|
+
throw new Error(`granted invocation failed: ${String(err)}`);
|
|
73
|
+
}
|
|
74
|
+
if (plan.event.type !== f.eventType || plan.event.type.startsWith("core."))
|
|
75
|
+
throw new Error(`plan event type ${plan.event.type}, want ${f.eventType}`);
|
|
76
|
+
const again = await f.provider.invoke(call);
|
|
77
|
+
if (JSON.stringify(again) !== JSON.stringify(plan))
|
|
78
|
+
throw new Error("invocation is not deterministic");
|
|
79
|
+
const refused = async (what, c) => {
|
|
80
|
+
try {
|
|
81
|
+
await f.provider.invoke(c);
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
if (err instanceof OperationError &&
|
|
85
|
+
actionId.test(err.code) &&
|
|
86
|
+
err.message.trim() !== "")
|
|
87
|
+
return;
|
|
88
|
+
throw new Error(`${what} not refused with an authored code: ${err}`);
|
|
89
|
+
}
|
|
90
|
+
throw new Error(`${what} not refused`);
|
|
91
|
+
};
|
|
92
|
+
await refused("unavailable target", { ...call, target: f.unavailable });
|
|
93
|
+
await refused("unrecognised caller", { ...call, caller: f.stranger });
|
|
94
|
+
if (f.badInput !== undefined)
|
|
95
|
+
await refused("invalid input", { ...call, input: f.badInput });
|
|
96
|
+
await refused("unknown action", { ...call, action: "no_such_action" });
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Checks, as conformance.CheckPanels does: on shown, 1 to PanelLimits.panels
|
|
100
|
+
* panels, each within the document limits (panelProblem) with a unique
|
|
101
|
+
* ID, every button naming an action listed on the same target, the same
|
|
102
|
+
* panels each time; and none on hidden.
|
|
103
|
+
*/
|
|
104
|
+
export async function checkPanels(f) {
|
|
105
|
+
const panels = await f.provider.panels(f.shown);
|
|
106
|
+
if (panels.length === 0 || panels.length > PanelLimits.panels)
|
|
107
|
+
throw new Error(`shows ${panels.length} panels, want 1 to ${PanelLimits.panels}`);
|
|
108
|
+
const listed = new Set((await f.provider.actions(f.shown)).map((a) => a.id));
|
|
109
|
+
const seen = new Set();
|
|
110
|
+
for (const p of panels) {
|
|
111
|
+
const bad = panelProblem(p);
|
|
112
|
+
if (bad)
|
|
113
|
+
throw new Error(`panel not shown: ${bad}`);
|
|
114
|
+
if (seen.has(p.id))
|
|
115
|
+
throw new Error(`duplicate panel ${p.id}`);
|
|
116
|
+
seen.add(p.id);
|
|
117
|
+
for (const s of p.sections)
|
|
118
|
+
for (const a of s.actions ?? [])
|
|
119
|
+
if (!listed.has(a))
|
|
120
|
+
throw new Error(`panel ${p.id} offers action ${a} the provider does not list here`);
|
|
121
|
+
}
|
|
122
|
+
const again = await f.provider.panels(f.shown);
|
|
123
|
+
if (JSON.stringify(again) !== JSON.stringify(panels))
|
|
124
|
+
throw new Error("panels are not deterministic");
|
|
125
|
+
const hidden = await f.provider.panels(f.hidden);
|
|
126
|
+
if (hidden.length !== 0)
|
|
127
|
+
throw new Error(`panels shown where there is nothing to show: ${hidden.length}`);
|
|
128
|
+
}
|
|
129
|
+
const states = new Set(Object.values(RequestState));
|
|
130
|
+
/**
|
|
131
|
+
* Checks, as conformance.CheckRequests does, on every target: each request
|
|
132
|
+
* has an ID unique on the target and a label, a known state, and who and
|
|
133
|
+
* when only once settled; its wording is an approval or a question, not
|
|
134
|
+
* both, each choice worded once, toned affirm, danger or not at all, and
|
|
135
|
+
* one of its action's choices; its action is named only while it is open,
|
|
136
|
+
* offered on the target now, and by no other request. answerable reports
|
|
137
|
+
* an open request with its action.
|
|
138
|
+
*/
|
|
139
|
+
export async function checkRequests(f) {
|
|
140
|
+
const check = async (t) => {
|
|
141
|
+
const requests = await f.provider.requests(t);
|
|
142
|
+
const choices = new Map((await f.provider.actions(t)).map((a) => [a.id, a.choices ?? []]));
|
|
143
|
+
const ids = new Set();
|
|
144
|
+
const named = new Set();
|
|
145
|
+
let answerable = 0;
|
|
146
|
+
for (const r of requests) {
|
|
147
|
+
if (r.id.trim() === "" || r.label.trim() === "")
|
|
148
|
+
throw new Error(`request without an ID or label: ${JSON.stringify(r)}`);
|
|
149
|
+
if (ids.has(r.id))
|
|
150
|
+
throw new Error(`request ID ${r.id} reported twice`);
|
|
151
|
+
if (!states.has(r.state))
|
|
152
|
+
throw new Error(`request ${r.id} has state ${r.state}`);
|
|
153
|
+
if (r.by && r.state === RequestState.Open)
|
|
154
|
+
throw new Error(`open request ${r.id} says who settled it`);
|
|
155
|
+
if (r.settledAt !== undefined && r.state === RequestState.Open)
|
|
156
|
+
throw new Error(`open request ${r.id} says when it was settled`);
|
|
157
|
+
const w = r.wording;
|
|
158
|
+
if (w !== undefined) {
|
|
159
|
+
if (w.wants && w.question)
|
|
160
|
+
throw new Error(`request ${r.id} is worded as an approval and a question`);
|
|
161
|
+
const worded = new Set();
|
|
162
|
+
for (const c of w.choices ?? []) {
|
|
163
|
+
if (worded.has(c.choice))
|
|
164
|
+
throw new Error(`request ${r.id} words choice ${c.choice} twice`);
|
|
165
|
+
if (c.tone && c.tone !== Tone.Affirm && c.tone !== Tone.Danger)
|
|
166
|
+
throw new Error(`request ${r.id} gives choice ${c.choice} the tone ${c.tone}`);
|
|
167
|
+
if (r.action && !(choices.get(r.action) ?? []).includes(c.choice))
|
|
168
|
+
throw new Error(`request ${r.id} words choice ${c.choice}, which action ${r.action} doesn't offer`);
|
|
169
|
+
worded.add(c.choice);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
ids.add(r.id);
|
|
173
|
+
if (!r.action)
|
|
174
|
+
continue;
|
|
175
|
+
if (r.state !== RequestState.Open)
|
|
176
|
+
throw new Error(`settled request ${r.id} names action ${r.action}`);
|
|
177
|
+
if (!choices.has(r.action))
|
|
178
|
+
throw new Error(`request ${r.id} names action ${r.action}, which is not offered`);
|
|
179
|
+
if (named.has(r.action))
|
|
180
|
+
throw new Error(`action ${r.action} is named by two requests`);
|
|
181
|
+
named.add(r.action);
|
|
182
|
+
answerable++;
|
|
183
|
+
}
|
|
184
|
+
return answerable;
|
|
185
|
+
};
|
|
186
|
+
if ((await check(f.answerable)) === 0)
|
|
187
|
+
throw new Error("no open request with its action where one is answerable");
|
|
188
|
+
for (const t of f.others)
|
|
189
|
+
await check(t);
|
|
190
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { type Readable, Writable } from "node:stream";
|
|
2
|
+
/** The artifact provider protocol's version (artifactstore.Version). */
|
|
3
|
+
export declare const ArtifactStoreVersion = 1;
|
|
4
|
+
/** The most content one artifact provider message carries (artifactstore.MaxChunk). */
|
|
5
|
+
export declare const ArtifactStoreChunk: number;
|
|
6
|
+
/**
|
|
7
|
+
* The codes a store refuses with (storage's errors, as artifactstore
|
|
8
|
+
* encodes them): throw an ArtifactError with one.
|
|
9
|
+
*/
|
|
10
|
+
export declare const ArtifactCode: {
|
|
11
|
+
/** storage.ErrNotFound: no such artifact, or not with that ref. */
|
|
12
|
+
readonly NotFound: string;
|
|
13
|
+
/** storage.ErrConflict: an import of an ID the store already holds. */
|
|
14
|
+
readonly Conflict: string;
|
|
15
|
+
/** storage.ErrInvalid: a request the store can't take. */
|
|
16
|
+
readonly Invalid: string;
|
|
17
|
+
/** storage.ErrCorrupt: stored content doesn't match its ref. */
|
|
18
|
+
readonly Corrupt: "artifact_corrupt";
|
|
19
|
+
/** storage.ErrInUse: another process holds the store. */
|
|
20
|
+
readonly InUse: "artifact_in_use";
|
|
21
|
+
/** storage.ErrOwnedElsewhere: another installation owns the location. Its message crosses to the host. */
|
|
22
|
+
readonly OwnedElsewhere: "artifact_owned_elsewhere";
|
|
23
|
+
};
|
|
24
|
+
export type ArtifactCode = (typeof ArtifactCode)[keyof typeof ArtifactCode];
|
|
25
|
+
/**
|
|
26
|
+
* A store's refusal, as one of ArtifactCode. Every code but
|
|
27
|
+
* OwnedElsewhere crosses with a fixed message, so nothing the store says
|
|
28
|
+
* about its content reaches the host's log; OwnedElsewhere's message names
|
|
29
|
+
* the conflict for the operator, so it must not quote a secret. Anything
|
|
30
|
+
* else thrown crosses as internal.
|
|
31
|
+
*/
|
|
32
|
+
export declare class ArtifactError extends Error {
|
|
33
|
+
readonly code: ArtifactCode;
|
|
34
|
+
constructor(code: ArtifactCode, message?: string);
|
|
35
|
+
}
|
|
36
|
+
/** An artifact's reference (storage.StoredArtifactRef): its ID, size, media type and content's SHA-256 in hex. */
|
|
37
|
+
export interface StoredArtifactRef {
|
|
38
|
+
id: string;
|
|
39
|
+
size: number;
|
|
40
|
+
mediaType: string;
|
|
41
|
+
sha256?: string;
|
|
42
|
+
}
|
|
43
|
+
/** One committed artifact, for collection (storage.StoredArtifact). */
|
|
44
|
+
export interface StoredArtifact {
|
|
45
|
+
ref: StoredArtifactRef;
|
|
46
|
+
publishedAt: Date;
|
|
47
|
+
}
|
|
48
|
+
/** Who claims a store's location (storage.Ownership). */
|
|
49
|
+
export interface Ownership {
|
|
50
|
+
/** The claiming installation's ID. */
|
|
51
|
+
installation: string;
|
|
52
|
+
/** Replace another installation's claim: the operator forced a takeover. */
|
|
53
|
+
takeOver?: boolean;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Content being written (storage.ArtifactWriter). Nothing of it is read or
|
|
57
|
+
* listed until commit, which publishes it under a new ID and returns its
|
|
58
|
+
* ref, with the size and SHA-256 of what was written; close abandons it.
|
|
59
|
+
* The host forgets the writer after either, so a second commit, or a
|
|
60
|
+
* write or close after one, is refused before it reaches the writer.
|
|
61
|
+
*/
|
|
62
|
+
export interface ArtifactWriter {
|
|
63
|
+
write(chunk: Uint8Array): void | Promise<void>;
|
|
64
|
+
commit(): StoredArtifactRef | Promise<StoredArtifactRef>;
|
|
65
|
+
close(): void | Promise<void>;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* An open store (storage.ArtifactStore). Its content is immutable once
|
|
69
|
+
* committed. What is thrown crosses as an ArtifactError's code, and as
|
|
70
|
+
* internal otherwise.
|
|
71
|
+
*/
|
|
72
|
+
export interface ArtifactStore {
|
|
73
|
+
/** Starts content of mediaType. */
|
|
74
|
+
create(mediaType: string): ArtifactWriter | Promise<ArtifactWriter>;
|
|
75
|
+
/**
|
|
76
|
+
* The content of ref, which must match the stored artifact's size and
|
|
77
|
+
* media type (NotFound otherwise). Reading it to its end throws Corrupt
|
|
78
|
+
* if the bytes don't match its size and digest; the host checks too.
|
|
79
|
+
*/
|
|
80
|
+
open(ref: StoredArtifactRef): AsyncIterable<Uint8Array> | Promise<AsyncIterable<Uint8Array>>;
|
|
81
|
+
/** Removes ref's artifact; one already gone is no error, one with a different ref is NotFound. */
|
|
82
|
+
delete(ref: StoredArtifactRef): void | Promise<void>;
|
|
83
|
+
/** Committed artifacts in ID order after after ("" for the first), at most limit. */
|
|
84
|
+
list(after: string, limit: number): StoredArtifact[] | Promise<StoredArtifact[]>;
|
|
85
|
+
/**
|
|
86
|
+
* Publishes body as exactly ref, ID included, for a restore: Conflict if
|
|
87
|
+
* the ID is taken, Corrupt (and nothing published) if body doesn't match
|
|
88
|
+
* ref's size and digest. If body throws, nothing is published.
|
|
89
|
+
*/
|
|
90
|
+
import(ref: StoredArtifactRef, body: AsyncIterable<Uint8Array>): void | Promise<void>;
|
|
91
|
+
/** Releases the store, when the host closes the connection. */
|
|
92
|
+
close?(): void | Promise<void>;
|
|
93
|
+
/**
|
|
94
|
+
* Whether another host can reach what the store holds
|
|
95
|
+
* (storage.ArtifactReach): true for an object store, false for a
|
|
96
|
+
* directory on this machine. Leave it out to make no claim.
|
|
97
|
+
*/
|
|
98
|
+
shared?: boolean;
|
|
99
|
+
/**
|
|
100
|
+
* Records that o.installation owns the store's location
|
|
101
|
+
* (storage.OwnedLocation.Claim): an ArtifactError OwnedElsewhere if
|
|
102
|
+
* another installation does, unless o.takeOver, which replaces its
|
|
103
|
+
* claim. The same installation claiming again succeeds. Without claim
|
|
104
|
+
* and checkOwner the store keeps no ownership marker, and doctor warns
|
|
105
|
+
* that nothing stops two installations sharing it.
|
|
106
|
+
*/
|
|
107
|
+
claim?(o: Ownership): void | Promise<void>;
|
|
108
|
+
/** Throws OwnedElsewhere if an installation other than installation has claimed the location. */
|
|
109
|
+
checkOwner?(installation: string): void | Promise<void>;
|
|
110
|
+
}
|
|
111
|
+
/** Opens a store at a location, in the provider's own terms (storage.ArtifactBackend). */
|
|
112
|
+
export interface ArtifactBackend {
|
|
113
|
+
open(location: string, signal: AbortSignal): ArtifactStore | Promise<ArtifactStore>;
|
|
114
|
+
}
|
|
115
|
+
/** A provider serving one connection. */
|
|
116
|
+
export interface ArtifactProvider {
|
|
117
|
+
/** Resolves once the host has closed the connection and everything it left open is closed. */
|
|
118
|
+
done: Promise<void>;
|
|
119
|
+
/** Ends the connection. */
|
|
120
|
+
close(): void;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Serves backend as an artifact provider on input and output (tests pass a
|
|
124
|
+
* pair of in-memory streams) until the host closes the connection, then
|
|
125
|
+
* closes whatever the host left open and the store.
|
|
126
|
+
*/
|
|
127
|
+
export declare function serveArtifactProvider(backend: ArtifactBackend, input: Readable, output: Writable): ArtifactProvider;
|
|
128
|
+
/**
|
|
129
|
+
* The entry point of an artifact provider executable: serves backend on
|
|
130
|
+
* stdin and stdout until the host closes stdin, then exits. stdout carries
|
|
131
|
+
* the protocol, so console output goes to stderr, the provider's log.
|
|
132
|
+
*/
|
|
133
|
+
export declare function serveArtifactStore(backend: ArtifactBackend): Promise<void>;
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
// Artifact stores: a storage.ArtifactBackend in its own process, as
|
|
2
|
+
// protocol/artifactstore.Serve runs one in Go, so an artifact store (an
|
|
3
|
+
// object store, anything else) can be written in TypeScript and named by
|
|
4
|
+
// the state directory's storage.json without changing Open Conduit.
|
|
5
|
+
//
|
|
6
|
+
// import { serveArtifactStore } from "@open-conduit/sdk";
|
|
7
|
+
// await serveArtifactStore(myBackend);
|
|
8
|
+
//
|
|
9
|
+
// This is not the extension protocol: the host starts the provider by the
|
|
10
|
+
// command storage.json names and speaks the artifact provider protocol
|
|
11
|
+
// (site/src/content/docs/architecture/artifact-providers.md) over its
|
|
12
|
+
// stdin and stdout. The host doesn't take a provider's word for content:
|
|
13
|
+
// it computes the size and digest of everything it writes and reads, and
|
|
14
|
+
// refuses what doesn't match its reference.
|
|
15
|
+
import { Writable } from "node:stream";
|
|
16
|
+
import { Code, ProtocolError } from "./errors.js";
|
|
17
|
+
import { Feed } from "./feed.js";
|
|
18
|
+
import { Conn } from "./jsonrpc.js";
|
|
19
|
+
import { matches } from "./schema.js";
|
|
20
|
+
import { ArtifactStoreCheckOwnerParams, ArtifactStoreChunkParams, ArtifactStoreClaimParams, ArtifactStoreCreateParams, ArtifactStoreHandle, ArtifactStoreInitializeParams, ArtifactStoreListParams, ArtifactStoreRef, } from "./wire.js";
|
|
21
|
+
/** The artifact provider protocol's version (artifactstore.Version). */
|
|
22
|
+
export const ArtifactStoreVersion = 1;
|
|
23
|
+
/** The most content one artifact provider message carries (artifactstore.MaxChunk). */
|
|
24
|
+
export const ArtifactStoreChunk = 1 << 20;
|
|
25
|
+
/**
|
|
26
|
+
* The codes a store refuses with (storage's errors, as artifactstore
|
|
27
|
+
* encodes them): throw an ArtifactError with one.
|
|
28
|
+
*/
|
|
29
|
+
export const ArtifactCode = {
|
|
30
|
+
/** storage.ErrNotFound: no such artifact, or not with that ref. */
|
|
31
|
+
NotFound: Code.NotFound,
|
|
32
|
+
/** storage.ErrConflict: an import of an ID the store already holds. */
|
|
33
|
+
Conflict: Code.Conflict,
|
|
34
|
+
/** storage.ErrInvalid: a request the store can't take. */
|
|
35
|
+
Invalid: Code.Invalid,
|
|
36
|
+
/** storage.ErrCorrupt: stored content doesn't match its ref. */
|
|
37
|
+
Corrupt: "artifact_corrupt",
|
|
38
|
+
/** storage.ErrInUse: another process holds the store. */
|
|
39
|
+
InUse: "artifact_in_use",
|
|
40
|
+
/** storage.ErrOwnedElsewhere: another installation owns the location. Its message crosses to the host. */
|
|
41
|
+
OwnedElsewhere: "artifact_owned_elsewhere",
|
|
42
|
+
};
|
|
43
|
+
const fixedMessage = {
|
|
44
|
+
[ArtifactCode.NotFound]: "artifact not found",
|
|
45
|
+
[ArtifactCode.Conflict]: "artifact already exists",
|
|
46
|
+
[ArtifactCode.Invalid]: "invalid artifact request",
|
|
47
|
+
[ArtifactCode.Corrupt]: "artifact content is corrupt",
|
|
48
|
+
[ArtifactCode.InUse]: "artifact store is in use",
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* A store's refusal, as one of ArtifactCode. Every code but
|
|
52
|
+
* OwnedElsewhere crosses with a fixed message, so nothing the store says
|
|
53
|
+
* about its content reaches the host's log; OwnedElsewhere's message names
|
|
54
|
+
* the conflict for the operator, so it must not quote a secret. Anything
|
|
55
|
+
* else thrown crosses as internal.
|
|
56
|
+
*/
|
|
57
|
+
export class ArtifactError extends Error {
|
|
58
|
+
code;
|
|
59
|
+
constructor(code, message) {
|
|
60
|
+
super(message ?? fixedMessage[code] ?? code);
|
|
61
|
+
this.name = "ArtifactError";
|
|
62
|
+
this.code = code;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const maxEmptyReads = 100;
|
|
66
|
+
function base64(b) {
|
|
67
|
+
return Buffer.from(b.buffer, b.byteOffset, b.byteLength).toString("base64");
|
|
68
|
+
}
|
|
69
|
+
function fromBase64(s) {
|
|
70
|
+
return s === undefined || s === null || s === ""
|
|
71
|
+
? new Uint8Array()
|
|
72
|
+
: new Uint8Array(Buffer.from(s, "base64"));
|
|
73
|
+
}
|
|
74
|
+
function params(schema, raw) {
|
|
75
|
+
const p = raw ?? {};
|
|
76
|
+
if (!matches(schema, p))
|
|
77
|
+
throw new ProtocolError(Code.Invalid, "malformed params");
|
|
78
|
+
return p;
|
|
79
|
+
}
|
|
80
|
+
function fromWire(r) {
|
|
81
|
+
return {
|
|
82
|
+
id: r.id,
|
|
83
|
+
size: r.size,
|
|
84
|
+
mediaType: r.media_type,
|
|
85
|
+
...(r.sha256 ? { sha256: r.sha256 } : {}),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function toWire(r) {
|
|
89
|
+
return {
|
|
90
|
+
id: r.id,
|
|
91
|
+
size: r.size,
|
|
92
|
+
media_type: r.mediaType,
|
|
93
|
+
...(r.sha256 ? { sha256: r.sha256 } : {}),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/** A storage error with a code that survives the wire (artifactstore's encodeError). */
|
|
97
|
+
function encode(err) {
|
|
98
|
+
if (err instanceof ArtifactError)
|
|
99
|
+
return new ProtocolError(err.code, err.code === ArtifactCode.OwnedElsewhere
|
|
100
|
+
? err.message
|
|
101
|
+
: (fixedMessage[err.code] ?? err.code));
|
|
102
|
+
return err;
|
|
103
|
+
}
|
|
104
|
+
/** An open reader: what is left of the chunk the store last gave, and the error or end that follows. */
|
|
105
|
+
class Reader {
|
|
106
|
+
#it;
|
|
107
|
+
#rest = new Uint8Array();
|
|
108
|
+
#ended = false;
|
|
109
|
+
#err;
|
|
110
|
+
constructor(it) {
|
|
111
|
+
this.#it = it;
|
|
112
|
+
}
|
|
113
|
+
async read() {
|
|
114
|
+
for (let empty = 0; this.#rest.length === 0; empty++) {
|
|
115
|
+
if (this.#err !== undefined)
|
|
116
|
+
throw this.#err;
|
|
117
|
+
if (this.#ended)
|
|
118
|
+
return { eof: true };
|
|
119
|
+
if (empty === maxEmptyReads)
|
|
120
|
+
throw new ProtocolError(Code.Internal, "the reader made no progress");
|
|
121
|
+
try {
|
|
122
|
+
const r = await this.#it.next();
|
|
123
|
+
if (r.done)
|
|
124
|
+
this.#ended = true;
|
|
125
|
+
else
|
|
126
|
+
this.#rest = r.value;
|
|
127
|
+
}
|
|
128
|
+
catch (err) {
|
|
129
|
+
this.#err = encode(err);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const out = this.#rest.subarray(0, ArtifactStoreChunk);
|
|
133
|
+
this.#rest = this.#rest.subarray(out.length);
|
|
134
|
+
return { chunk: base64(out) };
|
|
135
|
+
}
|
|
136
|
+
async close() {
|
|
137
|
+
await this.#it.return?.();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** One connection's provider: the store it opened and the handles the host holds. */
|
|
141
|
+
class ArtifactServer {
|
|
142
|
+
#backend;
|
|
143
|
+
#abort = new AbortController();
|
|
144
|
+
#store;
|
|
145
|
+
#opening = false;
|
|
146
|
+
#next = 0;
|
|
147
|
+
#writers = new Map();
|
|
148
|
+
#readers = new Map();
|
|
149
|
+
#imports = new Map();
|
|
150
|
+
constructor(backend) {
|
|
151
|
+
this.#backend = backend;
|
|
152
|
+
}
|
|
153
|
+
#id() {
|
|
154
|
+
return String(++this.#next);
|
|
155
|
+
}
|
|
156
|
+
async handle(method, raw) {
|
|
157
|
+
try {
|
|
158
|
+
return await this.#serve(method, raw);
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
throw encode(err);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
async #serve(method, raw) {
|
|
165
|
+
if (method === "artifactstore.initialize") {
|
|
166
|
+
const p = params(ArtifactStoreInitializeParams, raw);
|
|
167
|
+
if (p.version !== ArtifactStoreVersion)
|
|
168
|
+
throw new ProtocolError(Code.UnsupportedVersion, "unsupported artifact provider version");
|
|
169
|
+
if (this.#store !== undefined || this.#opening)
|
|
170
|
+
throw new ProtocolError(Code.Invalid, "provider is already initialized");
|
|
171
|
+
this.#opening = true;
|
|
172
|
+
try {
|
|
173
|
+
// The store outlives this request.
|
|
174
|
+
this.#store = await this.#backend.open(p.location, this.#abort.signal);
|
|
175
|
+
}
|
|
176
|
+
finally {
|
|
177
|
+
this.#opening = false;
|
|
178
|
+
}
|
|
179
|
+
const out = {
|
|
180
|
+
version: ArtifactStoreVersion,
|
|
181
|
+
};
|
|
182
|
+
if (typeof this.#store.shared === "boolean")
|
|
183
|
+
out.shared = this.#store.shared;
|
|
184
|
+
return out;
|
|
185
|
+
}
|
|
186
|
+
const store = this.#store;
|
|
187
|
+
if (store === undefined)
|
|
188
|
+
throw new ProtocolError(Code.Invalid, "provider is not initialized");
|
|
189
|
+
switch (method) {
|
|
190
|
+
case "artifactstore.claim": {
|
|
191
|
+
const p = params(ArtifactStoreClaimParams, raw);
|
|
192
|
+
if (store.claim === undefined || store.checkOwner === undefined)
|
|
193
|
+
throw new ProtocolError(Code.MethodNotFound, "the store keeps no ownership marker");
|
|
194
|
+
await store.claim({
|
|
195
|
+
installation: p.installation,
|
|
196
|
+
...(p.take_over ? { takeOver: true } : {}),
|
|
197
|
+
});
|
|
198
|
+
return {};
|
|
199
|
+
}
|
|
200
|
+
case "artifactstore.check_owner": {
|
|
201
|
+
const p = params(ArtifactStoreCheckOwnerParams, raw);
|
|
202
|
+
if (store.claim === undefined || store.checkOwner === undefined)
|
|
203
|
+
throw new ProtocolError(Code.MethodNotFound, "the store keeps no ownership marker");
|
|
204
|
+
await store.checkOwner(p.installation);
|
|
205
|
+
return {};
|
|
206
|
+
}
|
|
207
|
+
case "artifactstore.create": {
|
|
208
|
+
const p = params(ArtifactStoreCreateParams, raw);
|
|
209
|
+
const w = await store.create(p.media_type);
|
|
210
|
+
const id = this.#id();
|
|
211
|
+
this.#writers.set(id, w);
|
|
212
|
+
return { handle: id };
|
|
213
|
+
}
|
|
214
|
+
case "artifactstore.write": {
|
|
215
|
+
const p = params(ArtifactStoreChunkParams, raw);
|
|
216
|
+
await this.#writer(p.handle, false).write(fromBase64(p.chunk));
|
|
217
|
+
return {};
|
|
218
|
+
}
|
|
219
|
+
case "artifactstore.commit": {
|
|
220
|
+
const p = params(ArtifactStoreHandle, raw);
|
|
221
|
+
return toWire(await this.#writer(p.handle, true).commit());
|
|
222
|
+
}
|
|
223
|
+
case "artifactstore.abort": {
|
|
224
|
+
const p = params(ArtifactStoreHandle, raw);
|
|
225
|
+
await this.#writer(p.handle, true).close();
|
|
226
|
+
return {};
|
|
227
|
+
}
|
|
228
|
+
case "artifactstore.open": {
|
|
229
|
+
const p = params(ArtifactStoreRef, raw);
|
|
230
|
+
const body = await store.open(fromWire(p));
|
|
231
|
+
const id = this.#id();
|
|
232
|
+
this.#readers.set(id, new Reader(body[Symbol.asyncIterator]()));
|
|
233
|
+
return { handle: id };
|
|
234
|
+
}
|
|
235
|
+
case "artifactstore.read": {
|
|
236
|
+
const p = params(ArtifactStoreHandle, raw);
|
|
237
|
+
const r = this.#readers.get(p.handle);
|
|
238
|
+
if (r === undefined)
|
|
239
|
+
throw new ProtocolError(Code.Invalid, "unknown reader");
|
|
240
|
+
return r.read();
|
|
241
|
+
}
|
|
242
|
+
case "artifactstore.close_reader": {
|
|
243
|
+
const p = params(ArtifactStoreHandle, raw);
|
|
244
|
+
const r = this.#readers.get(p.handle);
|
|
245
|
+
this.#readers.delete(p.handle);
|
|
246
|
+
if (r === undefined)
|
|
247
|
+
throw new ProtocolError(Code.Invalid, "unknown reader");
|
|
248
|
+
await r.close();
|
|
249
|
+
return {};
|
|
250
|
+
}
|
|
251
|
+
case "artifactstore.delete": {
|
|
252
|
+
const p = params(ArtifactStoreRef, raw);
|
|
253
|
+
await store.delete(fromWire(p));
|
|
254
|
+
return {};
|
|
255
|
+
}
|
|
256
|
+
case "artifactstore.list": {
|
|
257
|
+
const p = params(ArtifactStoreListParams, raw);
|
|
258
|
+
const items = await store.list(p.after ?? "", p.limit);
|
|
259
|
+
const out = {
|
|
260
|
+
items: items.map((it) => ({
|
|
261
|
+
ref: toWire(it.ref),
|
|
262
|
+
published_at: it.publishedAt.toISOString(),
|
|
263
|
+
})),
|
|
264
|
+
};
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
case "artifactstore.import_begin": {
|
|
268
|
+
const p = params(ArtifactStoreRef, raw);
|
|
269
|
+
const feed = new Feed();
|
|
270
|
+
const done = (async () => store.import(fromWire(p), feed))();
|
|
271
|
+
// A write still in flight gets the import's own answer.
|
|
272
|
+
done.then(() => feed.stop(), (err) => feed.stop(encode(err)));
|
|
273
|
+
const id = this.#id();
|
|
274
|
+
this.#imports.set(id, { feed, done });
|
|
275
|
+
return { handle: id };
|
|
276
|
+
}
|
|
277
|
+
case "artifactstore.import_write": {
|
|
278
|
+
const p = params(ArtifactStoreChunkParams, raw);
|
|
279
|
+
const imp = this.#imports.get(p.handle);
|
|
280
|
+
if (imp === undefined)
|
|
281
|
+
throw new ProtocolError(Code.Invalid, "unknown import");
|
|
282
|
+
const chunk = fromBase64(p.chunk);
|
|
283
|
+
if (chunk.length > 0)
|
|
284
|
+
await imp.feed.push(chunk);
|
|
285
|
+
return {};
|
|
286
|
+
}
|
|
287
|
+
case "artifactstore.import_finish":
|
|
288
|
+
case "artifactstore.import_abort": {
|
|
289
|
+
const p = params(ArtifactStoreHandle, raw);
|
|
290
|
+
const imp = this.#imports.get(p.handle);
|
|
291
|
+
this.#imports.delete(p.handle);
|
|
292
|
+
if (imp === undefined)
|
|
293
|
+
throw new ProtocolError(Code.Invalid, "unknown import");
|
|
294
|
+
if (method === "artifactstore.import_abort") {
|
|
295
|
+
imp.feed.fail(new Error("artifact provider: import aborted"));
|
|
296
|
+
await imp.done.catch(() => { });
|
|
297
|
+
return {};
|
|
298
|
+
}
|
|
299
|
+
imp.feed.end();
|
|
300
|
+
await imp.done;
|
|
301
|
+
return {};
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
throw new ProtocolError(Code.MethodNotFound, "unknown method");
|
|
305
|
+
}
|
|
306
|
+
#writer(id, end) {
|
|
307
|
+
const w = this.#writers.get(id);
|
|
308
|
+
if (w === undefined)
|
|
309
|
+
throw new ProtocolError(Code.Invalid, "unknown writer");
|
|
310
|
+
if (end)
|
|
311
|
+
this.#writers.delete(id);
|
|
312
|
+
return w;
|
|
313
|
+
}
|
|
314
|
+
/** Closes whatever the host left open, then the store. */
|
|
315
|
+
async shutdown() {
|
|
316
|
+
this.#abort.abort();
|
|
317
|
+
const pending = [];
|
|
318
|
+
for (const w of this.#writers.values())
|
|
319
|
+
pending.push(Promise.resolve().then(() => w.close()));
|
|
320
|
+
for (const r of this.#readers.values())
|
|
321
|
+
pending.push(r.close());
|
|
322
|
+
for (const i of this.#imports.values()) {
|
|
323
|
+
i.feed.fail(new Error("artifact provider: import aborted"));
|
|
324
|
+
pending.push(i.done);
|
|
325
|
+
}
|
|
326
|
+
this.#writers.clear();
|
|
327
|
+
this.#readers.clear();
|
|
328
|
+
this.#imports.clear();
|
|
329
|
+
await Promise.allSettled(pending);
|
|
330
|
+
await Promise.resolve()
|
|
331
|
+
.then(() => this.#store?.close?.())
|
|
332
|
+
.catch(() => { });
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Serves backend as an artifact provider on input and output (tests pass a
|
|
337
|
+
* pair of in-memory streams) until the host closes the connection, then
|
|
338
|
+
* closes whatever the host left open and the store.
|
|
339
|
+
*/
|
|
340
|
+
export function serveArtifactProvider(backend, input, output) {
|
|
341
|
+
const server = new ArtifactServer(backend);
|
|
342
|
+
const conn = new Conn(input, output, (method, raw) => server.handle(method, raw));
|
|
343
|
+
return {
|
|
344
|
+
done: conn.done.then(() => server.shutdown()),
|
|
345
|
+
close: () => conn.close(),
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* The entry point of an artifact provider executable: serves backend on
|
|
350
|
+
* stdin and stdout until the host closes stdin, then exits. stdout carries
|
|
351
|
+
* the protocol, so console output goes to stderr, the provider's log.
|
|
352
|
+
*/
|
|
353
|
+
export async function serveArtifactStore(backend) {
|
|
354
|
+
const stdout = process.stdout;
|
|
355
|
+
const protocolWrite = stdout.write.bind(stdout);
|
|
356
|
+
stdout.write = process.stderr.write.bind(process.stderr);
|
|
357
|
+
const out = new Writable({
|
|
358
|
+
write(chunk, _encoding, done) {
|
|
359
|
+
protocolWrite(chunk, done);
|
|
360
|
+
},
|
|
361
|
+
});
|
|
362
|
+
await serveArtifactProvider(backend, process.stdin, out).done;
|
|
363
|
+
process.exit(0);
|
|
364
|
+
}
|