@finalai/sandbox-router-final 0.2.0 → 0.2.2
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 +63 -6
- package/dist/modules/claims.d.mts +3 -0
- package/dist/modules/claims.mjs +24 -0
- package/dist/modules/claims.mjs.map +7 -0
- package/dist/modules/computer.d.mts +7 -0
- package/dist/modules/computer.mjs +57 -0
- package/dist/modules/computer.mjs.map +7 -0
- package/dist/modules/images.d.mts +23 -3
- package/dist/modules/images.mjs +48 -23
- package/dist/modules/images.mjs.map +3 -3
- package/dist/modules/lifecycle.d.mts +25 -0
- package/dist/modules/lifecycle.mjs +46 -0
- package/dist/modules/lifecycle.mjs.map +7 -0
- package/dist/modules/limits.d.mts +1 -0
- package/dist/modules/limits.mjs +20 -1
- package/dist/modules/limits.mjs.map +2 -2
- package/dist/modules/options.d.mts +8 -5
- package/dist/modules/options.mjs +8 -6
- package/dist/modules/options.mjs.map +2 -2
- package/dist/modules/provider.mjs +1023 -127
- package/dist/modules/provider.mjs.map +2 -2
- package/dist/modules/service.d.mts +12 -0
- package/dist/modules/service.mjs +49 -0
- package/dist/modules/service.mjs.map +7 -0
- package/dist/modules/usage.d.mts +7 -0
- package/dist/modules/usage.mjs +50 -0
- package/dist/modules/usage.mjs.map +7 -0
- package/dist/modules/vm/api.d.mts +2 -1
- package/dist/modules/vm/api.mjs +11 -3
- package/dist/modules/vm/api.mjs.map +2 -2
- package/dist/modules/vm/client.d.mts +85 -4
- package/dist/modules/vm/client.mjs +142 -6
- package/dist/modules/vm/client.mjs.map +2 -2
- package/dist/modules/vm/errors.d.mts +2 -0
- package/dist/modules/vm/errors.mjs +2 -1
- package/dist/modules/vm/errors.mjs.map +2 -2
- package/dist/modules/vm/exec.d.mts +1 -0
- package/dist/modules/vm/exec.mjs +2 -0
- package/dist/modules/vm/exec.mjs.map +2 -2
- package/dist/modules/vm/files.d.mts +8 -0
- package/dist/modules/vm/files.mjs +47 -0
- package/dist/modules/vm/files.mjs.map +2 -2
- package/dist/modules/vm/ids.d.mts +1 -0
- package/dist/modules/vm/ids.mjs +2 -0
- package/dist/modules/vm/ids.mjs.map +2 -2
- package/dist/modules/vm/ingress.d.mts +5 -0
- package/dist/modules/vm/ingress.mjs +21 -0
- package/dist/modules/vm/ingress.mjs.map +2 -2
- package/dist/modules/vm/machines.d.mts +3 -0
- package/dist/modules/vm/machines.mjs +2 -0
- package/dist/modules/vm/machines.mjs.map +2 -2
- package/dist/modules/vm/network.d.mts +3 -1
- package/dist/modules/vm/network.mjs +3 -2
- package/dist/modules/vm/network.mjs.map +2 -2
- package/dist/modules/vm/resources.d.mts +251 -0
- package/dist/modules/vm/resources.mjs +210 -0
- package/dist/modules/vm/resources.mjs.map +7 -0
- package/dist/modules/vm/routes.d.mts +55 -0
- package/dist/modules/vm/routes.mjs +61 -0
- package/dist/modules/vm/routes.mjs.map +7 -0
- package/dist/modules/vm/sandbox.d.mts +92 -3
- package/dist/modules/vm/sandbox.mjs +234 -4
- package/dist/modules/vm/sandbox.mjs.map +2 -2
- package/dist/modules/vm/schemas.d.mts +219 -0
- package/dist/modules/vm/schemas.mjs +34 -3
- package/dist/modules/vm/schemas.mjs.map +2 -2
- package/dist/modules/vm/size.d.mts +10 -0
- package/dist/modules/vm/size.mjs +7 -0
- package/dist/modules/vm/size.mjs.map +7 -0
- package/dist/modules/vm/wire.d.mts +3 -0
- package/dist/modules/vm/wire.mjs +6 -0
- package/dist/modules/vm/wire.mjs.map +2 -2
- package/package.json +2 -2
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import {
|
|
2
|
-
AtEnd,
|
|
3
2
|
attempt,
|
|
3
|
+
BillingModel,
|
|
4
|
+
canonicalJson,
|
|
4
5
|
defineProvider,
|
|
6
|
+
DesktopState,
|
|
5
7
|
EgressMode,
|
|
6
8
|
ExitReason,
|
|
7
9
|
fail,
|
|
8
10
|
failFromStatus,
|
|
9
11
|
FileKind,
|
|
10
12
|
fitWithinLimits,
|
|
11
|
-
canonicalJson,
|
|
12
13
|
formatUsd,
|
|
13
|
-
sha256Hex,
|
|
14
14
|
HardwareConfidence,
|
|
15
15
|
isEgressAllowList,
|
|
16
16
|
ok,
|
|
@@ -18,35 +18,65 @@ import {
|
|
|
18
18
|
PortAuth,
|
|
19
19
|
ProcessFrameKind,
|
|
20
20
|
ProcessSignal,
|
|
21
|
-
BillingModel,
|
|
22
21
|
SandboxRouterErrorCode,
|
|
23
22
|
SandboxState,
|
|
23
|
+
ServiceState,
|
|
24
|
+
sha256Hex,
|
|
24
25
|
shellQuote,
|
|
25
26
|
SPECIFICATION_VERSION,
|
|
26
27
|
toNanos,
|
|
27
|
-
unsupported
|
|
28
|
+
unsupported,
|
|
29
|
+
VolumeState
|
|
28
30
|
} from "@finalai/sandbox-router/provider";
|
|
29
|
-
import {
|
|
31
|
+
import { DISPLAY_ENV, SCREENSHOT_COMMAND, xdotoolCommand } from "./computer.mjs";
|
|
30
32
|
import { createSeqFrames } from "./frames.mjs";
|
|
31
|
-
import {
|
|
33
|
+
import { baseSource, buildImage, ensureImage, imageStrategy } from "./images.mjs";
|
|
34
|
+
import { DEFAULT_WALL_CLOCK_S, lifecycleFields, lifecycleOf } from "./lifecycle.mjs";
|
|
35
|
+
import {
|
|
36
|
+
capabilities,
|
|
37
|
+
DEFAULT_DISK_GIB,
|
|
38
|
+
DEFAULT_VOLUME_GIB,
|
|
39
|
+
limits,
|
|
40
|
+
PROVIDER,
|
|
41
|
+
regions
|
|
42
|
+
} from "./limits.mjs";
|
|
32
43
|
import {
|
|
33
44
|
finalOptionsSchema
|
|
34
45
|
} from "./options.mjs";
|
|
46
|
+
import { claimOf } from "./claims.mjs";
|
|
47
|
+
import { isStoppedWorkload, serviceWorkload, STOPPED_WORKLOAD } from "./service.mjs";
|
|
48
|
+
import { chargeLines, metricPoints, metricsStep } from "./usage.mjs";
|
|
35
49
|
import {
|
|
36
50
|
createVmClient,
|
|
37
51
|
SourceKind
|
|
38
52
|
} from "./vm/client.mjs";
|
|
39
53
|
import { systemClock } from "./vm/clock.mjs";
|
|
40
54
|
import { isVmError } from "./vm/errors.mjs";
|
|
55
|
+
import { grantSandboxUuid, ingressOrigin } from "./vm/grants.mjs";
|
|
56
|
+
import { sandboxIdFromUuid } from "./vm/ids.mjs";
|
|
57
|
+
import { IdlePolicy } from "./vm/resources.mjs";
|
|
41
58
|
import { SandboxState as VmState } from "./vm/schemas.mjs";
|
|
42
|
-
import {
|
|
59
|
+
import {
|
|
60
|
+
COMPUTER_EDITOR_PORT,
|
|
61
|
+
DESKTOP_EDITOR_PORT,
|
|
62
|
+
PREVIEW_TOKEN_HEADER,
|
|
63
|
+
PREVIEW_TOKEN_QUERY
|
|
64
|
+
} from "./vm/wire.mjs";
|
|
43
65
|
const REGION = regions[0] ?? "us-west";
|
|
44
66
|
const SETTLE_TIMEOUT_MS = 5 * 6e4;
|
|
45
67
|
const SETTLE_POLL_MS = 500;
|
|
68
|
+
const DESKTOP_START_TIMEOUT_MS = 3 * 6e4;
|
|
69
|
+
const DESKTOP_POLL_MS = 2e3;
|
|
46
70
|
const LIST_PAGE = 200;
|
|
47
71
|
const PREVIEW_TOKEN_TTL_S = 86400;
|
|
72
|
+
const PREVIEW_TOKEN_MIN_TTL_S = 60;
|
|
73
|
+
const PREVIEW_TOKEN_MAX_TTL_S = 7 * 86400;
|
|
74
|
+
const GRANT_MIN_TTL_S = 60;
|
|
75
|
+
const GRANT_MAX_TTL_S = 86400;
|
|
48
76
|
const MAX_CACHED_HANDLES = 1e3;
|
|
49
77
|
const HOURS_PER_MONTH = 730;
|
|
78
|
+
const PREVIEW_SCOPE = /^preview:(\d+)$/;
|
|
79
|
+
const PLAN_MAX = /exceeds the plan maximum of (\d+)/;
|
|
50
80
|
const STATES = {
|
|
51
81
|
[VmState.Creating]: SandboxState.Creating,
|
|
52
82
|
[VmState.Running]: SandboxState.Running,
|
|
@@ -73,14 +103,22 @@ const toVendor = (info) => ({
|
|
|
73
103
|
granted: {
|
|
74
104
|
cpu: info.cpu?.request ?? info.vcpu,
|
|
75
105
|
memoryMib: info.memory?.request ?? info.memoryMb,
|
|
76
|
-
diskGib: info.diskGb
|
|
77
|
-
|
|
106
|
+
diskGib: info.diskGb,
|
|
107
|
+
cpuLimit: info.cpu?.limit ?? null,
|
|
108
|
+
memoryLimitMib: info.memory?.limit ?? null
|
|
109
|
+
},
|
|
110
|
+
generation: info.generation
|
|
78
111
|
});
|
|
79
112
|
const SIGNALS = {
|
|
80
113
|
[ProcessSignal.Hup]: 1,
|
|
81
114
|
[ProcessSignal.Int]: 2,
|
|
115
|
+
[ProcessSignal.Quit]: 3,
|
|
82
116
|
[ProcessSignal.Kill]: 9,
|
|
83
|
-
[ProcessSignal.
|
|
117
|
+
[ProcessSignal.Usr1]: 10,
|
|
118
|
+
[ProcessSignal.Usr2]: 12,
|
|
119
|
+
[ProcessSignal.Term]: 15,
|
|
120
|
+
[ProcessSignal.Cont]: 18,
|
|
121
|
+
[ProcessSignal.Stop]: 19
|
|
84
122
|
};
|
|
85
123
|
const signalName = (signal) => {
|
|
86
124
|
if (signal == null) return null;
|
|
@@ -96,9 +134,64 @@ const fileEntry = (stat) => ({
|
|
|
96
134
|
modifiedAt: Number.isNaN(stat.modifiedAt.getTime()) ? null : stat.modifiedAt.toISOString(),
|
|
97
135
|
mode: stat.mode & 4095
|
|
98
136
|
});
|
|
137
|
+
const labelFilter = (labels) => {
|
|
138
|
+
const bad = Object.keys(labels).find((key) => key.includes("="));
|
|
139
|
+
return bad == null ? ok(void 0) : fail(
|
|
140
|
+
SandboxRouterErrorCode.InvalidRequest,
|
|
141
|
+
`cannot filter by a label key holding "=": ${bad}`
|
|
142
|
+
);
|
|
143
|
+
};
|
|
144
|
+
const millisToIso = (at) => at == null ? null : new Date(at).toISOString();
|
|
145
|
+
const MEMORY_SNAPSHOTS = /* @__PURE__ */ new Set(["pause", "checkpoint", "fork", "template"]);
|
|
146
|
+
const vendorSnapshot = (snapshot) => ({
|
|
147
|
+
snapshotId: snapshot.id,
|
|
148
|
+
name: snapshot.name ?? snapshot.id,
|
|
149
|
+
state: snapshot.durableAt == null ? "pending" : "ready",
|
|
150
|
+
memory: MEMORY_SNAPSHOTS.has(snapshot.kind),
|
|
151
|
+
sizeBytes: null,
|
|
152
|
+
labels: snapshot.labels,
|
|
153
|
+
createdAt: snapshot.createdAt.toISOString(),
|
|
154
|
+
// Named snapshots are kept until deleted.
|
|
155
|
+
expiresAt: null
|
|
156
|
+
});
|
|
157
|
+
const presignedExpiry = (url) => {
|
|
158
|
+
try {
|
|
159
|
+
const params = new URL(url).searchParams;
|
|
160
|
+
const signed = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/.exec(
|
|
161
|
+
params.get("X-Amz-Date") ?? ""
|
|
162
|
+
);
|
|
163
|
+
const lifetimeS = Number(params.get("X-Amz-Expires"));
|
|
164
|
+
if (signed == null || !Number.isFinite(lifetimeS)) return null;
|
|
165
|
+
const [, year, month, day, hour, minute, second] = signed.map(Number);
|
|
166
|
+
const at = Date.UTC(year ?? 0, (month ?? 1) - 1, day, hour, minute, second);
|
|
167
|
+
return new Date(at + lifetimeS * 1e3).toISOString();
|
|
168
|
+
} catch {
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
const partsWithExpiry = (parts) => parts.map((part) => ({ ...part, expiresAt: presignedExpiry(part.url) }));
|
|
173
|
+
const CODES = {
|
|
174
|
+
conflict: SandboxRouterErrorCode.Conflict,
|
|
175
|
+
cache_object_exists: SandboxRouterErrorCode.AlreadyExists,
|
|
176
|
+
volume_name_taken: SandboxRouterErrorCode.AlreadyExists,
|
|
177
|
+
volume_in_use_path: SandboxRouterErrorCode.VolumeInUse,
|
|
178
|
+
no_free_slot: SandboxRouterErrorCode.NoFreeSlot,
|
|
179
|
+
no_volume_slots: SandboxRouterErrorCode.NoFreeSlot,
|
|
180
|
+
commit_not_allowed: SandboxRouterErrorCode.CommitNotAllowed,
|
|
181
|
+
volume_not_found: SandboxRouterErrorCode.NotFound,
|
|
182
|
+
hostname_taken: SandboxRouterErrorCode.AlreadyExists,
|
|
183
|
+
not_entitled: SandboxRouterErrorCode.Unauthorized,
|
|
184
|
+
volume_deleted: SandboxRouterErrorCode.NotFound
|
|
185
|
+
};
|
|
99
186
|
const classify = (cause) => {
|
|
100
187
|
if (!isVmError(cause)) return null;
|
|
101
188
|
const nativeError = `${cause.code}: ${cause.message}`;
|
|
189
|
+
if (cause.noCapacity)
|
|
190
|
+
return fail(SandboxRouterErrorCode.NoCapacity, "final has no capacity for this now", {
|
|
191
|
+
retryable: true,
|
|
192
|
+
status: cause.status,
|
|
193
|
+
nativeError
|
|
194
|
+
});
|
|
102
195
|
if (cause.status == null) {
|
|
103
196
|
if (cause.code === "timeout")
|
|
104
197
|
return fail(SandboxRouterErrorCode.Timeout, cause.message, { retryable: true, nativeError });
|
|
@@ -109,6 +202,8 @@ const classify = (cause) => {
|
|
|
109
202
|
});
|
|
110
203
|
return fail(SandboxRouterErrorCode.ProviderError, cause.message, { nativeError });
|
|
111
204
|
}
|
|
205
|
+
const code = CODES[cause.code];
|
|
206
|
+
if (code != null) return fail(code, cause.message, { status: cause.status, nativeError });
|
|
112
207
|
if (cause.status === 410)
|
|
113
208
|
return fail(SandboxRouterErrorCode.NotFound, "final has no such resource", {
|
|
114
209
|
status: 410,
|
|
@@ -116,11 +211,19 @@ const classify = (cause) => {
|
|
|
116
211
|
});
|
|
117
212
|
return failFromStatus(PROVIDER, cause.status, nativeError);
|
|
118
213
|
};
|
|
119
|
-
const isMissing = (cause) => isVmError(cause) && (cause.status === 404 || cause.status === 410 || cause.code === "invalid_id");
|
|
214
|
+
const isMissing = (cause) => isVmError(cause) && (cause.status === 404 || cause.status === 410 || cause.code === "invalid_id" || cause.code === "volume_not_found");
|
|
120
215
|
const call = (run) => attempt(PROVIDER, run, classify);
|
|
121
216
|
const failure = (cause) => classify(cause) ?? fail(SandboxRouterErrorCode.ProviderError, `${PROVIDER} failed`, {
|
|
122
217
|
nativeError: cause instanceof Error ? cause.message : String(cause)
|
|
123
218
|
});
|
|
219
|
+
const orNull = async (run) => {
|
|
220
|
+
try {
|
|
221
|
+
return ok(await run());
|
|
222
|
+
} catch (cause) {
|
|
223
|
+
if (isMissing(cause)) return ok(null);
|
|
224
|
+
return failure(cause);
|
|
225
|
+
}
|
|
226
|
+
};
|
|
124
227
|
const classifyCreate = (cause) => {
|
|
125
228
|
const lost = isVmError(cause) && (cause.status == null && cause.code === "request_failed" || cause.code === "pending") || cause instanceof Error && (cause.name === "TimeoutError" || cause.name === "AbortError");
|
|
126
229
|
if (lost)
|
|
@@ -141,20 +244,86 @@ const networkFields = (network) => {
|
|
|
141
244
|
allowCidrs: network.egress.allowCidrs ?? []
|
|
142
245
|
} : { allowInternet: false, allowDomains: [], allowCidrs: [] };
|
|
143
246
|
};
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
247
|
+
const networkOf = (policy) => {
|
|
248
|
+
const allowDomains = policy.allowDomains ?? [];
|
|
249
|
+
const allowCidrs = policy.allowCidrs ?? [];
|
|
250
|
+
if (policy.allowInternet) return { egress: EgressMode.AllowAll };
|
|
251
|
+
if (allowDomains.length === 0 && allowCidrs.length === 0) return { egress: EgressMode.DenyAll };
|
|
252
|
+
return { egress: { allowDomains, allowCidrs } };
|
|
148
253
|
};
|
|
254
|
+
const PLATFORM_SCOPES = {
|
|
255
|
+
exec: "exec",
|
|
256
|
+
"files:read": "files:read",
|
|
257
|
+
"files:write": "files"
|
|
258
|
+
};
|
|
259
|
+
const platformScope = (scope) => PLATFORM_SCOPES[scope] ?? (scope.startsWith("ports:") ? scope : scope);
|
|
149
260
|
const sourceOf = (artifact) => artifact.kind === "template" ? { kind: SourceKind.Template, templateId: artifact.id } : artifact.kind === "snapshot" ? { kind: SourceKind.Snapshot, snapshotId: artifact.id } : { kind: SourceKind.Image, imageId: artifact.id };
|
|
261
|
+
const DESKTOP_STATES = {
|
|
262
|
+
running: DesktopState.Running,
|
|
263
|
+
starting: DesktopState.Starting
|
|
264
|
+
};
|
|
265
|
+
const desktopStatus = (status) => ({
|
|
266
|
+
state: DESKTOP_STATES[status.state] ?? DesktopState.Stopped,
|
|
267
|
+
width: null,
|
|
268
|
+
height: null,
|
|
269
|
+
error: status.error ?? (status.state === "error" ? "the desktop is unhealthy" : null),
|
|
270
|
+
version: status.applied_version ?? status.version ?? null
|
|
271
|
+
});
|
|
272
|
+
const domainState = (status) => status === "active" ? "active" : status === "error" ? "failed" : "pending";
|
|
273
|
+
const volumeOf = (volume) => ({
|
|
274
|
+
volumeId: volume.id,
|
|
275
|
+
name: volume.name,
|
|
276
|
+
region: REGION,
|
|
277
|
+
sizeGib: volume.size_gb,
|
|
278
|
+
state: volume.state === "active" ? VolumeState.Ready : volume.state === "deleting" ? VolumeState.Deleted : VolumeState.Unknown,
|
|
279
|
+
labels: volume.labels
|
|
280
|
+
});
|
|
281
|
+
const CACHE_NAMESPACE = "sandbox-router";
|
|
282
|
+
const CACHE_SEPARATOR = "";
|
|
283
|
+
const CACHE_KEY_BYTES = 1024;
|
|
284
|
+
const storedKey = (scope, key) => {
|
|
285
|
+
if (scope.includes(CACHE_SEPARATOR) || key.includes(CACHE_SEPARATOR))
|
|
286
|
+
return fail(SandboxRouterErrorCode.InvalidRequest, "cache scopes and keys cannot hold U+001F");
|
|
287
|
+
const stored = `${scope}${CACHE_SEPARATOR}${key}`;
|
|
288
|
+
return Buffer.byteLength(stored, "utf8") > CACHE_KEY_BYTES ? fail(
|
|
289
|
+
SandboxRouterErrorCode.InvalidRequest,
|
|
290
|
+
`a cache scope and key together take at most ${CACHE_KEY_BYTES - 1} bytes`
|
|
291
|
+
) : ok(stored);
|
|
292
|
+
};
|
|
293
|
+
const routerKey = (object) => {
|
|
294
|
+
const at = object.key.indexOf(CACHE_SEPARATOR);
|
|
295
|
+
return object.namespace !== CACHE_NAMESPACE || at < 0 ? null : { scope: object.key.slice(0, at), key: object.key.slice(at + 1) };
|
|
296
|
+
};
|
|
297
|
+
const cacheEntry = (object, url, urlExpiresAt) => {
|
|
298
|
+
const named = routerKey(object);
|
|
299
|
+
return named == null ? null : {
|
|
300
|
+
id: object.id,
|
|
301
|
+
...named,
|
|
302
|
+
sizeBytes: object.size_bytes ?? 0,
|
|
303
|
+
createdAt: object.created_at ?? null,
|
|
304
|
+
url,
|
|
305
|
+
urlExpiresAt
|
|
306
|
+
};
|
|
307
|
+
};
|
|
308
|
+
const CACHE_LIST_LIMIT = 100;
|
|
309
|
+
const CACHE_LIST_MAX = 1e3;
|
|
310
|
+
const sizeOf = (spec) => ({
|
|
311
|
+
cpu: [spec.cpu, Math.max(spec.cpuLimit ?? spec.cpu, spec.cpu)],
|
|
312
|
+
memory: [spec.memoryMib, Math.max(spec.memoryLimitMib ?? spec.memoryMib, spec.memoryMib)]
|
|
313
|
+
});
|
|
150
314
|
const IDLE_WORKLOAD = {
|
|
151
315
|
entrypoint: ["/bin/sh", "-c"],
|
|
152
316
|
cmd: ["exec sleep infinity"],
|
|
153
317
|
restart: false
|
|
154
318
|
};
|
|
155
319
|
const sameSize = (source, size) => source.cpu?.request === size.cpu[0] && source.cpu.limit === size.cpu[1] && source.memory?.request === size.memory[0] && source.memory.limit === size.memory[1];
|
|
320
|
+
const parseOptions = (value) => {
|
|
321
|
+
const parsed = finalOptionsSchema.safeParse(value ?? {});
|
|
322
|
+
return parsed.success ? ok(parsed.data) : fail(SandboxRouterErrorCode.InvalidRequest, parsed.error.message);
|
|
323
|
+
};
|
|
156
324
|
const final = (credentials, options = {}) => {
|
|
157
325
|
const clock = systemClock;
|
|
326
|
+
const defaultWallClockS = options.defaultWallClockLimitS ?? DEFAULT_WALL_CLOCK_S;
|
|
158
327
|
const client = createVmClient({
|
|
159
328
|
apiKey: credentials.apiKey,
|
|
160
329
|
apiUrl: credentials.apiUrl,
|
|
@@ -188,6 +357,35 @@ const final = (credentials, options = {}) => {
|
|
|
188
357
|
}
|
|
189
358
|
};
|
|
190
359
|
const ready = async (handle, signal) => toVendor(await settle(handle, [VmState.Running], signal));
|
|
360
|
+
const routeOf = async (hostname) => (await client.ingressRoutes.list({ hostname: hostname.trim().toLowerCase() }))[0] ?? null;
|
|
361
|
+
const withLifecycle = async (handle, info) => {
|
|
362
|
+
const settings = await handle.settings();
|
|
363
|
+
return {
|
|
364
|
+
...toVendor(info),
|
|
365
|
+
lifecycle: lifecycleOf({
|
|
366
|
+
idleTimeoutS: settings.idle_timeout_s ?? null,
|
|
367
|
+
idleTimeoutDisabled: settings.idle_timeout_disabled ?? false,
|
|
368
|
+
idlePolicy: settings.idle_policy ?? IdlePolicy.Pause,
|
|
369
|
+
autoResume: settings.auto_resume ?? true,
|
|
370
|
+
maxLifetime: info.maxLifetime,
|
|
371
|
+
wallClockLimitS: info.wallClockLimitS,
|
|
372
|
+
wallClockDeadlineAt: info.wallClockDeadlineAt,
|
|
373
|
+
running: info.state === VmState.Running
|
|
374
|
+
})
|
|
375
|
+
};
|
|
376
|
+
};
|
|
377
|
+
const whileStopped = async (handle, change) => {
|
|
378
|
+
const before = await handle.refresh();
|
|
379
|
+
const wasRunning = before.state === VmState.Running;
|
|
380
|
+
if (before.state !== VmState.Stopped) {
|
|
381
|
+
await handle.stop();
|
|
382
|
+
await settle(handle, [VmState.Stopped]);
|
|
383
|
+
}
|
|
384
|
+
await change();
|
|
385
|
+
if (!wasRunning) return handle.refresh();
|
|
386
|
+
await handle.start();
|
|
387
|
+
return settle(handle, [VmState.Running]);
|
|
388
|
+
};
|
|
191
389
|
const startTemplateService = async (handle, templateId, env) => {
|
|
192
390
|
const template = await client.templates.get(templateId);
|
|
193
391
|
if (template.startCmd == null) return;
|
|
@@ -230,9 +428,11 @@ const final = (credentials, options = {}) => {
|
|
|
230
428
|
}
|
|
231
429
|
if (artifact != null) return ok(plain(sourceOf(artifact)));
|
|
232
430
|
if (spec.image == null) return ok(plain());
|
|
233
|
-
const
|
|
234
|
-
if (
|
|
235
|
-
|
|
431
|
+
const base = baseSource(spec.image.base);
|
|
432
|
+
if (base == null)
|
|
433
|
+
return fail(SandboxRouterErrorCode.UnsupportedByProvider, "final cannot run this base");
|
|
434
|
+
if ("lineage" in base && base.lineage === "base") return ok(plain());
|
|
435
|
+
const image = await ensureImage({ client, clock, signal: args.signal }, base);
|
|
236
436
|
return image.ok ? ok(plain({ kind: SourceKind.Image, imageId: image.value })) : image;
|
|
237
437
|
};
|
|
238
438
|
const stream = async (args) => {
|
|
@@ -311,32 +511,95 @@ const final = (credentials, options = {}) => {
|
|
|
311
511
|
resize: (size) => input(() => current.resize(size))
|
|
312
512
|
});
|
|
313
513
|
};
|
|
514
|
+
const capture = async (handle, command) => {
|
|
515
|
+
const stdout = [];
|
|
516
|
+
const stderr = [];
|
|
517
|
+
const process = await handle.exec({
|
|
518
|
+
cmd: command,
|
|
519
|
+
env: DISPLAY_ENV,
|
|
520
|
+
timeoutMs: 3e4,
|
|
521
|
+
onStdout: (bytes) => stdout.push(bytes),
|
|
522
|
+
onStderr: (bytes) => stderr.push(bytes)
|
|
523
|
+
});
|
|
524
|
+
process.closeStdin();
|
|
525
|
+
const result = await process.wait();
|
|
526
|
+
return {
|
|
527
|
+
exitCode: result.exitCode,
|
|
528
|
+
stdout: new Uint8Array(Buffer.concat(stdout)),
|
|
529
|
+
stderr: Buffer.concat(stderr).toString("utf8")
|
|
530
|
+
};
|
|
531
|
+
};
|
|
314
532
|
const fit = (spec) => {
|
|
315
533
|
const diskGib = spec.diskGib ?? DEFAULT_DISK_GIB;
|
|
316
534
|
const fitted = fitWithinLimits({ limits, spec: { ...spec, diskGib } });
|
|
535
|
+
const size = sizeOf(spec);
|
|
317
536
|
if (spec.gpu != null) fitted.rejected.push({ field: "gpu", reason: "no GPUs" });
|
|
318
537
|
if (spec.region != null && !regions.includes(spec.region))
|
|
319
538
|
fitted.rejected.push({ field: "region", reason: `only ${regions.join(", ")}` });
|
|
539
|
+
if (size.cpu[1] > limits.maxCpu)
|
|
540
|
+
fitted.rejected.push({ field: "cpuLimit", reason: `at most ${limits.maxCpu} vCPU` });
|
|
541
|
+
if (size.memory[1] > limits.maxMemoryMib)
|
|
542
|
+
fitted.rejected.push({
|
|
543
|
+
field: "memoryLimitMib",
|
|
544
|
+
reason: `at most ${limits.maxMemoryMib} MiB`
|
|
545
|
+
});
|
|
546
|
+
if (spec.service != null) {
|
|
547
|
+
const service = serviceWorkload(spec.service);
|
|
548
|
+
if (!service.ok) fitted.rejected.push({ field: "service", reason: service.reason });
|
|
549
|
+
}
|
|
550
|
+
if (spec.image != null && imageStrategy(spec.image) == null)
|
|
551
|
+
fitted.rejected.push({ field: "image", reason: "final cannot run this base" });
|
|
552
|
+
if (spec.volumes.some((mount) => mount.readOnly))
|
|
553
|
+
fitted.ignored.push({
|
|
554
|
+
field: "volumes",
|
|
555
|
+
reason: "a read-only mount is a writable copy whose writes never reach the volume"
|
|
556
|
+
});
|
|
557
|
+
const extra = [
|
|
558
|
+
...spec.cpuLimit == null ? [] : ["cpuLimit"],
|
|
559
|
+
...spec.memoryLimitMib == null ? [] : ["memoryLimitMib"],
|
|
560
|
+
"lifecycle",
|
|
561
|
+
"ports",
|
|
562
|
+
"network",
|
|
563
|
+
"env",
|
|
564
|
+
"labels",
|
|
565
|
+
"telemetry",
|
|
566
|
+
...spec.service == null ? [] : ["service"],
|
|
567
|
+
...spec.placement == null ? [] : ["placement"],
|
|
568
|
+
...spec.volumes.length === 0 ? [] : ["volumes"]
|
|
569
|
+
];
|
|
320
570
|
return {
|
|
321
571
|
...fitted,
|
|
322
|
-
|
|
572
|
+
granted: {
|
|
573
|
+
...fitted.granted,
|
|
574
|
+
cpuLimit: size.cpu[1],
|
|
575
|
+
memoryLimitMib: size.memory[1]
|
|
576
|
+
},
|
|
577
|
+
applied: [
|
|
578
|
+
...spec.diskGib == null ? fitted.applied.filter((field) => field !== "diskGib") : fitted.applied,
|
|
579
|
+
...extra.filter(
|
|
580
|
+
(field) => !fitted.rejected.some((note) => note.field === field) && !fitted.ignored.some((note) => note.field === field)
|
|
581
|
+
)
|
|
582
|
+
]
|
|
323
583
|
};
|
|
324
584
|
};
|
|
585
|
+
const availableRegions = async () => {
|
|
586
|
+
const listed = await call(() => client.machineTypes.list());
|
|
587
|
+
if (!listed.ok) return listed;
|
|
588
|
+
const listedRegions = new Set(listed.value.map((entry) => entry.regionZone));
|
|
589
|
+
return ok(regions.filter((region) => listedRegions.has(region)));
|
|
590
|
+
};
|
|
325
591
|
const prices = async (spec, context) => {
|
|
326
|
-
const parsed =
|
|
327
|
-
if (!parsed.
|
|
328
|
-
const
|
|
592
|
+
const parsed = parseOptions(context.providerOptions);
|
|
593
|
+
if (!parsed.ok) return parsed;
|
|
594
|
+
const size = sizeOf(spec);
|
|
329
595
|
const diskGib = spec.diskGib ?? DEFAULT_DISK_GIB;
|
|
330
596
|
const listed = await call(
|
|
331
|
-
() => client.machineTypes.list({
|
|
332
|
-
cpu: [spec.cpu, cpuLimit ?? spec.cpu],
|
|
333
|
-
memory: [spec.memoryMib, memoryLimitMib ?? spec.memoryMib],
|
|
334
|
-
diskGb: diskGib
|
|
335
|
-
})
|
|
597
|
+
() => client.machineTypes.list({ cpu: size.cpu, memory: size.memory, diskGb: diskGib })
|
|
336
598
|
);
|
|
337
599
|
if (!listed.ok) return listed;
|
|
600
|
+
const { machineTypes, cpuFamilies } = spec.placement ?? {};
|
|
338
601
|
const cheapest = listed.value.find(
|
|
339
|
-
(entry) => entry.price.hourly != null && entry.price.currency.toUpperCase() === "USD" && (
|
|
602
|
+
(entry) => entry.price.hourly != null && entry.price.currency.toUpperCase() === "USD" && (machineTypes == null || machineTypes.includes(entry.machineType)) && (cpuFamilies == null || cpuFamilies.includes(entry.hardware.cpuFamily))
|
|
340
603
|
);
|
|
341
604
|
if (cheapest?.price.hourly == null)
|
|
342
605
|
return fail(SandboxRouterErrorCode.ProviderError, "no priced machine type fits the spec");
|
|
@@ -357,21 +620,103 @@ const final = (credentials, options = {}) => {
|
|
|
357
620
|
sourceUrl: null
|
|
358
621
|
});
|
|
359
622
|
};
|
|
623
|
+
const previewTokens = async (handle, includeRevoked = false) => {
|
|
624
|
+
const now = clock.now();
|
|
625
|
+
return (await handle.tokens.list()).flatMap((token) => {
|
|
626
|
+
const port = token.scopes.length === 1 ? PREVIEW_SCOPE.exec(token.scopes[0] ?? "") : null;
|
|
627
|
+
const live = token.revoked_at == null && (token.expires_at == null || token.expires_at > now);
|
|
628
|
+
return token.purpose === "preview" && port != null && (live || includeRevoked) ? [
|
|
629
|
+
{
|
|
630
|
+
tokenId: token.id,
|
|
631
|
+
port: Number(port[1]),
|
|
632
|
+
expiresAt: millisToIso(token.expires_at),
|
|
633
|
+
createdAt: millisToIso(token.created_at),
|
|
634
|
+
revokedAt: millisToIso(token.revoked_at)
|
|
635
|
+
}
|
|
636
|
+
] : [];
|
|
637
|
+
});
|
|
638
|
+
};
|
|
639
|
+
const mintToken = async (handle, port, ttlS) => {
|
|
640
|
+
const lifetime = Math.min(
|
|
641
|
+
Math.max(Math.round(ttlS ?? PREVIEW_TOKEN_TTL_S), PREVIEW_TOKEN_MIN_TTL_S),
|
|
642
|
+
PREVIEW_TOKEN_MAX_TTL_S
|
|
643
|
+
);
|
|
644
|
+
const minted = await handle.createPreviewToken(port, { ttlS: lifetime });
|
|
645
|
+
return { token: minted.token, expiresAt: minted.expiresAt.toISOString() };
|
|
646
|
+
};
|
|
647
|
+
const domainsOf = async (handle) => {
|
|
648
|
+
const listed = await handle.domains.list();
|
|
649
|
+
return listed.domains.map((domain) => ({
|
|
650
|
+
hostname: domain.domain,
|
|
651
|
+
port: domain.port,
|
|
652
|
+
state: domainState(domain.status),
|
|
653
|
+
records: listed.cname_target == null ? [] : [{ type: "CNAME", name: domain.domain, value: listed.cname_target }],
|
|
654
|
+
error: domain.error,
|
|
655
|
+
createdAt: millisToIso(domain.created_at)
|
|
656
|
+
}));
|
|
657
|
+
};
|
|
658
|
+
const readCache = async (candidates) => {
|
|
659
|
+
const found = await client.caches.lookup(candidates);
|
|
660
|
+
return found == null ? null : cacheEntry(found.object, found.url, found.urlExpiresAt);
|
|
661
|
+
};
|
|
662
|
+
const serviceStatus = async (handle) => {
|
|
663
|
+
const current = await handle.workload.get();
|
|
664
|
+
if (current.workload == null) return null;
|
|
665
|
+
if (isStoppedWorkload(current.workload))
|
|
666
|
+
return {
|
|
667
|
+
state: ServiceState.Stopped,
|
|
668
|
+
healthy: null,
|
|
669
|
+
lastError: null,
|
|
670
|
+
restarts: 0,
|
|
671
|
+
lastExitCode: null,
|
|
672
|
+
updatedAt: null
|
|
673
|
+
};
|
|
674
|
+
const healthy = current.health?.healthy ?? null;
|
|
675
|
+
const lastError = current.health?.error ?? null;
|
|
676
|
+
const updatedAt = current.health?.checked_at == null ? null : new Date(current.health.checked_at).toISOString();
|
|
677
|
+
const info = await handle.refresh();
|
|
678
|
+
if (info.state !== VmState.Running)
|
|
679
|
+
return {
|
|
680
|
+
state: ServiceState.Stopped,
|
|
681
|
+
healthy: null,
|
|
682
|
+
lastError,
|
|
683
|
+
// The platform does not count restarts.
|
|
684
|
+
restarts: 0,
|
|
685
|
+
lastExitCode: null,
|
|
686
|
+
updatedAt
|
|
687
|
+
};
|
|
688
|
+
const guest = (await handle.guestStatus()).workload;
|
|
689
|
+
const checked = current.workload.health_check != null;
|
|
690
|
+
const restarting = current.workload.restart !== false;
|
|
691
|
+
const state = guest.state === "running" ? healthy === false ? ServiceState.Unhealthy : healthy === true || !checked ? ServiceState.Running : ServiceState.Starting : guest.state === "failed" ? ServiceState.Failed : guest.state === "exited" ? restarting ? ServiceState.Starting : ServiceState.Stopped : guest.state === "no_command" ? ServiceState.Stopped : ServiceState.Starting;
|
|
692
|
+
return {
|
|
693
|
+
state,
|
|
694
|
+
healthy,
|
|
695
|
+
lastError: lastError ?? guest.error ?? null,
|
|
696
|
+
restarts: 0,
|
|
697
|
+
lastExitCode: guest.exit_code ?? null,
|
|
698
|
+
updatedAt
|
|
699
|
+
};
|
|
700
|
+
};
|
|
360
701
|
return defineProvider({
|
|
361
702
|
specificationVersion: SPECIFICATION_VERSION,
|
|
362
703
|
name: PROVIDER,
|
|
363
704
|
regions,
|
|
705
|
+
availableRegions,
|
|
364
706
|
capabilities,
|
|
365
707
|
limits,
|
|
366
708
|
providerOptions: finalOptionsSchema,
|
|
367
709
|
fit,
|
|
368
710
|
prices,
|
|
369
711
|
create: async (spec, context) => {
|
|
370
|
-
const
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
712
|
+
const parsed = parseOptions(context.providerOptions);
|
|
713
|
+
if (!parsed.ok) return parsed;
|
|
714
|
+
const providerOptions = parsed.value;
|
|
715
|
+
const timers = lifecycleFields(spec.lifecycle, defaultWallClockS);
|
|
716
|
+
const service = spec.service == null ? null : serviceWorkload(spec.service);
|
|
717
|
+
if (service != null && !service.ok)
|
|
718
|
+
return fail(SandboxRouterErrorCode.InvalidRequest, service.reason);
|
|
719
|
+
const size = sizeOf(spec);
|
|
375
720
|
const resolved = await call(
|
|
376
721
|
() => resolveSource({
|
|
377
722
|
spec,
|
|
@@ -384,20 +729,47 @@ const final = (credentials, options = {}) => {
|
|
|
384
729
|
if (!resolved.ok) return resolved;
|
|
385
730
|
if (!resolved.value.ok) return resolved.value;
|
|
386
731
|
const plan = resolved.value.value;
|
|
732
|
+
const placement = spec.placement;
|
|
733
|
+
const machine = placement?.machineTypes == null && placement?.cpuFamilies == null && providerOptions.machine == null ? void 0 : {
|
|
734
|
+
types: placement?.machineTypes,
|
|
735
|
+
cpuFamilies: placement?.cpuFamilies,
|
|
736
|
+
sort: providerOptions.machine?.sort,
|
|
737
|
+
maxPricePerHour: providerOptions.machine?.maxPricePerHour
|
|
738
|
+
};
|
|
387
739
|
const request = {
|
|
740
|
+
sandboxId: providerOptions.sandboxId == null || providerOptions.sandboxId.startsWith("sbx_") ? providerOptions.sandboxId : sandboxIdFromUuid(providerOptions.sandboxId),
|
|
741
|
+
ephemeral: providerOptions.ephemeral,
|
|
388
742
|
projectId: providerOptions.projectId,
|
|
389
743
|
source: plan.source,
|
|
390
|
-
workload: plan.workload,
|
|
744
|
+
workload: service == null ? plan.workload : void 0,
|
|
745
|
+
workloadBody: service?.workload,
|
|
391
746
|
cpu: plan.sized ? size.cpu : void 0,
|
|
392
747
|
memory: plan.sized ? size.memory : void 0,
|
|
393
748
|
diskGb: spec.diskGib,
|
|
394
|
-
machine
|
|
749
|
+
machine,
|
|
750
|
+
placementGroup: placement?.group,
|
|
395
751
|
env: Object.keys(spec.env).length === 0 ? void 0 : spec.env,
|
|
396
|
-
ports: spec.ports,
|
|
397
|
-
publicPorts:
|
|
752
|
+
ports: spec.ports.map((entry) => entry.port),
|
|
753
|
+
publicPorts: spec.ports.filter((entry) => entry.public).map((entry) => entry.port),
|
|
398
754
|
tools: providerOptions.tools,
|
|
399
755
|
...networkFields(spec.network),
|
|
400
|
-
|
|
756
|
+
idleTimeoutS: timers.idleTimeoutS,
|
|
757
|
+
idlePolicy: timers.idlePolicy,
|
|
758
|
+
autoResume: timers.autoResume,
|
|
759
|
+
wallClockLimitS: timers.wallClockLimitS,
|
|
760
|
+
maxLifetime: timers.maxLifetime ?? void 0,
|
|
761
|
+
pausedRetentionS: providerOptions.pausedRetentionS,
|
|
762
|
+
volumes: spec.volumes.map((mount) => ({
|
|
763
|
+
volumeId: mount.volumeId,
|
|
764
|
+
path: mount.path,
|
|
765
|
+
// A sandbox's writes reach a volume only by a commit.
|
|
766
|
+
allowCommit: !mount.readOnly && mount.allowCommit !== false
|
|
767
|
+
})),
|
|
768
|
+
telemetryResource: Object.keys(spec.telemetry).length === 0 ? void 0 : spec.telemetry,
|
|
769
|
+
ownerSelf: providerOptions.owner === "self",
|
|
770
|
+
retentionExempt: providerOptions.retentionExempt,
|
|
771
|
+
platformEgress: providerOptions.platformEgress,
|
|
772
|
+
cpuPool: providerOptions.cpuPool,
|
|
401
773
|
labels: { name: context.name, ...context.labels },
|
|
402
774
|
signal: context.signal
|
|
403
775
|
};
|
|
@@ -409,10 +781,10 @@ const final = (credentials, options = {}) => {
|
|
|
409
781
|
if (!created.ok) return created;
|
|
410
782
|
const handle = created.value;
|
|
411
783
|
const started = await call(async () => {
|
|
412
|
-
const
|
|
784
|
+
const info = await settle(handle, [VmState.Running], context.signal);
|
|
413
785
|
if (plan.startTemplate != null)
|
|
414
786
|
await startTemplateService(handle, plan.startTemplate, spec.env);
|
|
415
|
-
return
|
|
787
|
+
return withLifecycle(handle, info);
|
|
416
788
|
});
|
|
417
789
|
if (!started.ok) await handle.delete().catch(() => void 0);
|
|
418
790
|
return started;
|
|
@@ -420,8 +792,10 @@ const final = (credentials, options = {}) => {
|
|
|
420
792
|
get: async (id) => {
|
|
421
793
|
try {
|
|
422
794
|
const cached = handles.get(id);
|
|
423
|
-
const
|
|
424
|
-
return ok(
|
|
795
|
+
const handle = cached ?? remember(await client.sandboxes.get(id));
|
|
796
|
+
return ok(
|
|
797
|
+
await withLifecycle(handle, cached == null ? handle.info() : await handle.refresh())
|
|
798
|
+
);
|
|
425
799
|
} catch (cause) {
|
|
426
800
|
if (isMissing(cause)) return ok(null);
|
|
427
801
|
return failure(cause);
|
|
@@ -467,43 +841,104 @@ const final = (credentials, options = {}) => {
|
|
|
467
841
|
await handle.start();
|
|
468
842
|
await settle(handle, [VmState.Running]);
|
|
469
843
|
}),
|
|
470
|
-
//
|
|
471
|
-
//
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
const
|
|
475
|
-
if (
|
|
844
|
+
// Replaces the whole policy, fields left out taking the same defaults as at create. A max
|
|
845
|
+
// lifetime counts from the latest start; without one the wall-clock limit restarts from now.
|
|
846
|
+
setLifecycle: (id, lifecycle) => withHandle(id, async (handle) => {
|
|
847
|
+
const fields = lifecycleFields(lifecycle, defaultWallClockS);
|
|
848
|
+
const { wallClockLimitS } = fields;
|
|
849
|
+
if (wallClockLimitS !== void 0)
|
|
850
|
+
try {
|
|
851
|
+
await handle.setTimeout(wallClockLimitS);
|
|
852
|
+
} catch (cause) {
|
|
853
|
+
const planMax = lifecycle.max === void 0 && isVmError(cause) ? PLAN_MAX.exec(cause.message)?.[1] : void 0;
|
|
854
|
+
if (planMax == null) throw cause;
|
|
855
|
+
await handle.setTimeout(Number(planMax));
|
|
856
|
+
}
|
|
857
|
+
await handle.updateSettings({
|
|
858
|
+
idleTimeoutS: fields.idleTimeoutS,
|
|
859
|
+
idlePolicy: fields.idlePolicy ?? IdlePolicy.Pause,
|
|
860
|
+
autoResume: fields.autoResume ?? true,
|
|
861
|
+
maxLifetime: fields.maxLifetime
|
|
862
|
+
});
|
|
863
|
+
}),
|
|
864
|
+
getNetwork: (id) => withHandle(id, async (handle) => {
|
|
865
|
+
const status = await handle.network.get();
|
|
866
|
+
return {
|
|
867
|
+
network: networkOf(status.policy),
|
|
868
|
+
revision: status.revision == null ? null : String(status.revision)
|
|
869
|
+
};
|
|
870
|
+
}),
|
|
871
|
+
setNetwork: async (id, network, setOptions = {}) => {
|
|
872
|
+
const { expectedRevision } = setOptions;
|
|
873
|
+
const revision = expectedRevision == null ? void 0 : Number(expectedRevision);
|
|
874
|
+
if (revision != null && !Number.isSafeInteger(revision))
|
|
875
|
+
return fail(SandboxRouterErrorCode.InvalidRequest, "not a revision of this provider");
|
|
476
876
|
return withHandle(id, async (handle) => {
|
|
477
|
-
|
|
877
|
+
const fields = networkFields(network);
|
|
878
|
+
let status = await handle.network.set(
|
|
879
|
+
{ ...fields, denyCidrs: [] },
|
|
880
|
+
{ expectedRevision: revision }
|
|
881
|
+
);
|
|
882
|
+
const deadline = clock.now() + SETTLE_TIMEOUT_MS;
|
|
883
|
+
while (!status.applied && clock.now() < deadline) {
|
|
884
|
+
await clock.sleep(SETTLE_POLL_MS);
|
|
885
|
+
status = await handle.network.get();
|
|
886
|
+
}
|
|
887
|
+
if (!status.applied) throw new Error("the network policy was not applied in time");
|
|
478
888
|
});
|
|
479
889
|
},
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
const
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
status = await handle.network.get();
|
|
487
|
-
}
|
|
488
|
-
if (!status.applied) throw new Error("the network policy was not applied in time");
|
|
890
|
+
// Labels merge into the sandbox's; the platform cannot remove one.
|
|
891
|
+
// Replaces the labels. This adapter's `name` label is kept unless the new set names one.
|
|
892
|
+
setLabels: (id, labels) => withHandle(id, async (handle) => {
|
|
893
|
+
const current = await handle.refresh();
|
|
894
|
+
const name = current.labels.name;
|
|
895
|
+
await handle.replaceLabels(name == null || "name" in labels ? labels : { ...labels, name });
|
|
489
896
|
}),
|
|
490
|
-
|
|
491
|
-
id,
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
897
|
+
events: {
|
|
898
|
+
list: (id, listOptions) => withHandle(id, async (handle) => {
|
|
899
|
+
const limit = Math.min(Math.max(listOptions.limit ?? 50, 1), 200);
|
|
900
|
+
const events = await handle.events({ before: listOptions.before, limit });
|
|
901
|
+
return {
|
|
902
|
+
events: events.map((event) => ({
|
|
903
|
+
id: event.id,
|
|
904
|
+
type: "state",
|
|
905
|
+
state: event.state == null ? null : sandboxStateOf(event.state),
|
|
906
|
+
generation: event.generation,
|
|
907
|
+
at: new Date(event.created_at).toISOString(),
|
|
908
|
+
details: {}
|
|
909
|
+
})),
|
|
910
|
+
nextBefore: events.length === limit ? events.at(-1)?.id ?? null : null
|
|
911
|
+
};
|
|
505
912
|
})
|
|
506
|
-
|
|
913
|
+
},
|
|
914
|
+
exec: async (id, command, execOptions) => {
|
|
915
|
+
const result = await withHandle(id, async (handle) => {
|
|
916
|
+
if (execOptions.autoResume === false) {
|
|
917
|
+
const info = await handle.refresh();
|
|
918
|
+
if (info.state !== VmState.Running)
|
|
919
|
+
return fail(
|
|
920
|
+
SandboxRouterErrorCode.InvalidRequest,
|
|
921
|
+
`the sandbox is ${info.state} and the command may not wake it`
|
|
922
|
+
);
|
|
923
|
+
}
|
|
924
|
+
return stream({
|
|
925
|
+
open: (handlers) => handle.exec({
|
|
926
|
+
cmd: command,
|
|
927
|
+
env: execOptions.env,
|
|
928
|
+
cwd: execOptions.cwd,
|
|
929
|
+
user: execOptions.user,
|
|
930
|
+
timeoutMs: execOptions.timeoutMs,
|
|
931
|
+
autoResume: execOptions.autoResume,
|
|
932
|
+
...handlers
|
|
933
|
+
}),
|
|
934
|
+
afterSeq: -1,
|
|
935
|
+
pty: false,
|
|
936
|
+
keepStdin: execOptions.stdin === true,
|
|
937
|
+
signal: execOptions.signal
|
|
938
|
+
});
|
|
939
|
+
});
|
|
940
|
+
return result.ok ? result.value : result;
|
|
941
|
+
},
|
|
507
942
|
attach: (id, processId, { afterSeq }) => withHandle(
|
|
508
943
|
id,
|
|
509
944
|
(handle) => stream({
|
|
@@ -528,15 +963,57 @@ const final = (credentials, options = {}) => {
|
|
|
528
963
|
keepStdin: true
|
|
529
964
|
})
|
|
530
965
|
).then((result) => result.ok ? result.value : result),
|
|
966
|
+
processes: {
|
|
967
|
+
// `user` is null for a uid without a name in the image.
|
|
968
|
+
list: (id, listOptions = {}) => withHandle(id, async (handle) => {
|
|
969
|
+
if (listOptions.autoResume === false) {
|
|
970
|
+
const info = await handle.refresh();
|
|
971
|
+
if (info.state !== VmState.Running)
|
|
972
|
+
return fail(
|
|
973
|
+
SandboxRouterErrorCode.InvalidRequest,
|
|
974
|
+
`the sandbox is ${info.state} and listing its processes may not wake it`
|
|
975
|
+
);
|
|
976
|
+
}
|
|
977
|
+
return ok(
|
|
978
|
+
(await handle.processes({ autoResume: listOptions.autoResume })).map((process) => ({
|
|
979
|
+
processId: process.process_id,
|
|
980
|
+
command: process.cmd,
|
|
981
|
+
args: process.args ?? null,
|
|
982
|
+
cwd: process.cwd ?? null,
|
|
983
|
+
user: process.user ?? null,
|
|
984
|
+
pid: process.pid,
|
|
985
|
+
running: process.state === "running",
|
|
986
|
+
exitCode: process.exit_code ?? null,
|
|
987
|
+
startedAt: millisToIso(process.started_at_ms),
|
|
988
|
+
endedAt: millisToIso(process.ended_at_ms)
|
|
989
|
+
}))
|
|
990
|
+
);
|
|
991
|
+
}).then((result) => result.ok ? result.value : result)
|
|
992
|
+
},
|
|
531
993
|
files: {
|
|
994
|
+
// Reads go through the API, which reads a paused or stopped sandbox's saved disk without
|
|
995
|
+
// waking it, so `autoResume` changes nothing.
|
|
532
996
|
read: (id, path, range) => withHandle(
|
|
533
997
|
id,
|
|
534
998
|
(handle) => handle.files.read(path, { offset: range?.offset, length: range?.length })
|
|
535
999
|
),
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
1000
|
+
// An append keeps the file's mode: the platform appends without one.
|
|
1001
|
+
write: async (id, path, bytes, writeOptions = {}) => {
|
|
1002
|
+
if (writeOptions.append === true && writeOptions.mode != null)
|
|
1003
|
+
return fail(SandboxRouterErrorCode.InvalidRequest, "final cannot set a mode on append");
|
|
1004
|
+
return withHandle(id, async (handle) => {
|
|
1005
|
+
if (writeOptions.append === true) await handle.files.append(path, bytes);
|
|
1006
|
+
else await handle.files.write(path, bytes, { mode: writeOptions.mode });
|
|
1007
|
+
});
|
|
1008
|
+
},
|
|
539
1009
|
list: (id, path) => withHandle(id, async (handle) => (await handle.files.list(path)).entries.map(fileEntry)),
|
|
1010
|
+
listPage: (id, path, pageOptions) => withHandle(id, async (handle) => {
|
|
1011
|
+
const page = await handle.files.listPage(path, {
|
|
1012
|
+
cursor: pageOptions.cursor,
|
|
1013
|
+
limit: pageOptions.limit
|
|
1014
|
+
});
|
|
1015
|
+
return { entries: page.entries.map(fileEntry), nextCursor: page.nextCursor };
|
|
1016
|
+
}),
|
|
540
1017
|
mkdir: (id, path, mkdirOptions) => withHandle(
|
|
541
1018
|
id,
|
|
542
1019
|
(handle) => handle.files.mkdir(path, { parents: mkdirOptions?.recursive ?? true })
|
|
@@ -554,48 +1031,453 @@ const final = (credentials, options = {}) => {
|
|
|
554
1031
|
})
|
|
555
1032
|
},
|
|
556
1033
|
ports: {
|
|
557
|
-
// A
|
|
1034
|
+
// A public port needs nothing; any other answers to a preview token, sent in a header by
|
|
558
1035
|
// programs (a browser opening the URL exchanges it for a session cookie).
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
1036
|
+
// The desktop's editor answers only to a one-time link (its token in the URL, good for a
|
|
1037
|
+
// minute), which starts a 15-minute browser session; `ttlS` does not change either.
|
|
1038
|
+
url: (id, port, urlOptions = {}) => {
|
|
1039
|
+
if (port === COMPUTER_EDITOR_PORT)
|
|
1040
|
+
return Promise.resolve(
|
|
1041
|
+
unsupported(PROVIDER, `port ${COMPUTER_EDITOR_PORT}, which the platform reserves`)
|
|
1042
|
+
);
|
|
1043
|
+
if (port === DESKTOP_EDITOR_PORT)
|
|
1044
|
+
return withHandle(id, async (handle) => {
|
|
1045
|
+
const [base, link] = await Promise.all([
|
|
1046
|
+
handle.previewUrl(port),
|
|
1047
|
+
handle.desktop.editor()
|
|
1048
|
+
]);
|
|
1049
|
+
const url = new URL(base);
|
|
1050
|
+
url.searchParams.set(PREVIEW_TOKEN_QUERY, link.token);
|
|
1051
|
+
return {
|
|
1052
|
+
url: url.toString(),
|
|
1053
|
+
auth: PortAuth.Url,
|
|
1054
|
+
token: link.token,
|
|
1055
|
+
expiresAt: link.expiresAt.toISOString()
|
|
1056
|
+
};
|
|
1057
|
+
});
|
|
1058
|
+
return withHandle(id, async (handle) => {
|
|
1059
|
+
const [published, base] = await Promise.all([
|
|
1060
|
+
handle.listPorts(),
|
|
1061
|
+
handle.previewUrl(port)
|
|
1062
|
+
]);
|
|
1063
|
+
if (published.some((entry) => entry.port === port && entry.public))
|
|
1064
|
+
return { url: base, auth: PortAuth.Public, token: null, expiresAt: null };
|
|
1065
|
+
const token = await mintToken(handle, port, urlOptions.ttlS);
|
|
1066
|
+
const url = new URL(base);
|
|
1067
|
+
url.searchParams.set(PREVIEW_TOKEN_QUERY, token.token);
|
|
1068
|
+
return {
|
|
1069
|
+
url: url.toString(),
|
|
1070
|
+
auth: PortAuth.Header,
|
|
1071
|
+
token: token.token,
|
|
1072
|
+
header: PREVIEW_TOKEN_HEADER,
|
|
1073
|
+
expiresAt: token.expiresAt
|
|
1074
|
+
};
|
|
1075
|
+
});
|
|
1076
|
+
},
|
|
1077
|
+
list: (id) => withHandle(id, (handle) => handle.listPorts()),
|
|
1078
|
+
setPublic: (id, port, isPublic) => withHandle(id, (handle) => handle.setPortPublic(port, isPublic)),
|
|
1079
|
+
createToken: (id, { port, ttlS }) => withHandle(id, async (handle) => {
|
|
1080
|
+
const minted = await mintToken(handle, port, ttlS);
|
|
1081
|
+
const listed = (await previewTokens(handle)).find(
|
|
1082
|
+
(token) => token.port === port && token.expiresAt === minted.expiresAt
|
|
1083
|
+
);
|
|
1084
|
+
if (listed == null) throw new Error("the minted preview token is not listed");
|
|
1085
|
+
return { ...listed, token: minted.token };
|
|
1086
|
+
}),
|
|
1087
|
+
listTokens: (id, listOptions = {}) => withHandle(id, (handle) => previewTokens(handle, listOptions.includeRevoked === true)),
|
|
1088
|
+
revokeToken: (id, tokenId) => withHandle(id, async (handle) => {
|
|
1089
|
+
try {
|
|
1090
|
+
await handle.tokens.revoke(tokenId);
|
|
1091
|
+
} catch (cause) {
|
|
1092
|
+
if (!isMissing(cause)) throw cause;
|
|
1093
|
+
}
|
|
1094
|
+
})
|
|
1095
|
+
},
|
|
1096
|
+
service: {
|
|
1097
|
+
get: (id) => withHandle(id, serviceStatus),
|
|
1098
|
+
update: async (id, spec) => {
|
|
1099
|
+
if (spec == null) return withHandle(id, (handle) => handle.workload.set(STOPPED_WORKLOAD));
|
|
1100
|
+
const service = serviceWorkload(spec);
|
|
1101
|
+
if (!service.ok) return fail(SandboxRouterErrorCode.InvalidRequest, service.reason);
|
|
1102
|
+
return withHandle(id, (handle) => handle.workload.set(service.workload));
|
|
1103
|
+
},
|
|
1104
|
+
// Setting the workload again restarts it.
|
|
1105
|
+
restart: async (id) => {
|
|
1106
|
+
const result = await withHandle(id, async (handle) => {
|
|
1107
|
+
const current = await handle.workload.get();
|
|
1108
|
+
if (current.workload == null || isStoppedWorkload(current.workload))
|
|
1109
|
+
return fail(SandboxRouterErrorCode.NotFound, "the sandbox has no service");
|
|
1110
|
+
await handle.workload.set(current.workload);
|
|
1111
|
+
return ok(void 0);
|
|
1112
|
+
});
|
|
1113
|
+
return result.ok ? result.value : result;
|
|
1114
|
+
}
|
|
1115
|
+
},
|
|
1116
|
+
volumes: {
|
|
1117
|
+
create: (args) => call(
|
|
1118
|
+
async () => volumeOf(
|
|
1119
|
+
await client.volumes.create({
|
|
1120
|
+
name: args.name,
|
|
1121
|
+
sizeGb: args.sizeGib ?? DEFAULT_VOLUME_GIB,
|
|
1122
|
+
expiresAfterUnusedS: args.expiresAfterUnusedS,
|
|
1123
|
+
labels: args.labels
|
|
1124
|
+
})
|
|
1125
|
+
)
|
|
1126
|
+
),
|
|
1127
|
+
get: (volumeId) => orNull(async () => {
|
|
1128
|
+
const volume = volumeOf(await client.volumes.get(volumeId));
|
|
1129
|
+
if (volume.state === VolumeState.Deleted) {
|
|
1130
|
+
const missing = Object.assign(new Error("deleted"), { status: 404 });
|
|
1131
|
+
throw missing;
|
|
1132
|
+
}
|
|
1133
|
+
return volume;
|
|
1134
|
+
}).then(
|
|
1135
|
+
(result) => (
|
|
1136
|
+
// A volume being deleted reads as gone.
|
|
1137
|
+
!result.ok && result.error.message === "deleted" ? ok(null) : result
|
|
1138
|
+
)
|
|
1139
|
+
),
|
|
1140
|
+
list: async ({ labels, name }) => {
|
|
1141
|
+
const filter = labelFilter(labels);
|
|
1142
|
+
if (!filter.ok) return filter;
|
|
1143
|
+
return call(
|
|
1144
|
+
async () => (await client.volumes.list({ labels })).map(volumeOf).filter(
|
|
1145
|
+
(volume) => volume.state !== VolumeState.Deleted && (name == null || volume.name === name)
|
|
1146
|
+
)
|
|
1147
|
+
);
|
|
1148
|
+
},
|
|
1149
|
+
delete: async (volumeId) => {
|
|
1150
|
+
const deleted = await orNull(() => client.volumes.delete(volumeId));
|
|
1151
|
+
return deleted.ok ? ok(void 0) : deleted;
|
|
1152
|
+
},
|
|
1153
|
+
// Attaching the same volume at the same path again succeeds. The platform attaches a volume
|
|
1154
|
+
// once per sandbox.
|
|
1155
|
+
attach: (sandboxId, mount) => withHandle(sandboxId, async (handle) => {
|
|
1156
|
+
const attached = (await handle.refresh()).volumes.some(
|
|
1157
|
+
(volume) => volume.volumeId === mount.volumeId && volume.path === mount.path && (volume.state === "attached" || volume.state === "attaching")
|
|
1158
|
+
);
|
|
1159
|
+
if (attached) return;
|
|
1160
|
+
await handle.volumes.attach({
|
|
1161
|
+
volumeId: mount.volumeId,
|
|
1162
|
+
path: mount.path,
|
|
1163
|
+
allowCommit: !mount.readOnly && mount.allowCommit !== false
|
|
1164
|
+
});
|
|
1165
|
+
}),
|
|
1166
|
+
detach: (sandboxId, volumeId) => withHandle(sandboxId, async (handle) => {
|
|
1167
|
+
try {
|
|
1168
|
+
await handle.volumes.detach(volumeId);
|
|
1169
|
+
} catch (cause) {
|
|
1170
|
+
if (!isMissing(cause)) throw cause;
|
|
1171
|
+
}
|
|
1172
|
+
}),
|
|
1173
|
+
mounts: (sandboxId) => withHandle(
|
|
1174
|
+
sandboxId,
|
|
1175
|
+
async (handle) => (await handle.refresh()).volumes.filter((volume) => volume.state !== "detached" && volume.state !== "detaching").map((volume) => ({
|
|
1176
|
+
volumeId: volume.volumeId,
|
|
1177
|
+
path: volume.path,
|
|
1178
|
+
readOnly: !volume.allowCommit,
|
|
1179
|
+
allowCommit: volume.allowCommit
|
|
1180
|
+
}))
|
|
1181
|
+
),
|
|
1182
|
+
commit: (sandboxId, volumeId) => withHandle(sandboxId, (handle) => handle.volumes.commit(volumeId)),
|
|
1183
|
+
commitStatus: (volumeId, commitId) => call(async () => {
|
|
1184
|
+
const commit = await client.volumes.commit(volumeId, commitId);
|
|
1185
|
+
return {
|
|
1186
|
+
state: commit.state === "committed" ? "committed" : commit.state === "pending" ? "pending" : "failed",
|
|
1187
|
+
version: commit.version
|
|
1188
|
+
};
|
|
1189
|
+
})
|
|
1190
|
+
},
|
|
1191
|
+
// Points start at `from`, one per bucket, rounded up to whole minutes (the platform's usage
|
|
1192
|
+
// windows); the platform answers at most 1,440 points and reaches 30 days back.
|
|
1193
|
+
metrics: async (id, { from, to, bucketS }) => {
|
|
1194
|
+
const step = metricsStep(bucketS);
|
|
1195
|
+
if (!step.ok) return step;
|
|
1196
|
+
return withHandle(
|
|
1197
|
+
id,
|
|
1198
|
+
async (handle) => metricPoints(
|
|
1199
|
+
await handle.metrics({ from: Date.parse(from), to: Date.parse(to), stepS: step.value })
|
|
1200
|
+
)
|
|
1201
|
+
);
|
|
1202
|
+
},
|
|
1203
|
+
charges: (id, { from, to }) => withHandle(id, async (handle) => {
|
|
1204
|
+
const answer = await handle.charges({ from: Date.parse(from), to: Date.parse(to) });
|
|
1205
|
+
return { lines: chargeLines(answer), settled: answer.settled };
|
|
1206
|
+
}),
|
|
1207
|
+
// Claims are platform ingress routes, found by hostname.
|
|
1208
|
+
ingress: {
|
|
1209
|
+
claim: ({ hostname, port, targetLabels, prepareOnly }) => call(
|
|
1210
|
+
async () => claimOf(
|
|
1211
|
+
await client.ingressRoutes.create({
|
|
1212
|
+
hostname,
|
|
1213
|
+
port,
|
|
1214
|
+
selector: prepareOnly === true ? null : targetLabels
|
|
1215
|
+
})
|
|
1216
|
+
)
|
|
1217
|
+
),
|
|
1218
|
+
// One compare-and-set at the revision read.
|
|
1219
|
+
retarget: async (hostname, { port, targetLabels }) => {
|
|
1220
|
+
const found = await call(() => routeOf(hostname));
|
|
1221
|
+
if (!found.ok) return found;
|
|
1222
|
+
const route = found.value;
|
|
1223
|
+
if (route == null) return fail(SandboxRouterErrorCode.NotFound, `no claim of ${hostname}`);
|
|
1224
|
+
return call(
|
|
1225
|
+
async () => claimOf(
|
|
1226
|
+
await client.ingressRoutes.update(route.id, {
|
|
1227
|
+
selector: targetLabels,
|
|
1228
|
+
port,
|
|
1229
|
+
expectedRevision: route.revision
|
|
1230
|
+
})
|
|
1231
|
+
)
|
|
1232
|
+
);
|
|
1233
|
+
},
|
|
1234
|
+
release: (hostname) => call(async () => {
|
|
1235
|
+
const route = await routeOf(hostname);
|
|
1236
|
+
if (route == null) return;
|
|
1237
|
+
try {
|
|
1238
|
+
await client.ingressRoutes.delete(route.id);
|
|
1239
|
+
} catch (cause) {
|
|
1240
|
+
if (!isMissing(cause)) throw cause;
|
|
1241
|
+
}
|
|
1242
|
+
}),
|
|
1243
|
+
get: (hostname) => call(async () => {
|
|
1244
|
+
const route = await routeOf(hostname);
|
|
1245
|
+
return route == null ? null : claimOf(route);
|
|
1246
|
+
}),
|
|
1247
|
+
list: async ({ labels }) => {
|
|
1248
|
+
const filter = labelFilter(labels);
|
|
1249
|
+
if (!filter.ok) return filter;
|
|
1250
|
+
return call(async () => (await client.ingressRoutes.list({ labels })).map(claimOf));
|
|
1251
|
+
}
|
|
1252
|
+
},
|
|
1253
|
+
caches: {
|
|
1254
|
+
// The platform pages by the last key; the cursor carries it.
|
|
1255
|
+
list: async ({ scopePrefix, cursor, limit }) => {
|
|
1256
|
+
if (scopePrefix.includes(CACHE_SEPARATOR))
|
|
1257
|
+
return fail(SandboxRouterErrorCode.InvalidRequest, "cache scopes cannot hold U+001F");
|
|
1258
|
+
const after = cursor == null ? void 0 : Buffer.from(cursor, "base64url").toString("utf8");
|
|
1259
|
+
if (after != null && !after.startsWith(scopePrefix))
|
|
1260
|
+
return fail(SandboxRouterErrorCode.InvalidRequest, "the cursor is for another listing");
|
|
1261
|
+
return call(async () => {
|
|
1262
|
+
const page = await client.caches.list({
|
|
1263
|
+
namespace: CACHE_NAMESPACE,
|
|
1264
|
+
prefix: scopePrefix,
|
|
1265
|
+
after,
|
|
1266
|
+
limit: Math.min(Math.max(Math.round(limit ?? CACHE_LIST_LIMIT), 1), CACHE_LIST_MAX)
|
|
1267
|
+
});
|
|
1268
|
+
return {
|
|
1269
|
+
entries: page.objects.flatMap((object) => {
|
|
1270
|
+
const named = routerKey(object);
|
|
1271
|
+
return named == null ? [] : [
|
|
1272
|
+
{
|
|
1273
|
+
id: object.id,
|
|
1274
|
+
...named,
|
|
1275
|
+
sizeBytes: object.size_bytes ?? 0,
|
|
1276
|
+
createdAt: object.created_at ?? null
|
|
1277
|
+
}
|
|
1278
|
+
];
|
|
1279
|
+
}),
|
|
1280
|
+
nextCursor: page.next == null ? null : Buffer.from(page.next, "utf8").toString("base64url")
|
|
1281
|
+
};
|
|
1282
|
+
});
|
|
1283
|
+
},
|
|
1284
|
+
delete: async (entryId) => {
|
|
1285
|
+
const deleted = await orNull(() => client.caches.delete(entryId));
|
|
1286
|
+
return deleted.ok ? ok(void 0) : deleted;
|
|
1287
|
+
},
|
|
1288
|
+
lookup: async ({ candidates }) => {
|
|
1289
|
+
const stored = [];
|
|
1290
|
+
for (const candidate of candidates) {
|
|
1291
|
+
const key = storedKey(candidate.scope, candidate.key);
|
|
1292
|
+
if (!key.ok) return key;
|
|
1293
|
+
stored.push({ namespace: CACHE_NAMESPACE, key: key.value, prefix: candidate.prefix });
|
|
1294
|
+
}
|
|
1295
|
+
return call(() => readCache(stored));
|
|
1296
|
+
},
|
|
1297
|
+
// A key's object can be replaced; the old one's URL is no longer handed out.
|
|
1298
|
+
get: (entryId) => orNull(async () => {
|
|
1299
|
+
const object = await client.caches.get(entryId);
|
|
1300
|
+
if (object.state !== "ready" || routerKey(object) == null) return null;
|
|
1301
|
+
const entry = await readCache([
|
|
1302
|
+
{ namespace: object.namespace, key: object.key, prefix: false }
|
|
563
1303
|
]);
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
const
|
|
568
|
-
|
|
1304
|
+
return entry?.id === entryId ? entry : null;
|
|
1305
|
+
}).then((result) => result.ok ? ok(result.value ?? null) : result),
|
|
1306
|
+
startUpload: async ({ scope, key, partCount }) => {
|
|
1307
|
+
const stored = storedKey(scope, key);
|
|
1308
|
+
if (!stored.ok) return stored;
|
|
1309
|
+
return call(async () => {
|
|
1310
|
+
const started = await client.caches.start({
|
|
1311
|
+
namespace: CACHE_NAMESPACE,
|
|
1312
|
+
key: stored.value,
|
|
1313
|
+
partCount
|
|
1314
|
+
});
|
|
1315
|
+
const parts = partsWithExpiry(started.parts);
|
|
1316
|
+
const expiries = parts.flatMap(
|
|
1317
|
+
(part) => part.expiresAt == null ? [] : [part.expiresAt]
|
|
1318
|
+
);
|
|
1319
|
+
return {
|
|
1320
|
+
uploadId: started.object.id,
|
|
1321
|
+
parts,
|
|
1322
|
+
expiresAt: expiries.length === parts.length ? expiries.sort()[0] ?? null : null
|
|
1323
|
+
};
|
|
1324
|
+
});
|
|
1325
|
+
},
|
|
1326
|
+
partUrls: ({ uploadId, partNumbers }) => call(async () => partsWithExpiry(await client.caches.parts(uploadId, partNumbers))),
|
|
1327
|
+
completeUpload: ({ uploadId, parts }) => call(async () => {
|
|
1328
|
+
const object = await client.caches.complete(uploadId, parts);
|
|
1329
|
+
const entry = await readCache([
|
|
1330
|
+
{ namespace: object.namespace, key: object.key, prefix: false }
|
|
1331
|
+
]);
|
|
1332
|
+
if (entry?.id !== object.id) throw new Error("the completed object is not readable");
|
|
1333
|
+
return entry;
|
|
1334
|
+
})
|
|
1335
|
+
},
|
|
1336
|
+
desktop: {
|
|
1337
|
+
// Resolves once the desktop runs.
|
|
1338
|
+
start: (id) => withHandle(id, async (handle) => {
|
|
1339
|
+
let status = await handle.desktop.start();
|
|
1340
|
+
const deadline = clock.now() + DESKTOP_START_TIMEOUT_MS;
|
|
1341
|
+
while (status.state !== "running") {
|
|
1342
|
+
if (clock.now() >= deadline)
|
|
1343
|
+
throw Object.assign(new Error(`the desktop is still ${status.state}`), {
|
|
1344
|
+
name: "TimeoutError"
|
|
1345
|
+
});
|
|
1346
|
+
await clock.sleep(DESKTOP_POLL_MS);
|
|
1347
|
+
status = await handle.desktop.status();
|
|
1348
|
+
}
|
|
1349
|
+
return desktopStatus(status);
|
|
1350
|
+
}),
|
|
1351
|
+
stop: (id) => withHandle(id, (handle) => handle.desktop.stop()),
|
|
1352
|
+
status: (id) => withHandle(id, async (handle) => desktopStatus(await handle.desktop.status())),
|
|
1353
|
+
// The platform's viewer page when it has one; otherwise the screen's WebRTC signalling
|
|
1354
|
+
// socket, which takes the token as its subprotocol.
|
|
1355
|
+
screen: (id, screenOptions) => withHandle(id, async (handle) => {
|
|
1356
|
+
const screen = await handle.desktop.screen({
|
|
1357
|
+
viewOnly: screenOptions?.viewOnly ?? false
|
|
1358
|
+
});
|
|
1359
|
+
const expiresAt = new Date(screen.connect.expires_at).toISOString();
|
|
1360
|
+
if (screen.viewer_url != null)
|
|
1361
|
+
return {
|
|
1362
|
+
protocol: "url",
|
|
1363
|
+
url: screen.viewer_url,
|
|
1364
|
+
token: null,
|
|
1365
|
+
expiresAt,
|
|
1366
|
+
details: { viewOnly: String(screen.view_only) }
|
|
1367
|
+
};
|
|
1368
|
+
const origin = ingressOrigin(screen.connect.endpoint).replace(/^http/, "ws");
|
|
569
1369
|
return {
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
token:
|
|
573
|
-
|
|
574
|
-
|
|
1370
|
+
protocol: "webrtc",
|
|
1371
|
+
url: `${origin}/v1/sandboxes/${grantSandboxUuid(screen.connect.token)}/screen`,
|
|
1372
|
+
token: screen.connect.token,
|
|
1373
|
+
expiresAt,
|
|
1374
|
+
details: {
|
|
1375
|
+
viewOnly: String(screen.view_only),
|
|
1376
|
+
iceServers: JSON.stringify(screen.ice_servers ?? [])
|
|
1377
|
+
}
|
|
1378
|
+
};
|
|
1379
|
+
})
|
|
1380
|
+
},
|
|
1381
|
+
computerUse: {
|
|
1382
|
+
screenshot: (id) => withHandle(id, async (handle) => {
|
|
1383
|
+
const shot = await capture(handle, SCREENSHOT_COMMAND);
|
|
1384
|
+
if (shot.exitCode !== 0) throw new Error(`the screenshot failed: ${shot.stderr}`);
|
|
1385
|
+
return shot.stdout;
|
|
1386
|
+
}),
|
|
1387
|
+
act: async (id, action) => {
|
|
1388
|
+
const command = xdotoolCommand(action);
|
|
1389
|
+
if (command == null) return fail(SandboxRouterErrorCode.InvalidRequest, "an empty action");
|
|
1390
|
+
return withHandle(id, async (handle) => {
|
|
1391
|
+
const done = await capture(handle, command);
|
|
1392
|
+
if (done.exitCode !== 0) throw new Error(`the input failed: ${done.stderr}`);
|
|
1393
|
+
});
|
|
1394
|
+
}
|
|
1395
|
+
},
|
|
1396
|
+
domains: {
|
|
1397
|
+
// The platform serves a custom domain only for a public port: adding one makes the port
|
|
1398
|
+
// public.
|
|
1399
|
+
add: (id, { hostname, port }) => withHandle(id, async (handle) => {
|
|
1400
|
+
const published = await handle.listPorts();
|
|
1401
|
+
if (!published.some((entry) => entry.port === port && entry.public))
|
|
1402
|
+
await handle.setPortPublic(port, true);
|
|
1403
|
+
const added = await handle.domains.add(hostname, port);
|
|
1404
|
+
const listed = await domainsOf(handle);
|
|
1405
|
+
return listed.find((domain) => domain.hostname === added.domain) ?? {
|
|
1406
|
+
hostname: added.domain,
|
|
1407
|
+
port: added.port,
|
|
1408
|
+
state: domainState(added.status),
|
|
1409
|
+
records: [],
|
|
1410
|
+
error: added.error,
|
|
1411
|
+
createdAt: millisToIso(added.created_at)
|
|
575
1412
|
};
|
|
1413
|
+
}),
|
|
1414
|
+
list: (id) => withHandle(id, domainsOf),
|
|
1415
|
+
remove: (id, hostname) => withHandle(id, async (handle) => {
|
|
1416
|
+
const found = (await handle.domains.list()).domains.find(
|
|
1417
|
+
(domain) => domain.domain === hostname.toLowerCase()
|
|
1418
|
+
);
|
|
1419
|
+
if (found == null) return;
|
|
1420
|
+
try {
|
|
1421
|
+
await handle.domains.remove(found.id);
|
|
1422
|
+
} catch (cause) {
|
|
1423
|
+
if (!isMissing(cause)) throw cause;
|
|
1424
|
+
}
|
|
576
1425
|
})
|
|
577
1426
|
},
|
|
578
|
-
|
|
1427
|
+
// Named snapshots are kept until deleted, so `retain` needs nothing more.
|
|
1428
|
+
snapshot: (id, { name, labels }) => withHandle(id, async (handle) => {
|
|
579
1429
|
try {
|
|
580
|
-
return await handle.checkpoint({ name });
|
|
1430
|
+
return await handle.checkpoint({ name, labels });
|
|
581
1431
|
} catch (cause) {
|
|
582
1432
|
if (!(isVmError(cause) && cause.code === "name_taken")) throw cause;
|
|
583
1433
|
const earlier = (await client.snapshots.list()).find(
|
|
584
1434
|
(snapshot) => snapshot.name === name && snapshot.sandboxId === id
|
|
585
1435
|
);
|
|
586
1436
|
if (earlier != null) return { snapshotId: earlier.id };
|
|
587
|
-
return handle.checkpoint({ name: `${name}-${crypto.randomUUID().slice(0, 8)}
|
|
1437
|
+
return handle.checkpoint({ name: `${name}-${crypto.randomUUID().slice(0, 8)}`, labels });
|
|
588
1438
|
}
|
|
589
1439
|
}),
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
if (
|
|
596
|
-
return
|
|
1440
|
+
snapshots: {
|
|
1441
|
+
get: (snapshotId) => orNull(async () => vendorSnapshot(await client.snapshots.get(snapshotId))),
|
|
1442
|
+
// Named snapshots carrying every label.
|
|
1443
|
+
list: async ({ labels }) => {
|
|
1444
|
+
const filter = labelFilter(labels);
|
|
1445
|
+
if (!filter.ok) return filter;
|
|
1446
|
+
return call(
|
|
1447
|
+
async () => (await client.snapshots.list({ labels })).filter((snapshot) => snapshot.kind === "checkpoint").map(vendorSnapshot)
|
|
1448
|
+
);
|
|
597
1449
|
}
|
|
598
1450
|
},
|
|
1451
|
+
// The platform changes size only while the sandbox is stopped: a running sandbox restarts
|
|
1452
|
+
// (its memory is lost, its files kept) and a paused one is left stopped.
|
|
1453
|
+
resize: (id, size) => withHandle(id, async (handle) => {
|
|
1454
|
+
const before = await handle.refresh();
|
|
1455
|
+
if (size.diskGib != null && size.diskGib < before.diskGb)
|
|
1456
|
+
return fail(SandboxRouterErrorCode.InvalidRequest, "disks only grow");
|
|
1457
|
+
const info = await whileStopped(
|
|
1458
|
+
handle,
|
|
1459
|
+
() => handle.updateSettings({
|
|
1460
|
+
size: {
|
|
1461
|
+
cpu: [size.cpu, Math.max(size.cpuLimit ?? size.cpu, size.cpu)],
|
|
1462
|
+
memory: [
|
|
1463
|
+
size.memoryMib,
|
|
1464
|
+
Math.max(size.memoryLimitMib ?? size.memoryMib, size.memoryMib)
|
|
1465
|
+
],
|
|
1466
|
+
diskGb: size.diskGib
|
|
1467
|
+
}
|
|
1468
|
+
})
|
|
1469
|
+
);
|
|
1470
|
+
const granted = toVendor(info).granted;
|
|
1471
|
+
return granted == null ? fail(SandboxRouterErrorCode.ProviderError, "final reported no size") : ok(granted);
|
|
1472
|
+
}).then((result) => result.ok ? result.value : result),
|
|
1473
|
+
// The boot environment, so the sandbox restarts as for `resize`.
|
|
1474
|
+
setEnv: (id, env) => withHandle(id, async (handle) => {
|
|
1475
|
+
await whileStopped(handle, () => handle.updateSettings({ env }));
|
|
1476
|
+
}),
|
|
1477
|
+
deleteSnapshot: async (snapshotId) => {
|
|
1478
|
+
const deleted = await orNull(() => client.snapshots.delete(snapshotId));
|
|
1479
|
+
return deleted.ok ? ok(void 0) : deleted;
|
|
1480
|
+
},
|
|
599
1481
|
fork: (id, { count, labels, name }) => withHandle(id, async (handle) => {
|
|
600
1482
|
const { children } = await handle.fork(count);
|
|
601
1483
|
return Promise.all(
|
|
@@ -608,36 +1490,50 @@ const final = (credentials, options = {}) => {
|
|
|
608
1490
|
}),
|
|
609
1491
|
image: {
|
|
610
1492
|
strategy: imageStrategy,
|
|
611
|
-
build: (spec, buildContext) =>
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
1493
|
+
build: async (spec, buildContext) => {
|
|
1494
|
+
const parsed = parseOptions(buildContext.providerOptions);
|
|
1495
|
+
if (!parsed.ok) return parsed;
|
|
1496
|
+
const built = await call(
|
|
1497
|
+
() => buildImage(
|
|
1498
|
+
{ client, clock, signal: buildContext.signal, onLog: buildContext.onLog },
|
|
1499
|
+
spec,
|
|
1500
|
+
{ resources: buildContext.resources ?? null, tools: parsed.value.tools ?? [] }
|
|
1501
|
+
)
|
|
1502
|
+
);
|
|
1503
|
+
return built.ok ? built.value : built;
|
|
1504
|
+
},
|
|
617
1505
|
remove: async (artifact) => {
|
|
618
|
-
|
|
1506
|
+
const removed = await orNull(async () => {
|
|
619
1507
|
if (artifact.kind === "template") await client.templates.delete(artifact.id);
|
|
620
1508
|
else if (artifact.kind === "snapshot") await client.snapshots.delete(artifact.id);
|
|
621
1509
|
else await client.images.delete(artifact.id);
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
if (isMissing(cause)) return ok(void 0);
|
|
625
|
-
return failure(cause);
|
|
626
|
-
}
|
|
1510
|
+
});
|
|
1511
|
+
return removed.ok ? ok(void 0) : removed;
|
|
627
1512
|
}
|
|
628
1513
|
},
|
|
629
|
-
connect:
|
|
630
|
-
const
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
1514
|
+
connect: async (id, connectOptions = {}) => {
|
|
1515
|
+
const { scopes, ttlS } = connectOptions;
|
|
1516
|
+
if (ttlS != null && (ttlS < GRANT_MIN_TTL_S || ttlS > GRANT_MAX_TTL_S))
|
|
1517
|
+
return fail(
|
|
1518
|
+
SandboxRouterErrorCode.InvalidRequest,
|
|
1519
|
+
`a grant lasts ${GRANT_MIN_TTL_S} s to ${GRANT_MAX_TTL_S} s`
|
|
1520
|
+
);
|
|
1521
|
+
return withHandle(id, async (handle) => {
|
|
1522
|
+
const grant = await handle.connect({
|
|
1523
|
+
scopes: scopes == null ? void 0 : [...new Set(scopes.map(platformScope))],
|
|
1524
|
+
ttlS: ttlS == null ? void 0 : Math.round(ttlS)
|
|
1525
|
+
});
|
|
1526
|
+
return {
|
|
1527
|
+
provider: PROVIDER,
|
|
1528
|
+
providerSandboxId: id,
|
|
1529
|
+
kind: "grant",
|
|
1530
|
+
token: grant.token,
|
|
1531
|
+
url: grant.endpoint.includes("://") ? grant.endpoint : `https://${grant.endpoint}`,
|
|
1532
|
+
expiresAt: new Date(grant.expiresAt).toISOString(),
|
|
1533
|
+
details: { generation: String(grant.generation) }
|
|
1534
|
+
};
|
|
1535
|
+
});
|
|
1536
|
+
}
|
|
641
1537
|
});
|
|
642
1538
|
};
|
|
643
1539
|
export {
|