@parcha/agentrun-computer 0.1.0-beta.53 → 0.1.0-beta.54
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/README.md +147 -14
- package/dist/computerd-linux-amd64 +0 -0
- package/dist/computerd-linux-arm64 +0 -0
- package/dist/computerd.json +1 -1
- package/dist/conformance/cases/mount.js +3 -8
- package/dist/conformance/groundbox.d.ts +61 -0
- package/dist/conformance/groundbox.js +87 -0
- package/dist/conformance/sweep.js +1 -1
- package/dist/daytona.d.ts +7 -0
- package/dist/daytona.js +38 -38
- package/dist/descriptors/daytona.d.ts +4 -0
- package/dist/descriptors/daytona.js +2 -0
- package/dist/descriptors/groundbox.d.ts +34 -0
- package/dist/descriptors/groundbox.js +30 -0
- package/dist/descriptors/index.d.ts +33 -1
- package/dist/descriptors/index.js +4 -2
- package/dist/groundbox.d.ts +61 -0
- package/dist/groundbox.js +663 -0
- package/dist/host.d.ts +2 -2
- package/dist/hosted/provider.d.ts +5 -1
- package/dist/hosted/provider.js +73 -9
- package/dist/hosted/scripts.d.ts +7 -4
- package/dist/hosted/scripts.js +11 -6
- package/dist/index.d.ts +3 -3
- package/dist/index.js +4 -4
- package/dist/sync-folder.d.ts +14 -10
- package/dist/sync-folder.js +25 -7
- package/dist/tar.d.ts +0 -2
- package/dist/tar.js +1 -1
- package/package.json +8 -2
|
@@ -0,0 +1,663 @@
|
|
|
1
|
+
// The Groundbox host: sandboxes on Groundbox (https://groundbox.dev), each a Firecracker microVM, over its REST API
|
|
2
|
+
// (https://api.groundbox.dev/v1, a Bearer key) with fetch and Node's WebSocket (no SDK). The exec is a resumable
|
|
3
|
+
// command of Groundbox's command stream (GET /v1/sandboxes/{id}/exec/stream, a WebSocket of JSON messages), handed to
|
|
4
|
+
// framedExec: the command runs on in the sandbox when a connection ends, as every connection does within the hour, and
|
|
5
|
+
// a new socket reads on from the last output position, so no output is lost or read twice. Its stdin does not ride that
|
|
6
|
+
// socket, where input is delivered at most once and nothing says what arrived: the command reads a fifo, and each write
|
|
7
|
+
// is one answered call that writes the fifo (POST .../exec). A computer starts from our box image by default
|
|
8
|
+
// (prepareImage), where Groundbox runs a command as root; on Groundbox's own image or a template it runs as the image's
|
|
9
|
+
// user, runner, who has passwordless sudo, which the adapter's scripts use. A command's own kill is the user's who ran
|
|
10
|
+
// it, so kill is the shared pid kill as root. Labels are the sandbox's metadata, which the listing filters by. The
|
|
11
|
+
// lifetime is the janitor's, by the deadline label, and Groundbox's own timer (timeout_minutes) is set to the request's
|
|
12
|
+
// backstop. Kind desktop is the box image's Xvfb and xfwm4, started through the daemon as on E2B and boxd. The rest of
|
|
13
|
+
// the computer is the shared machine-host adapter's (./hosted/provider.ts). Every Groundbox fact used here is cited in
|
|
14
|
+
// the README's Groundbox section.
|
|
15
|
+
import { randomBytes } from "node:crypto";
|
|
16
|
+
import { boxImageRef } from "./box-image.js";
|
|
17
|
+
import { GROUNDBOX, GROUNDBOX_OWN_IMAGE } from "./descriptors/groundbox.js";
|
|
18
|
+
import { DEADLINE_LABEL, show } from "./drift.js";
|
|
19
|
+
import { HostError } from "./host.js";
|
|
20
|
+
import { framedExec } from "./hosted/framed-exec.js";
|
|
21
|
+
import { boundOf, orThrow, pause, seconds } from "./hosted/process.js";
|
|
22
|
+
import { HostedProvider } from "./hosted/provider.js";
|
|
23
|
+
import { allPages, jsonOf, rest } from "./hosted/rest.js";
|
|
24
|
+
import { PID_KILL } from "./hosted/scripts.js";
|
|
25
|
+
import { dateOf, isWhole } from "./hosted/values.js";
|
|
26
|
+
import { ok } from "./result.js";
|
|
27
|
+
export async function create(options) {
|
|
28
|
+
return new GroundboxProvider(options);
|
|
29
|
+
}
|
|
30
|
+
/** The conformance CLI's module for Groundbox: its live switch, the run's 30-minute cap and its image. */
|
|
31
|
+
export const conformance = () => import("./conformance/groundbox.js");
|
|
32
|
+
const DEFAULT_API_URL = "https://api.groundbox.dev/v1";
|
|
33
|
+
/** A loopback host as URL writes it (an IPv4 address in its four numbers, IPv6 in brackets): the one place http may go. */
|
|
34
|
+
const LOOPBACK = /^(127(\.\d{1,3}){3}|\[::1\]|localhost)$/;
|
|
35
|
+
/** The longest a resumable command may run, in seconds: 30 days (EXEC_STREAM_MAX_TIMEOUT_S in Groundbox's contracts). The sandbox's own timer ends it first. */
|
|
36
|
+
const EXEC_STREAM_MAX_S = 30 * 24 * 3_600;
|
|
37
|
+
/** The most timeout_minutes takes: 30 days (SANDBOX_MAX_TIMEOUT_MINUTES). */
|
|
38
|
+
const MAX_TIMEOUT_MINUTES = 30 * 24 * 60;
|
|
39
|
+
/**
|
|
40
|
+
* The longest any plan keeps a computer: Groundbox's 30 days, less the adapter's backstop margin of 5 minutes and a
|
|
41
|
+
* minute of rounding, so the backstop create asks Groundbox's timer for is one it takes.
|
|
42
|
+
*/
|
|
43
|
+
const MAX_LIFETIME_MS = (MAX_TIMEOUT_MINUTES - 6) * 60_000;
|
|
44
|
+
/** The cap a user gets unless the provider is given another: a day. */
|
|
45
|
+
const DEFAULT_LIFETIME_MS = 24 * 60 * 60_000;
|
|
46
|
+
/** A size's bounds (SandboxSpec): whole CPUs, and whole GB of memory up to 4 a CPU; with no CPUs named, Groundbox gives 2. */
|
|
47
|
+
const MAX_CPUS = 16;
|
|
48
|
+
const MAX_MEMORY_GB_PER_CPU = 4;
|
|
49
|
+
const DEFAULT_CPUS = 2;
|
|
50
|
+
const MAX_DISK_GB = 100;
|
|
51
|
+
/** A metadata name is 1 to 64 characters and its value at most 512 (Metadata). */
|
|
52
|
+
const LABEL_NAME_MAX = 64;
|
|
53
|
+
const LABEL_VALUE_MAX = 512;
|
|
54
|
+
/** A template's id, or its name, with a version or without (TemplateRef). */
|
|
55
|
+
const TEMPLATE = /^(tpl_[A-Za-z0-9]{8,40}|[a-z0-9][a-z0-9-]{0,62})(:[1-9]\d{0,5})?$/;
|
|
56
|
+
/**
|
|
57
|
+
* Any other image is a public image reference that `docker pull` takes (ghcr.io/org/app:tag, name@sha256:...), sent as
|
|
58
|
+
* `image`: one word of printable ASCII. A bare Docker Hub name such as "alpine" reads as a template; name it in full
|
|
59
|
+
* (docker.io/library/alpine) or with a tag that is not a number (alpine:3.20).
|
|
60
|
+
*/
|
|
61
|
+
const IMAGE_REF = /^[\x21-\x7e]{1,512}$/;
|
|
62
|
+
/** What a spec's image is: Groundbox's own (no field sent), a template of the key's team, or a public image. */
|
|
63
|
+
const imageField = (image) => (image === GROUNDBOX_OWN_IMAGE ? {} : TEMPLATE.test(image) ? { template: image } : { image });
|
|
64
|
+
/** The user of Groundbox's own image, which Groundbox runs a command as there (uid 1001, with passwordless sudo): init refuses to start beside its processes. */
|
|
65
|
+
const IMAGE_UID = 1001;
|
|
66
|
+
/** The listing's page, the most it takes, and the most pages read. */
|
|
67
|
+
const PAGE = 200;
|
|
68
|
+
const MAX_PAGES = 100;
|
|
69
|
+
/**
|
|
70
|
+
* Groundbox's statuses (SANDBOX_STATUSES) as the adapter's. One shut down with its disk kept is there and not running.
|
|
71
|
+
* stopped and failed are records Groundbox keeps of sandboxes that will not come back, so none; `live=true` lists
|
|
72
|
+
* neither.
|
|
73
|
+
*/
|
|
74
|
+
const STATES = {
|
|
75
|
+
...{ queued: "starting", starting: "starting", resuming: "starting", running: "running" },
|
|
76
|
+
...{ pausing: "stopped", paused: "stopped", shutting_down: "stopped", shut_down: "stopped" },
|
|
77
|
+
...{ stopping: "gone", stopped: undefined, failed: undefined },
|
|
78
|
+
};
|
|
79
|
+
/** Groundbox's error codes (ERROR_CODES) as the adapter's; one not here is read by its status (httpCode). */
|
|
80
|
+
const CODES = {
|
|
81
|
+
...{ unauthorized: "denied", forbidden: "denied", key_pending_claim: "denied", missing_scope: "denied", team_held: "denied", team_suspended: "denied", paid_plan_required: "denied" },
|
|
82
|
+
...{ insufficient_balance: "limit", spend_cap_reached: "limit", concurrency_limit: "limit", rate_limited: "limit" },
|
|
83
|
+
...{ not_found: "not_found", timeout: "timeout", bad_request: "invalid", conflict: "refused", idempotency_key_reused: "refused" },
|
|
84
|
+
...{ no_capacity: "vendor", not_available: "vendor", internal: "vendor" },
|
|
85
|
+
};
|
|
86
|
+
/**
|
|
87
|
+
* Where each command's directory is made: in /tmp, under a name of the host's own that no one knows before the command
|
|
88
|
+
* starts, so its writes and its kill find it. The directory is the command's user's alone (0700) and holds its stdin
|
|
89
|
+
* fifo (`in`) and the record of its pid (`pid`): /tmp is anyone's, and once a command ended a fifo or a record left
|
|
90
|
+
* there by name could be anyone's too, so a write (which may carry a disk's token) or a kill would go where they say.
|
|
91
|
+
*/
|
|
92
|
+
const DIR_PREFIX = "/tmp/.agentrun-exec-";
|
|
93
|
+
/**
|
|
94
|
+
* The sh every command starts under ($1 its directory, then the argv). It makes the directory with mode 0700, as
|
|
95
|
+
* mktemp -d does, and a path already there is never its own: the command does not start (exit 126). In it, the fifo
|
|
96
|
+
* and the record of its own pid and start time (as PID_WRAPPER's line, for the kill; written whole and then renamed,
|
|
97
|
+
* so the kill never reads half of it). It runs the argv with the fifo as its stdin, opened to read and write, so the
|
|
98
|
+
* fifo never reads end of file between two writers; then it removes the directory and exits as the argv did.
|
|
99
|
+
*/
|
|
100
|
+
const START_SCRIPT = [
|
|
101
|
+
"d=$1; shift",
|
|
102
|
+
'mkdir -m 700 "$d" 2>/dev/null || { echo "agentrun: $d is already there, so it is not one this command made: the command did not start" >&2; exit 126; }',
|
|
103
|
+
'mkfifo -m 600 "$d/in" || exit 126',
|
|
104
|
+
'echo "$$ $(s=$(cat /proc/$$/stat 2>/dev/null) && set -- ${s##*") "} && echo "${20}")" >"$d/pid.new" && mv -f "$d/pid.new" "$d/pid"',
|
|
105
|
+
'"$@" 0<>"$d/in"; c=$?',
|
|
106
|
+
'rm -rf "$d"; exit $c',
|
|
107
|
+
].join("\n");
|
|
108
|
+
/**
|
|
109
|
+
* The check a write and a kill make of a command's directory ($d) before they use what is in it, from inside it (cd,
|
|
110
|
+
* so the path can't be swapped after the check): the directory itself and not a link to another, owned by this user
|
|
111
|
+
* (the command's: Groundbox runs every command of a sandbox as one user) with mode 0700. Else exit 4, in words.
|
|
112
|
+
*/
|
|
113
|
+
const OWN_DIR = `cd -P "$d" 2>/dev/null && [ "$(pwd -P)" = "$(cd -P "\${d%/*}" && pwd -P)/\${d##*/}" ] && [ "$(stat -c %u:%a .)" = "$(id -u):700" ] || { echo "$d is not the command's own directory" >&2; exit 4; }`;
|
|
114
|
+
/** The check of one file in it ($1 its name): not a link, and this user's. */
|
|
115
|
+
const ownFile = (name) => `[ ! -L ${name} ] && [ "$(stat -c %u ${name})" = "$(id -u)" ] || { echo "$d/${name} is not the command's own" >&2; exit 4; }`;
|
|
116
|
+
/**
|
|
117
|
+
* One write ($1 the command's directory): its stdin into the fifo there. A command Groundbox has just started may not
|
|
118
|
+
* have made its fifo yet, so the write waits up to 5 s for it; with none by then the command has ended (its sh removed
|
|
119
|
+
* it): exit 3. A fifo that went between the check and the write leaves a file of the write's own, removed: exit 3.
|
|
120
|
+
*/
|
|
121
|
+
const WRITE_SCRIPT = [
|
|
122
|
+
'd=$1; i=0; until [ -p "$d/in" ]; do [ "$i" -lt 50 ] || exit 3; i=$((i + 1)); sleep 0.1; done',
|
|
123
|
+
OWN_DIR,
|
|
124
|
+
ownFile("in"),
|
|
125
|
+
"cat >in",
|
|
126
|
+
'[ -p in ] || { rm -f in; cd / && rmdir "$d" 2>/dev/null; exit 3; }',
|
|
127
|
+
].join("\n");
|
|
128
|
+
/**
|
|
129
|
+
* The kill ($1 the command's directory, $2 PID_KILL): the shared pid kill of the recorded pid, as root, since a command
|
|
130
|
+
* that became root through sudo is past its starter's signals, and Groundbox's own kill of a command is that user's. A
|
|
131
|
+
* command Groundbox has just started may not have recorded its pid yet, so the kill waits up to 5 s for the record, as
|
|
132
|
+
* a write waits for the fifo; with none by then the command has ended (its sh removed it). Then the directory is
|
|
133
|
+
* removed, as the killed sh could not.
|
|
134
|
+
*/
|
|
135
|
+
const KILL_SCRIPT = [
|
|
136
|
+
'd=$1; i=0; until [ -s "$d/pid" ]; do [ "$i" -lt 50 ] || exit 0; i=$((i + 1)); sleep 0.1; done',
|
|
137
|
+
OWN_DIR,
|
|
138
|
+
ownFile("pid"),
|
|
139
|
+
"read -r pid start 2>/dev/null <pid || exit 0",
|
|
140
|
+
'p=; [ "$(id -u)" = 0 ] || p="sudo -n"',
|
|
141
|
+
'$p sh -c "$2" sh "$pid" "$start"',
|
|
142
|
+
'cd / && rm -rf "$d"',
|
|
143
|
+
].join("\n");
|
|
144
|
+
/** One write's bytes: POST .../exec takes 512 KiB of stdin (EXEC_MAX_STDIN_BYTES). */
|
|
145
|
+
const WRITE_BYTES = 256 * 1024;
|
|
146
|
+
/** A write or a kill is one short command: its own bound in the sandbox, and the call's past it. */
|
|
147
|
+
const STEP_S = 60;
|
|
148
|
+
const STEP_MS = 75_000;
|
|
149
|
+
/** A resumable stream says `heartbeat` every 20 s (EXEC_STREAM_HEARTBEAT_S): one silent for this long is dead, and is opened again. */
|
|
150
|
+
const SILENCE_MS = 70_000;
|
|
151
|
+
/**
|
|
152
|
+
* The pauses between tries to read on, doubling from the first to the last; and how long with no socket Groundbox
|
|
153
|
+
* speaks on before the stream fails.
|
|
154
|
+
*/
|
|
155
|
+
const RESUME_MIN_MS = 500;
|
|
156
|
+
const RESUME_MAX_MS = 10_000;
|
|
157
|
+
const RESUME_GIVE_UP_MS = 5 * 60_000;
|
|
158
|
+
/** The longest one try to read on waits for Groundbox to speak on its socket: past one heartbeat. */
|
|
159
|
+
const ATTACH_MS = 30_000;
|
|
160
|
+
/** The close code of a socket this host drops to open another (not 1000, which ends the command). */
|
|
161
|
+
const DROP = 4000;
|
|
162
|
+
/** The close code that ends the command: a start that failed or timed out leaves nothing running unseen. */
|
|
163
|
+
const END = 1000;
|
|
164
|
+
/**
|
|
165
|
+
* The output read and not yet taken by framedExec that pauses reading: the socket is let go of, and a new one attaches
|
|
166
|
+
* from the position read to once the queue is down to QUEUE_LOW, so a reader that stops never makes the host hold more.
|
|
167
|
+
* Groundbox keeps the command's output meanwhile; what it no longer keeps comes back as `skipped`, which fails the stream.
|
|
168
|
+
*/
|
|
169
|
+
const QUEUE_HIGH = 8 * 1024 * 1024;
|
|
170
|
+
const QUEUE_LOW = 2 * 1024 * 1024;
|
|
171
|
+
/** The bytes a chunk of base64 holds. */
|
|
172
|
+
const bytesOf = (base64) => Math.floor((base64.length * 3) / 4);
|
|
173
|
+
/** A sandbox as the adapter reads a machine; none for a record Groundbox keeps of one that has ended. */
|
|
174
|
+
function machineOf(sandbox) {
|
|
175
|
+
const labels = { ...(sandbox.metadata ?? {}) };
|
|
176
|
+
// A status this host does not know is a machine that is there and not running: the janitor still finds and ends it.
|
|
177
|
+
if (!(sandbox.status in STATES))
|
|
178
|
+
return { id: sandbox.id, labels, state: "stopped", why: `Groundbox reads its status as ${sandbox.status}` };
|
|
179
|
+
const state = STATES[sandbox.status];
|
|
180
|
+
if (state === undefined)
|
|
181
|
+
return undefined;
|
|
182
|
+
const created = dateOf(sandbox.created_at);
|
|
183
|
+
return { id: sandbox.id, labels, state, ...(created ? { createdAt: created } : {}) };
|
|
184
|
+
}
|
|
185
|
+
/** Why Groundbox's metadata can't hold these labels, in words; undefined when it can. */
|
|
186
|
+
function labelProblem(labels) {
|
|
187
|
+
const names = Object.keys(labels).filter((name) => name.length < 1 || name.length > LABEL_NAME_MAX);
|
|
188
|
+
if (names.length > 0)
|
|
189
|
+
return `Groundbox takes label names of 1 to ${LABEL_NAME_MAX} characters: ${names.map((name) => show(name)).join(", ")}`;
|
|
190
|
+
const long = Object.entries(labels).filter(([, value]) => typeof value === "string" && value.length > LABEL_VALUE_MAX);
|
|
191
|
+
if (long.length > 0)
|
|
192
|
+
return `Groundbox takes label values of at most ${LABEL_VALUE_MAX} characters: ${long.map(([name, value]) => `${name} holds ${value.length}`).join(", ")}`;
|
|
193
|
+
return undefined;
|
|
194
|
+
}
|
|
195
|
+
/** Groundbox's sandboxes as a MachineHost (./host.ts). */
|
|
196
|
+
class GroundboxHost {
|
|
197
|
+
descriptor = GROUNDBOX;
|
|
198
|
+
facts = {
|
|
199
|
+
daemon: "child",
|
|
200
|
+
isolation: "microvm",
|
|
201
|
+
lifetime: "janitor",
|
|
202
|
+
maxLifetimeMs: MAX_LIFETIME_MS,
|
|
203
|
+
arch: "amd64",
|
|
204
|
+
// Groundbox's agent in the guest listens on a unix socket that is root's, reached over vsock: nothing on TCP.
|
|
205
|
+
vendorAgentPorts: [],
|
|
206
|
+
// A desktop runs the box image's xfwm4 once its X server answers.
|
|
207
|
+
windowManager: true,
|
|
208
|
+
};
|
|
209
|
+
#apiKey;
|
|
210
|
+
#apiUrl;
|
|
211
|
+
#fetch;
|
|
212
|
+
#webSocket;
|
|
213
|
+
#diskGb;
|
|
214
|
+
#kind;
|
|
215
|
+
#bounds;
|
|
216
|
+
#api;
|
|
217
|
+
constructor(options) {
|
|
218
|
+
this.#apiKey = options.apiKey;
|
|
219
|
+
this.#apiUrl = options.apiUrl.replace(/\/+$/, "");
|
|
220
|
+
this.#fetch = options.fetch;
|
|
221
|
+
this.#webSocket = options.webSocket;
|
|
222
|
+
this.#diskGb = options.diskGb;
|
|
223
|
+
this.#kind = options.kind;
|
|
224
|
+
this.#bounds = { silenceMs: SILENCE_MS, queueHighBytes: QUEUE_HIGH, queueLowBytes: QUEUE_LOW, resumeGiveUpMs: RESUME_GIVE_UP_MS, ...options.streamBounds };
|
|
225
|
+
this.#api = this.#client();
|
|
226
|
+
}
|
|
227
|
+
/** The API's client, with headers of one call's own beside the key (a create's Idempotency-Key). */
|
|
228
|
+
#client(headers = {}) {
|
|
229
|
+
return rest({
|
|
230
|
+
base: this.#apiUrl,
|
|
231
|
+
headers: () => ({ Authorization: `Bearer ${this.#apiKey}`, Accept: "application/json", ...headers }),
|
|
232
|
+
vendor: GROUNDBOX.id,
|
|
233
|
+
...(this.#fetch ? { fetch: this.#fetch } : {}),
|
|
234
|
+
timeoutMs: 30_000,
|
|
235
|
+
retry: { attempts: 3, baseMs: 500 },
|
|
236
|
+
// Every refusal's body is { error: { code, message } } (ErrorResponse): the code is read as the adapter's, the
|
|
237
|
+
// message is the words.
|
|
238
|
+
explain: ({ status, bytes, what }) => {
|
|
239
|
+
const error = jsonOf(bytes)?.error;
|
|
240
|
+
const code = typeof error?.code === "string" ? CODES[error.code] : undefined;
|
|
241
|
+
const words = typeof error?.message === "string" ? error.message : "";
|
|
242
|
+
return { ...(code ? { code } : {}), message: `${what} answered ${status}${typeof error?.code === "string" ? ` ${error.code}` : ""}${words ? `: ${words}` : ""}` };
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
async #call(method, path, json, ctx, extra = {}, api = this.#api) {
|
|
247
|
+
const answer = orThrow(await api.call(method, api.url(path), { ...(json === undefined ? {} : { json }), timeoutMs: ctx.timeoutMs, ...extra }, ctx.signal));
|
|
248
|
+
return jsonOf(answer.bytes);
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* A spec's image is "default" (Groundbox's own), a template of the key's team, or a public image; its size is whole CPUs and whole GiB of memory, as
|
|
252
|
+
* Groundbox takes them (a size outside its bounds is refused there, never rounded); a label is one its metadata holds.
|
|
253
|
+
*/
|
|
254
|
+
check(spec) {
|
|
255
|
+
const refusals = [];
|
|
256
|
+
const { image, cpus, memoryMb, labels } = spec;
|
|
257
|
+
if (image !== undefined && !(typeof image === "string" && IMAGE_REF.test(image))) {
|
|
258
|
+
refusals.push({ field: "image", message: `an image is "${GROUNDBOX_OWN_IMAGE}" (the team's default template, else Groundbox's own Ubuntu 24.04), a Groundbox template (its id tpl_..., its name, or name:version), or a public image reference such as ghcr.io/org/app:tag` });
|
|
259
|
+
}
|
|
260
|
+
else if (image === GROUNDBOX_OWN_IMAGE && this.#kind === "desktop") {
|
|
261
|
+
// Groundbox's own image has Xvfb but not xfwm4, the window manager every desktop here runs.
|
|
262
|
+
refusals.push({ field: "image", message: `a Groundbox desktop starts from an image with Xvfb and xfwm4, which Groundbox's own image lacks (xfwm4): name the box image, ${boxImageRef()}, which prepareImage() answers, or an image of your own that has both` });
|
|
263
|
+
}
|
|
264
|
+
if (cpus !== undefined && !(isWhole(cpus) && cpus >= 1 && cpus <= MAX_CPUS))
|
|
265
|
+
refusals.push({ field: "cpus", message: `a Groundbox computer has a whole number of CPUs, 1 to ${MAX_CPUS}` });
|
|
266
|
+
if (memoryMb !== undefined) {
|
|
267
|
+
const most = (isWhole(cpus) && cpus >= 1 && cpus <= MAX_CPUS ? cpus : DEFAULT_CPUS) * MAX_MEMORY_GB_PER_CPU;
|
|
268
|
+
if (!(isWhole(memoryMb) && memoryMb >= 1024 && memoryMb % 1024 === 0))
|
|
269
|
+
refusals.push({ field: "memoryMb", message: "a Groundbox computer's memory is a whole number of GiB, such as 4096" });
|
|
270
|
+
else if (memoryMb / 1024 > most)
|
|
271
|
+
refusals.push({ field: "memoryMb", message: `a Groundbox computer has at most ${MAX_MEMORY_GB_PER_CPU} GiB of memory a CPU (${most * 1024} with ${most / MAX_MEMORY_GB_PER_CPU} CPUs): name more cpus, up to ${MAX_CPUS}` });
|
|
272
|
+
}
|
|
273
|
+
const problem = labels !== null && typeof labels === "object" && !Array.isArray(labels) ? labelProblem(labels) : undefined;
|
|
274
|
+
if (problem)
|
|
275
|
+
refusals.push({ field: "labels", message: problem });
|
|
276
|
+
return refusals;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* POST /v1/sandboxes from the spec's image (a template, a public image, or neither for Groundbox's own), with the labels
|
|
280
|
+
* as its metadata, the spec's size when it names one (else Groundbox's own, or the
|
|
281
|
+
* template's), and timeout_minutes to the request's backstop: Groundbox's timer is the only one it has, and it ends a
|
|
282
|
+
* sandbox whose server is gone. The call carries an Idempotency-Key of this one request, so sent again on no answer
|
|
283
|
+
* it never starts a second sandbox. Groundbox answers once the sandbox runs, or with it still starting, which the
|
|
284
|
+
* adapter then waits out; one it could not start is refused here in its words.
|
|
285
|
+
*/
|
|
286
|
+
async create(req, ctx) {
|
|
287
|
+
// The adapter's own labels are held to Groundbox's bounds here: a network list or an image name may be long.
|
|
288
|
+
const problem = labelProblem(req.labels);
|
|
289
|
+
if (problem)
|
|
290
|
+
throw new HostError("limit", `${problem}; give a shorter network list or labels`);
|
|
291
|
+
const minutes = Math.ceil((Date.parse(req.backstopAt) - Date.now()) / 60_000);
|
|
292
|
+
const body = {
|
|
293
|
+
...imageField(req.image),
|
|
294
|
+
...(req.cpus === undefined ? {} : { cpus: req.cpus }),
|
|
295
|
+
...(req.memoryMb === undefined ? {} : { memory_gb: req.memoryMb / 1024 }),
|
|
296
|
+
...(this.#diskGb === undefined ? {} : { disk_gb: this.#diskGb }),
|
|
297
|
+
timeout_minutes: Math.min(MAX_TIMEOUT_MINUTES, Math.max(1, minutes)),
|
|
298
|
+
metadata: req.labels,
|
|
299
|
+
};
|
|
300
|
+
const made = await this.#call("POST", "/sandboxes", body, ctx, { retry: true }, this.#client({ "Idempotency-Key": `agentrun-${req.name}-${req.backstopAt}` }));
|
|
301
|
+
if (typeof made?.id !== "string")
|
|
302
|
+
throw new Error("POST /sandboxes: no sandbox id in the answer");
|
|
303
|
+
if (made.status === "failed" || made.status === "stopped") {
|
|
304
|
+
throw new HostError("vendor", `Groundbox did not start ${made.id}: its status is ${made.status}${made.stop_reason ? ` (${made.stop_reason})` : ""}`);
|
|
305
|
+
}
|
|
306
|
+
return { id: made.id };
|
|
307
|
+
}
|
|
308
|
+
/** GET /v1/sandboxes/{id}; a 404 is not_found, which the adapter reads as none, and an ended sandbox's record is none. */
|
|
309
|
+
async get(id, ctx) {
|
|
310
|
+
return machineOf(await this.#call("GET", `/sandboxes/${encodeURIComponent(id)}`, undefined, ctx, { retry: true }));
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Every sandbox of the key's team that is there and carries these labels: one listing, `live=true` (every status but
|
|
314
|
+
* stopped and failed) with a `metadata[name]=value` for each label, every page, within ctx.timeoutMs in all.
|
|
315
|
+
*/
|
|
316
|
+
async list(labels, ctx) {
|
|
317
|
+
const until = Date.now() + ctx.timeoutMs;
|
|
318
|
+
const filter = Object.entries(labels).map(([name, value]) => `&${encodeURIComponent(`metadata[${name}]`)}=${encodeURIComponent(value)}`);
|
|
319
|
+
const listed = orThrow(await allPages(async (cursor) => {
|
|
320
|
+
const query = `live=true&limit=${PAGE}${filter.join("")}${cursor === undefined ? "" : `&cursor=${encodeURIComponent(cursor)}`}`;
|
|
321
|
+
const page = await this.#api.json("GET", this.#api.url(`/sandboxes?${query}`), { retry: true, timeoutMs: Math.max(1, until - Date.now()) }, ctx.signal);
|
|
322
|
+
if (!page.ok)
|
|
323
|
+
return page;
|
|
324
|
+
const { data, next_cursor: next } = (page.value ?? {});
|
|
325
|
+
if (!Array.isArray(data))
|
|
326
|
+
return { ok: false, error: { code: "vendor", vendor: GROUNDBOX.id, message: "GET /sandboxes: a page that is not a list of sandboxes" } };
|
|
327
|
+
return { ok: true, value: { items: data, ...(typeof next === "string" ? { next } : {}) } };
|
|
328
|
+
}, MAX_PAGES, { vendor: GROUNDBOX.id, what: "the listing of live sandboxes" }));
|
|
329
|
+
return listed.map((sandbox) => (typeof sandbox?.id === "string" ? machineOf(sandbox) : undefined)).filter((machine) => machine !== undefined);
|
|
330
|
+
}
|
|
331
|
+
/** DELETE /v1/sandboxes/{id}, which answers the sandbox, ended or still stopping; one already ended is fine. */
|
|
332
|
+
async delete(id, ctx) {
|
|
333
|
+
await this.#call("DELETE", `/sandboxes/${encodeURIComponent(id)}`, undefined, ctx, { retry: true });
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* argv as one resumable command of the stream, through framedExec, under START_SCRIPT: as the sandbox's command user,
|
|
337
|
+
* in its own process group, with the longest timeout Groundbox takes (the sandbox's own timer ends it first), its
|
|
338
|
+
* output as base64, so every byte comes as it was and a position in it is exact. A write is one call per WRITE_BYTES
|
|
339
|
+
* that writes the command's fifo and answers once it has; there is no end of stdin (a fifo held open has none), which
|
|
340
|
+
* nothing the adapter runs waits for. kill is KILL_SCRIPT's. A write or a kill whose directory, fifo or pid record is
|
|
341
|
+
* not the command's own is refused.
|
|
342
|
+
*/
|
|
343
|
+
exec(id, argv, ctx) {
|
|
344
|
+
return framedExec({
|
|
345
|
+
start: (argv, ctx) => this.#start(id, argv, ctx),
|
|
346
|
+
events: (command) => this.#events(command),
|
|
347
|
+
write: async (command, text) => {
|
|
348
|
+
const bytes = Buffer.from(text, "utf8");
|
|
349
|
+
for (let at = 0; at < bytes.length; at += WRITE_BYTES) {
|
|
350
|
+
const code = await this.#step(command, [WRITE_SCRIPT, "sh", command.dir], bytes.subarray(at, at + WRITE_BYTES));
|
|
351
|
+
if (code === 3)
|
|
352
|
+
throw new Error("the process has ended");
|
|
353
|
+
// Its words never hold what was written: it may be a disk's token.
|
|
354
|
+
if (code === 4)
|
|
355
|
+
throw new Error(`the command's stdin at ${command.dir} is not the command's own: the write was refused`);
|
|
356
|
+
if (code !== 0)
|
|
357
|
+
throw new Error(`writing to the command failed (exit ${code})`);
|
|
358
|
+
}
|
|
359
|
+
},
|
|
360
|
+
kill: async (command) => {
|
|
361
|
+
const code = await this.#step(command, [KILL_SCRIPT, "sh", command.dir, PID_KILL]);
|
|
362
|
+
if (code === 4)
|
|
363
|
+
throw new Error(`the command's pid record at ${command.dir} is not the command's own: the kill was refused`);
|
|
364
|
+
},
|
|
365
|
+
}, argv, ctx);
|
|
366
|
+
}
|
|
367
|
+
/** One short command beside a running one (POST .../exec), its stdin given whole: its exit code, -1 past its bound. Never sent twice. */
|
|
368
|
+
async #step(command, script, stdin) {
|
|
369
|
+
const body = { args: ["sh", "-c", ...script], timeout_s: STEP_S, ...(stdin === undefined ? {} : { stdin_base64: Buffer.from(stdin).toString("base64") }) };
|
|
370
|
+
const ran = await this.#call("POST", `/sandboxes/${encodeURIComponent(command.sandbox)}/exec`, body, { timeoutMs: STEP_MS });
|
|
371
|
+
return typeof ran?.exit_code === "number" && ran.timed_out !== true ? ran.exit_code : -1;
|
|
372
|
+
}
|
|
373
|
+
/** Starts the command on a new socket and answers once Groundbox says it has started, within the call's bound. */
|
|
374
|
+
async #start(id, argv, ctx) {
|
|
375
|
+
const command = { sandbox: id, dir: `${DIR_PREFIX}${randomBytes(8).toString("hex")}`, seq: 0, events: [], queued: 0, paused: false, resuming: false, ended: false, wake: () => { }, quiet: () => { } };
|
|
376
|
+
const first = { type: "start", args: ["sh", "-c", START_SCRIPT, "sh", command.dir, ...argv], resumable: true, encoding: "base64", timeout_s: EXEC_STREAM_MAX_S };
|
|
377
|
+
try {
|
|
378
|
+
await this.#connect(command, first, ctx);
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
this.#end(command);
|
|
382
|
+
throw error;
|
|
383
|
+
}
|
|
384
|
+
return command;
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* The stream is over: nothing more is read, its socket's watchdog stops, and the socket is closed (1000, which also
|
|
388
|
+
* ends a command still running).
|
|
389
|
+
*/
|
|
390
|
+
#end(command, failure) {
|
|
391
|
+
if (!command.ended)
|
|
392
|
+
command.failure ??= failure;
|
|
393
|
+
command.ended = true;
|
|
394
|
+
command.quiet();
|
|
395
|
+
command.socket?.close(END);
|
|
396
|
+
command.wake();
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* One socket of the command's stream: `first` is its start, or an attach from the position read to. It answers once
|
|
400
|
+
* the socket is the command's (a start: Groundbox said `started`; an attach: Groundbox said anything on it, so a peer
|
|
401
|
+
* that takes an attach and says nothing is no read-on), within the bound. From then its messages are the command's
|
|
402
|
+
* events, and a close that is no end of the command opens another (#resume). A start that failed or timed out closes
|
|
403
|
+
* with 1000, which ends the command should Groundbox have started it. A socket that does not open says what the
|
|
404
|
+
* sandbox reads as: a refused upgrade carries its status and body where a WebSocket client can't read them.
|
|
405
|
+
*/
|
|
406
|
+
async #connect(command, first, ctx) {
|
|
407
|
+
const url = `${this.#apiUrl.replace(/^http/, "ws")}/sandboxes/${encodeURIComponent(command.sandbox)}/exec/stream`;
|
|
408
|
+
let socket;
|
|
409
|
+
try {
|
|
410
|
+
socket = this.#webSocket(url, { headers: { Authorization: `Bearer ${this.#apiKey}` } });
|
|
411
|
+
}
|
|
412
|
+
catch (error) {
|
|
413
|
+
throw new Error(`opening the command stream: ${error.message}`);
|
|
414
|
+
}
|
|
415
|
+
command.socket = socket;
|
|
416
|
+
let ready;
|
|
417
|
+
const readied = new Promise((done) => (ready = done));
|
|
418
|
+
let silence;
|
|
419
|
+
command.quiet = () => clearTimeout(silence);
|
|
420
|
+
/** This socket was given up on: nothing it says is read any more, and its close opens no other. */
|
|
421
|
+
let abandoned = false;
|
|
422
|
+
/**
|
|
423
|
+
* Lets this socket go while the command runs on: its later messages and its close are ignored, since a close may
|
|
424
|
+
* never come (WebSocket's close waits for a peer that may be gone). Silent: another socket attaches at once. Full:
|
|
425
|
+
* none until the reader has taken enough (#events).
|
|
426
|
+
*/
|
|
427
|
+
const letGo = (why) => {
|
|
428
|
+
if (abandoned)
|
|
429
|
+
return;
|
|
430
|
+
abandoned = true;
|
|
431
|
+
clearTimeout(silence);
|
|
432
|
+
if (command.socket === socket)
|
|
433
|
+
command.socket = undefined;
|
|
434
|
+
try {
|
|
435
|
+
socket.close(DROP);
|
|
436
|
+
}
|
|
437
|
+
catch {
|
|
438
|
+
// Already closing: nothing more to do with it.
|
|
439
|
+
}
|
|
440
|
+
if (why === "full")
|
|
441
|
+
command.paused = true;
|
|
442
|
+
else {
|
|
443
|
+
// An attach Groundbox never spoke on fails its try (#resume's); a socket already read on is past this.
|
|
444
|
+
ready(new Error(`the command stream said nothing for ${seconds(this.#bounds.silenceMs)} after its ${first.type}`));
|
|
445
|
+
void this.#resume(command);
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
const heard = () => {
|
|
449
|
+
clearTimeout(silence);
|
|
450
|
+
// A resumable stream is never silent for long (its heartbeat): one that is has died, with or without a close.
|
|
451
|
+
if (command.execId !== undefined && !command.ended)
|
|
452
|
+
(silence = setTimeout(() => letGo("silent"), this.#bounds.silenceMs)).unref?.();
|
|
453
|
+
};
|
|
454
|
+
socket.addEventListener("open", () => {
|
|
455
|
+
try {
|
|
456
|
+
socket.send(JSON.stringify(first));
|
|
457
|
+
heard();
|
|
458
|
+
}
|
|
459
|
+
catch (error) {
|
|
460
|
+
ready(new Error(`the command stream took no ${first.type}: ${error.message}`));
|
|
461
|
+
}
|
|
462
|
+
});
|
|
463
|
+
socket.addEventListener("message", ({ data }) => {
|
|
464
|
+
if (abandoned || socket !== command.socket || command.ended || typeof data !== "string")
|
|
465
|
+
return;
|
|
466
|
+
let message;
|
|
467
|
+
try {
|
|
468
|
+
message = JSON.parse(data);
|
|
469
|
+
}
|
|
470
|
+
catch {
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
heard();
|
|
474
|
+
// Groundbox speaks on the attach (output, a heartbeat, the exit): the command is read on here.
|
|
475
|
+
if (first.type === "attach")
|
|
476
|
+
ready();
|
|
477
|
+
if (message.type === "started" && typeof message.exec_id === "string") {
|
|
478
|
+
command.execId = message.exec_id;
|
|
479
|
+
// The watchdog arms only once there is a command to attach to: from here, a socket silent after `started` alone is let go too.
|
|
480
|
+
heard();
|
|
481
|
+
ready();
|
|
482
|
+
}
|
|
483
|
+
else if ((message.type === "stdout" || message.type === "stderr") && typeof message.data === "string") {
|
|
484
|
+
command.events.push({ stream: message.type, base64: message.data });
|
|
485
|
+
command.queued += bytesOf(message.data);
|
|
486
|
+
if (typeof message.seq === "number")
|
|
487
|
+
command.seq = message.seq;
|
|
488
|
+
// Everything up to seq is queued: a socket opened later attaches from there, and nothing is lost or read twice.
|
|
489
|
+
if (command.queued > this.#bounds.queueHighBytes)
|
|
490
|
+
letGo("full");
|
|
491
|
+
}
|
|
492
|
+
else if (message.type === "skipped") {
|
|
493
|
+
this.#end(command, new Error(`Groundbox no longer keeps ${String(message.bytes)} bytes of the command's output, lost while its stream was down`));
|
|
494
|
+
}
|
|
495
|
+
else if (message.type === "exit" && typeof message.exit_code === "number") {
|
|
496
|
+
command.events.push({ exit: message.exit_code });
|
|
497
|
+
this.#end(command);
|
|
498
|
+
}
|
|
499
|
+
else if (message.type === "error") {
|
|
500
|
+
const failure = new HostError((typeof message.code === "string" ? CODES[message.code] : undefined) ?? "vendor", `Groundbox ended the command: ${typeof message.message === "string" ? message.message : "no reason given"}`);
|
|
501
|
+
ready(failure);
|
|
502
|
+
this.#end(command, failure);
|
|
503
|
+
}
|
|
504
|
+
command.wake();
|
|
505
|
+
});
|
|
506
|
+
socket.addEventListener("error", (event) => ready(new Error(`the command stream failed${event.message ? `: ${event.message}` : ""}`)));
|
|
507
|
+
socket.addEventListener("close", ({ code }) => {
|
|
508
|
+
clearTimeout(silence);
|
|
509
|
+
ready(new Error(`the command stream closed before the command ${first.type === "attach" ? "was read on" : "started"} (code ${code ?? "none"})`));
|
|
510
|
+
// The command runs on in the sandbox: another socket reads on from where this one got to.
|
|
511
|
+
if (socket === command.socket && !abandoned && !command.ended && command.execId !== undefined)
|
|
512
|
+
void this.#resume(command);
|
|
513
|
+
});
|
|
514
|
+
const bound = boundOf(ctx.timeoutMs, ctx.signal, first.type === "attach" ? "the command stream's attach" : "opening the command stream");
|
|
515
|
+
try {
|
|
516
|
+
const failed = await Promise.race([readied, bound.promise]);
|
|
517
|
+
if (failed !== undefined)
|
|
518
|
+
throw failed;
|
|
519
|
+
}
|
|
520
|
+
catch (error) {
|
|
521
|
+
abandoned = true;
|
|
522
|
+
clearTimeout(silence);
|
|
523
|
+
// A start with no `started` in time may still start in the sandbox: only 1000 ends it there. An attach's command runs on.
|
|
524
|
+
socket.close(first.type === "start" ? END : DROP);
|
|
525
|
+
const name = error.name;
|
|
526
|
+
if (error instanceof HostError || name === "AbortError" || name === "TimeoutError")
|
|
527
|
+
throw error;
|
|
528
|
+
const read = await this.#api.json("GET", this.#api.url(`/sandboxes/${encodeURIComponent(command.sandbox)}`), { timeoutMs: ctx.timeoutMs }, ctx.signal);
|
|
529
|
+
if (!read.ok)
|
|
530
|
+
throw new HostError(read.error.code, `${error.message}; ${read.error.message}`);
|
|
531
|
+
const status = read.value?.status;
|
|
532
|
+
const words = `${error.message}; Groundbox reads the sandbox as ${show(status)}`;
|
|
533
|
+
throw typeof status === "string" && status in STATES && STATES[status] === undefined ? new HostError("gone", words) : new Error(words);
|
|
534
|
+
}
|
|
535
|
+
finally {
|
|
536
|
+
bound.clear();
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Reads on after a socket closed with the command still running: a new socket attaches from the position read to,
|
|
541
|
+
* tried again with doubling pauses. A try succeeds once Groundbox speaks on its socket, so a peer that takes every
|
|
542
|
+
* attach and says nothing never starts the clock again. A sandbox that is gone, or no socket Groundbox speaks on
|
|
543
|
+
* within the give-up bound (RESUME_GIVE_UP_MS), fails the stream.
|
|
544
|
+
*/
|
|
545
|
+
async #resume(command) {
|
|
546
|
+
// One at a time, and none while reading is paused (#events starts it again).
|
|
547
|
+
if (command.resuming || command.paused || command.ended)
|
|
548
|
+
return;
|
|
549
|
+
command.resuming = true;
|
|
550
|
+
try {
|
|
551
|
+
const since = Date.now();
|
|
552
|
+
const giveUp = this.#bounds.resumeGiveUpMs;
|
|
553
|
+
for (let wait = RESUME_MIN_MS; !command.ended; wait = Math.min(wait * 2, RESUME_MAX_MS)) {
|
|
554
|
+
try {
|
|
555
|
+
// Each try within what is left of the bound, and ATTACH_MS at most.
|
|
556
|
+
const timeoutMs = Math.max(1, Math.min(ATTACH_MS, since + giveUp - Date.now()));
|
|
557
|
+
await this.#connect(command, { type: "attach", exec_id: command.execId, seq: command.seq, encoding: "base64" }, { timeoutMs });
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
catch (error) {
|
|
561
|
+
const code = error instanceof HostError ? error.code : undefined;
|
|
562
|
+
if (code === "not_found" || code === "gone")
|
|
563
|
+
return this.#end(command, error);
|
|
564
|
+
// No try that would start past the bound: the stream fails with the last try's words.
|
|
565
|
+
if (Date.now() + wait - since >= giveUp)
|
|
566
|
+
return this.#end(command, new Error(`the command's stream could not be read on again within ${seconds(giveUp)}: ${error.message}`));
|
|
567
|
+
}
|
|
568
|
+
await pause(wait);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
finally {
|
|
572
|
+
command.resuming = false;
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
/** The command's events as its sockets give them, to its exit or its failure; then the last socket is let go of. */
|
|
576
|
+
async *#events(command) {
|
|
577
|
+
try {
|
|
578
|
+
for (;;) {
|
|
579
|
+
const next = command.events.shift();
|
|
580
|
+
if (next !== undefined && "base64" in next) {
|
|
581
|
+
command.queued -= bytesOf(next.base64);
|
|
582
|
+
// Reading was paused with too much unread: read on from where it stopped once the reader has caught up.
|
|
583
|
+
if (command.paused && command.queued <= this.#bounds.queueLowBytes) {
|
|
584
|
+
command.paused = false;
|
|
585
|
+
void this.#resume(command);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
if (next !== undefined)
|
|
589
|
+
yield next;
|
|
590
|
+
else if (command.ended)
|
|
591
|
+
break;
|
|
592
|
+
else
|
|
593
|
+
await new Promise((done) => (command.wake = done));
|
|
594
|
+
}
|
|
595
|
+
if (command.failure)
|
|
596
|
+
throw command.failure;
|
|
597
|
+
}
|
|
598
|
+
finally {
|
|
599
|
+
this.#end(command);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* The daemon's upload through the files API (PUT /v1/sandboxes/{id}/files?path=), the bytes as they are, written as
|
|
604
|
+
* the sandbox's command user (root on the box image, runner on Groundbox's own).
|
|
605
|
+
*/
|
|
606
|
+
async upload(id, path, bytes, ctx) {
|
|
607
|
+
await this.#call("PUT", `/sandboxes/${encodeURIComponent(id)}/files?path=${encodeURIComponent(path)}`, undefined, ctx, { retry: true, bytes: new Uint8Array(bytes) });
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* The janitor's deadline label, moved. PATCH /v1/sandboxes/{id} replaces the whole metadata map, so the map is read
|
|
611
|
+
* and sent back with the one label changed; the adapter is its only writer. Groundbox's own timer stays at the
|
|
612
|
+
* backstop create gave it.
|
|
613
|
+
*/
|
|
614
|
+
async extend(id, endsAt, ctx) {
|
|
615
|
+
const path = `/sandboxes/${encodeURIComponent(id)}`;
|
|
616
|
+
const sandbox = await this.#call("GET", path, undefined, ctx, { retry: true });
|
|
617
|
+
await this.#call("PATCH", path, { metadata: { ...(sandbox?.metadata ?? {}), [DEADLINE_LABEL]: endsAt.toISOString() } }, ctx);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* Computers that are Groundbox sandboxes, on the shared adapter. A spec's image is the box image by default
|
|
622
|
+
* (prepareImage), "default" (the team's default template, else Groundbox's own image), a template of the key's team, or
|
|
623
|
+
* a public image.
|
|
624
|
+
*/
|
|
625
|
+
export class GroundboxProvider extends HostedProvider {
|
|
626
|
+
/**
|
|
627
|
+
* The provider contract's prepareImage (its descriptor declares it): the box image the release publishes, by its
|
|
628
|
+
* public registry tag (box-image.ts). No call: Groundbox turns it into a disk at the first create from it, and keeps
|
|
629
|
+
* that disk for later ones.
|
|
630
|
+
*/
|
|
631
|
+
async prepareImage() {
|
|
632
|
+
return ok(boxImageRef());
|
|
633
|
+
}
|
|
634
|
+
constructor(options) {
|
|
635
|
+
const { apiKey, apiUrl = DEFAULT_API_URL, diskGb, fetch, webSocket, streamBounds, maxLifetimeMs = DEFAULT_LIFETIME_MS, ...rest } = options ?? {};
|
|
636
|
+
if (typeof apiKey !== "string" || apiKey === "")
|
|
637
|
+
throw new Error("options.apiKey, the Groundbox API key, is required: the provider reads no environment, so the caller passes it");
|
|
638
|
+
let url;
|
|
639
|
+
try {
|
|
640
|
+
url = new URL(apiUrl);
|
|
641
|
+
}
|
|
642
|
+
catch {
|
|
643
|
+
// Refused below, in words.
|
|
644
|
+
}
|
|
645
|
+
// The key rides every call and the stream's upgrade: never in cleartext past this machine.
|
|
646
|
+
if (url === undefined || !(url.protocol === "https:" || (url.protocol === "http:" && LOOPBACK.test(url.hostname)))) {
|
|
647
|
+
throw new Error(`the Groundbox API URL must be https, or http to a loopback host (127.0.0.0/8, ::1 or localhost), such as ${DEFAULT_API_URL}, not ${JSON.stringify(apiUrl)}`);
|
|
648
|
+
}
|
|
649
|
+
if (diskGb !== undefined && !(isWhole(diskGb) && diskGb >= 1 && diskGb <= MAX_DISK_GB))
|
|
650
|
+
throw new Error(`diskGb is a whole number of GB, 1 to ${MAX_DISK_GB}, not ${String(diskGb)}`);
|
|
651
|
+
if (Number(rest.daemonUser?.split(":")[0]) === IMAGE_UID)
|
|
652
|
+
throw new Error(`the daemon user ${rest.daemonUser} is the uid of the sandbox's own user, whose processes init refuses to run beside; choose another, such as 2510:2510`);
|
|
653
|
+
super(new GroundboxHost({
|
|
654
|
+
apiKey,
|
|
655
|
+
apiUrl,
|
|
656
|
+
...(fetch ? { fetch } : {}),
|
|
657
|
+
webSocket: webSocket ?? ((url, init) => new WebSocket(url, init)),
|
|
658
|
+
...(diskGb === undefined ? {} : { diskGb }),
|
|
659
|
+
kind: rest.kind === "desktop" ? "desktop" : "linux",
|
|
660
|
+
...(streamBounds === undefined ? {} : { streamBounds }),
|
|
661
|
+
}), { ...rest, maxLifetimeMs });
|
|
662
|
+
}
|
|
663
|
+
}
|