@finalai/sandbox-router-final 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +38 -2
- package/dist/modules/frames.d.mts +18 -0
- package/dist/modules/frames.mjs +98 -0
- package/dist/modules/frames.mjs.map +7 -0
- package/dist/modules/images.d.mts +15 -0
- package/dist/modules/images.mjs +116 -0
- package/dist/modules/images.mjs.map +7 -0
- package/dist/modules/index.d.mts +4 -0
- package/dist/modules/index.mjs +16 -0
- package/dist/modules/index.mjs.map +7 -0
- package/dist/modules/limits.d.mts +6 -0
- package/dist/modules/limits.mjs +37 -0
- package/dist/modules/limits.mjs.map +7 -0
- package/dist/modules/options.d.mts +24 -0
- package/dist/modules/options.mjs +19 -0
- package/dist/modules/options.mjs.map +7 -0
- package/dist/modules/provider.d.mts +5 -0
- package/dist/modules/provider.mjs +654 -0
- package/dist/modules/provider.mjs.map +7 -0
- package/dist/modules/vm/api.d.mts +28 -0
- package/dist/modules/vm/api.mjs +94 -0
- package/dist/modules/vm/api.mjs.map +7 -0
- package/dist/modules/vm/client.d.mts +104 -0
- package/dist/modules/vm/client.mjs +186 -0
- package/dist/modules/vm/client.mjs.map +7 -0
- package/dist/modules/vm/clock.d.mts +5 -0
- package/dist/modules/vm/clock.mjs +11 -0
- package/dist/modules/vm/clock.mjs.map +7 -0
- package/dist/modules/vm/errors.d.mts +23 -0
- package/dist/modules/vm/errors.mjs +30 -0
- package/dist/modules/vm/errors.mjs.map +7 -0
- package/dist/modules/vm/exec.d.mts +47 -0
- package/dist/modules/vm/exec.mjs +292 -0
- package/dist/modules/vm/exec.mjs.map +7 -0
- package/dist/modules/vm/files.d.mts +18 -0
- package/dist/modules/vm/files.mjs +160 -0
- package/dist/modules/vm/files.mjs.map +7 -0
- package/dist/modules/vm/grants.d.mts +35 -0
- package/dist/modules/vm/grants.mjs +106 -0
- package/dist/modules/vm/grants.mjs.map +7 -0
- package/dist/modules/vm/ids.d.mts +3 -0
- package/dist/modules/vm/ids.mjs +35 -0
- package/dist/modules/vm/ids.mjs.map +7 -0
- package/dist/modules/vm/ingress.d.mts +99 -0
- package/dist/modules/vm/ingress.mjs +263 -0
- package/dist/modules/vm/ingress.mjs.map +7 -0
- package/dist/modules/vm/machines.d.mts +82 -0
- package/dist/modules/vm/machines.mjs +62 -0
- package/dist/modules/vm/machines.mjs.map +7 -0
- package/dist/modules/vm/network.d.mts +17 -0
- package/dist/modules/vm/network.mjs +44 -0
- package/dist/modules/vm/network.mjs.map +7 -0
- package/dist/modules/vm/sandbox.d.mts +75 -0
- package/dist/modules/vm/sandbox.mjs +175 -0
- package/dist/modules/vm/sandbox.mjs.map +7 -0
- package/dist/modules/vm/schemas.d.mts +1209 -0
- package/dist/modules/vm/schemas.mjs +289 -0
- package/dist/modules/vm/schemas.mjs.map +7 -0
- package/dist/modules/vm/wire.d.mts +3 -0
- package/dist/modules/vm/wire.mjs +9 -0
- package/dist/modules/vm/wire.mjs.map +7 -0
- package/dist/modules/vm/workload.d.mts +14 -0
- package/dist/modules/vm/workload.mjs +11 -0
- package/dist/modules/vm/workload.mjs.map +7 -0
- package/package.json +38 -4
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AtEnd,
|
|
3
|
+
attempt,
|
|
4
|
+
defineProvider,
|
|
5
|
+
EgressMode,
|
|
6
|
+
ExitReason,
|
|
7
|
+
fail,
|
|
8
|
+
failFromStatus,
|
|
9
|
+
FileKind,
|
|
10
|
+
fitWithinLimits,
|
|
11
|
+
canonicalJson,
|
|
12
|
+
formatUsd,
|
|
13
|
+
sha256Hex,
|
|
14
|
+
HardwareConfidence,
|
|
15
|
+
isEgressAllowList,
|
|
16
|
+
ok,
|
|
17
|
+
PauseKeep,
|
|
18
|
+
PortAuth,
|
|
19
|
+
ProcessFrameKind,
|
|
20
|
+
ProcessSignal,
|
|
21
|
+
BillingModel,
|
|
22
|
+
SandboxRouterErrorCode,
|
|
23
|
+
SandboxState,
|
|
24
|
+
shellQuote,
|
|
25
|
+
SPECIFICATION_VERSION,
|
|
26
|
+
toNanos,
|
|
27
|
+
unsupported
|
|
28
|
+
} from "@finalai/sandbox-router/provider";
|
|
29
|
+
import { capabilities, DEFAULT_DISK_GIB, limits, PROVIDER, regions } from "./limits.mjs";
|
|
30
|
+
import { createSeqFrames } from "./frames.mjs";
|
|
31
|
+
import { baseReference, buildImage, ensureImage, imageStrategy } from "./images.mjs";
|
|
32
|
+
import {
|
|
33
|
+
finalOptionsSchema
|
|
34
|
+
} from "./options.mjs";
|
|
35
|
+
import {
|
|
36
|
+
createVmClient,
|
|
37
|
+
SourceKind
|
|
38
|
+
} from "./vm/client.mjs";
|
|
39
|
+
import { systemClock } from "./vm/clock.mjs";
|
|
40
|
+
import { isVmError } from "./vm/errors.mjs";
|
|
41
|
+
import { SandboxState as VmState } from "./vm/schemas.mjs";
|
|
42
|
+
import { PREVIEW_TOKEN_HEADER, PREVIEW_TOKEN_QUERY } from "./vm/wire.mjs";
|
|
43
|
+
const REGION = regions[0] ?? "us-west";
|
|
44
|
+
const SETTLE_TIMEOUT_MS = 5 * 6e4;
|
|
45
|
+
const SETTLE_POLL_MS = 500;
|
|
46
|
+
const LIST_PAGE = 200;
|
|
47
|
+
const PREVIEW_TOKEN_TTL_S = 86400;
|
|
48
|
+
const MAX_CACHED_HANDLES = 1e3;
|
|
49
|
+
const HOURS_PER_MONTH = 730;
|
|
50
|
+
const STATES = {
|
|
51
|
+
[VmState.Creating]: SandboxState.Creating,
|
|
52
|
+
[VmState.Running]: SandboxState.Running,
|
|
53
|
+
[VmState.Starting]: SandboxState.Creating,
|
|
54
|
+
[VmState.Resuming]: SandboxState.Creating,
|
|
55
|
+
[VmState.Pausing]: SandboxState.Paused,
|
|
56
|
+
[VmState.Paused]: SandboxState.Paused,
|
|
57
|
+
[VmState.Stopping]: SandboxState.Stopped,
|
|
58
|
+
[VmState.Stopped]: SandboxState.Stopped,
|
|
59
|
+
[VmState.Deleting]: SandboxState.Deleted,
|
|
60
|
+
[VmState.Deleted]: SandboxState.Deleted,
|
|
61
|
+
[VmState.Failed]: SandboxState.Failed
|
|
62
|
+
};
|
|
63
|
+
const sandboxStateOf = (native) => STATES[native] ?? SandboxState.Unknown;
|
|
64
|
+
const GONE = /* @__PURE__ */ new Set([VmState.Deleting, VmState.Deleted]);
|
|
65
|
+
const toVendor = (info) => ({
|
|
66
|
+
providerSandboxId: info.id,
|
|
67
|
+
region: REGION,
|
|
68
|
+
state: sandboxStateOf(info.state),
|
|
69
|
+
nativeState: info.state,
|
|
70
|
+
nativeError: info.state === VmState.Failed ? info.interruption?.reason ?? info.recovery?.reason ?? null : null,
|
|
71
|
+
labels: info.labels,
|
|
72
|
+
createdAt: info.createdAt.toISOString(),
|
|
73
|
+
granted: {
|
|
74
|
+
cpu: info.cpu?.request ?? info.vcpu,
|
|
75
|
+
memoryMib: info.memory?.request ?? info.memoryMb,
|
|
76
|
+
diskGib: info.diskGb
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
const SIGNALS = {
|
|
80
|
+
[ProcessSignal.Hup]: 1,
|
|
81
|
+
[ProcessSignal.Int]: 2,
|
|
82
|
+
[ProcessSignal.Kill]: 9,
|
|
83
|
+
[ProcessSignal.Term]: 15
|
|
84
|
+
};
|
|
85
|
+
const signalName = (signal) => {
|
|
86
|
+
if (signal == null) return null;
|
|
87
|
+
const known = Object.entries(SIGNALS).find(([, number]) => number === signal);
|
|
88
|
+
return known?.[0] ?? `SIG${signal}`;
|
|
89
|
+
};
|
|
90
|
+
const fileKind = (kind) => kind === "file" ? FileKind.File : kind === "directory" ? FileKind.Directory : kind === "symlink" ? FileKind.Symlink : FileKind.Other;
|
|
91
|
+
const fileEntry = (stat) => ({
|
|
92
|
+
name: stat.path.split("/").filter((part) => part !== "").at(-1) ?? "/",
|
|
93
|
+
path: stat.path,
|
|
94
|
+
kind: fileKind(stat.kind),
|
|
95
|
+
size: stat.size,
|
|
96
|
+
modifiedAt: Number.isNaN(stat.modifiedAt.getTime()) ? null : stat.modifiedAt.toISOString(),
|
|
97
|
+
mode: stat.mode & 4095
|
|
98
|
+
});
|
|
99
|
+
const classify = (cause) => {
|
|
100
|
+
if (!isVmError(cause)) return null;
|
|
101
|
+
const nativeError = `${cause.code}: ${cause.message}`;
|
|
102
|
+
if (cause.status == null) {
|
|
103
|
+
if (cause.code === "timeout")
|
|
104
|
+
return fail(SandboxRouterErrorCode.Timeout, cause.message, { retryable: true, nativeError });
|
|
105
|
+
if (cause.code === "request_failed" || cause.code === "connect_failed")
|
|
106
|
+
return fail(SandboxRouterErrorCode.NetworkError, cause.message, {
|
|
107
|
+
retryable: true,
|
|
108
|
+
nativeError
|
|
109
|
+
});
|
|
110
|
+
return fail(SandboxRouterErrorCode.ProviderError, cause.message, { nativeError });
|
|
111
|
+
}
|
|
112
|
+
if (cause.status === 410)
|
|
113
|
+
return fail(SandboxRouterErrorCode.NotFound, "final has no such resource", {
|
|
114
|
+
status: 410,
|
|
115
|
+
nativeError
|
|
116
|
+
});
|
|
117
|
+
return failFromStatus(PROVIDER, cause.status, nativeError);
|
|
118
|
+
};
|
|
119
|
+
const isMissing = (cause) => isVmError(cause) && (cause.status === 404 || cause.status === 410 || cause.code === "invalid_id");
|
|
120
|
+
const call = (run) => attempt(PROVIDER, run, classify);
|
|
121
|
+
const failure = (cause) => classify(cause) ?? fail(SandboxRouterErrorCode.ProviderError, `${PROVIDER} failed`, {
|
|
122
|
+
nativeError: cause instanceof Error ? cause.message : String(cause)
|
|
123
|
+
});
|
|
124
|
+
const classifyCreate = (cause) => {
|
|
125
|
+
const lost = isVmError(cause) && (cause.status == null && cause.code === "request_failed" || cause.code === "pending") || cause instanceof Error && (cause.name === "TimeoutError" || cause.name === "AbortError");
|
|
126
|
+
if (lost)
|
|
127
|
+
return fail(SandboxRouterErrorCode.Timeout, "final did not answer the create", {
|
|
128
|
+
retryable: true,
|
|
129
|
+
nativeError: cause instanceof Error ? cause.message : String(cause)
|
|
130
|
+
});
|
|
131
|
+
return classify(cause);
|
|
132
|
+
};
|
|
133
|
+
const networkFields = (network) => {
|
|
134
|
+
if (network.egress === EgressMode.AllowAll)
|
|
135
|
+
return { allowInternet: true, allowDomains: [], allowCidrs: [] };
|
|
136
|
+
if (network.egress === EgressMode.DenyAll)
|
|
137
|
+
return { allowInternet: false, allowDomains: [], allowCidrs: [] };
|
|
138
|
+
return isEgressAllowList(network.egress) ? {
|
|
139
|
+
allowInternet: false,
|
|
140
|
+
allowDomains: network.egress.allowDomains ?? [],
|
|
141
|
+
allowCidrs: network.egress.allowCidrs ?? []
|
|
142
|
+
} : { allowInternet: false, allowDomains: [], allowCidrs: [] };
|
|
143
|
+
};
|
|
144
|
+
const timerFields = (spec) => spec.atEnd === AtEnd.Pause ? { idleTimeoutS: spec.timeouts.idleS, wallClockLimitS: spec.timeouts.maxS } : {
|
|
145
|
+
idleTimeoutS: spec.timeouts.idleS,
|
|
146
|
+
ephemeral: spec.timeouts.idleS == null ? void 0 : true,
|
|
147
|
+
ttlS: spec.timeouts.maxS
|
|
148
|
+
};
|
|
149
|
+
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 };
|
|
150
|
+
const IDLE_WORKLOAD = {
|
|
151
|
+
entrypoint: ["/bin/sh", "-c"],
|
|
152
|
+
cmd: ["exec sleep infinity"],
|
|
153
|
+
restart: false
|
|
154
|
+
};
|
|
155
|
+
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];
|
|
156
|
+
const final = (credentials, options = {}) => {
|
|
157
|
+
const clock = systemClock;
|
|
158
|
+
const client = createVmClient({
|
|
159
|
+
apiKey: credentials.apiKey,
|
|
160
|
+
apiUrl: credentials.apiUrl,
|
|
161
|
+
previewDomain: options.previewDomain,
|
|
162
|
+
fetch: options.fetch
|
|
163
|
+
});
|
|
164
|
+
const handles = /* @__PURE__ */ new Map();
|
|
165
|
+
const remember = (handle) => {
|
|
166
|
+
if (handles.size >= MAX_CACHED_HANDLES) {
|
|
167
|
+
const oldest = handles.keys().next().value;
|
|
168
|
+
if (oldest != null) handles.delete(oldest);
|
|
169
|
+
}
|
|
170
|
+
handles.set(handle.id, handle);
|
|
171
|
+
return handle;
|
|
172
|
+
};
|
|
173
|
+
const handleOf = async (id) => handles.get(id) ?? remember(await client.sandboxes.get(id));
|
|
174
|
+
const withHandle = (id, run) => call(async () => run(await handleOf(id)));
|
|
175
|
+
const settle = async (handle, want, signal) => {
|
|
176
|
+
const deadline = clock.now() + SETTLE_TIMEOUT_MS;
|
|
177
|
+
let info = handle.info();
|
|
178
|
+
for (; ; ) {
|
|
179
|
+
if (want.some((state) => state === info.state)) return info;
|
|
180
|
+
if (info.state === VmState.Failed || GONE.has(info.state))
|
|
181
|
+
throw new Error(`sandbox ${handle.id} is ${info.state}`);
|
|
182
|
+
if (clock.now() >= deadline)
|
|
183
|
+
throw Object.assign(new Error(`sandbox ${handle.id} is still ${info.state}`), {
|
|
184
|
+
name: "TimeoutError"
|
|
185
|
+
});
|
|
186
|
+
await clock.sleep(SETTLE_POLL_MS, signal);
|
|
187
|
+
info = await handle.refresh();
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
const ready = async (handle, signal) => toVendor(await settle(handle, [VmState.Running], signal));
|
|
191
|
+
const startTemplateService = async (handle, templateId, env) => {
|
|
192
|
+
const template = await client.templates.get(templateId);
|
|
193
|
+
if (template.startCmd == null) return;
|
|
194
|
+
const result = await handle.run(
|
|
195
|
+
`nohup sh -c ${shellQuote(template.startCmd)} >/tmp/sandbox-start.log 2>&1 </dev/null &`,
|
|
196
|
+
{ env }
|
|
197
|
+
);
|
|
198
|
+
if (result.exitCode !== 0) throw new Error(`the start command failed: ${result.stderr}`);
|
|
199
|
+
};
|
|
200
|
+
const resolveSource = async (args) => {
|
|
201
|
+
const { spec, size, artifact } = args;
|
|
202
|
+
const plain = (source) => ({
|
|
203
|
+
source,
|
|
204
|
+
sized: true,
|
|
205
|
+
workload: void 0,
|
|
206
|
+
startTemplate: null
|
|
207
|
+
});
|
|
208
|
+
if (args.snapshotId != null)
|
|
209
|
+
return ok({
|
|
210
|
+
source: { kind: SourceKind.Snapshot, snapshotId: args.snapshotId },
|
|
211
|
+
sized: false,
|
|
212
|
+
workload: void 0,
|
|
213
|
+
startTemplate: null
|
|
214
|
+
});
|
|
215
|
+
if (artifact?.kind === "template") {
|
|
216
|
+
const template = await client.templates.get(artifact.id);
|
|
217
|
+
const restorable = Object.keys(spec.env).length === 0 && sameSize(template, size);
|
|
218
|
+
return ok(
|
|
219
|
+
restorable ? { source: sourceOf(artifact), sized: false, workload: void 0, startTemplate: null } : {
|
|
220
|
+
...plain({ kind: SourceKind.Image, imageId: template.imageId }),
|
|
221
|
+
startTemplate: artifact.id
|
|
222
|
+
}
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
if (artifact?.kind === "snapshot") {
|
|
226
|
+
const snapshot = await client.snapshots.get(artifact.id);
|
|
227
|
+
return ok(
|
|
228
|
+
sameSize(snapshot, size) ? { source: sourceOf(artifact), sized: false, workload: void 0, startTemplate: null } : { ...plain(sourceOf(artifact)), workload: IDLE_WORKLOAD }
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
if (artifact != null) return ok(plain(sourceOf(artifact)));
|
|
232
|
+
if (spec.image == null) return ok(plain());
|
|
233
|
+
const reference = baseReference(spec.image.base);
|
|
234
|
+
if (reference == null) return ok(plain());
|
|
235
|
+
const image = await ensureImage({ client, clock, signal: args.signal }, reference);
|
|
236
|
+
return image.ok ? ok(plain({ kind: SourceKind.Image, imageId: image.value })) : image;
|
|
237
|
+
};
|
|
238
|
+
const stream = async (args) => {
|
|
239
|
+
const stdout = args.pty ? ProcessFrameKind.Data : ProcessFrameKind.Stdout;
|
|
240
|
+
const stderr = args.pty ? ProcessFrameKind.Data : ProcessFrameKind.Stderr;
|
|
241
|
+
let process = null;
|
|
242
|
+
let killed = false;
|
|
243
|
+
let detached = false;
|
|
244
|
+
const sendKill = (signal) => {
|
|
245
|
+
try {
|
|
246
|
+
process?.kill(signal);
|
|
247
|
+
} catch {
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
const frames = createSeqFrames({
|
|
251
|
+
afterSeq: args.afterSeq,
|
|
252
|
+
awaitStarted: args.afterSeq < 0,
|
|
253
|
+
maxOutputBytes: limits.maxOutputBytes,
|
|
254
|
+
onOutputCap: () => sendKill(SIGNALS[ProcessSignal.Kill])
|
|
255
|
+
});
|
|
256
|
+
const opened = await call(
|
|
257
|
+
() => args.open({
|
|
258
|
+
onStdout: (bytes, seq) => frames.output(stdout, seq, bytes),
|
|
259
|
+
onStderr: (bytes, seq) => frames.output(stderr, seq, bytes)
|
|
260
|
+
})
|
|
261
|
+
);
|
|
262
|
+
if (!opened.ok) return opened;
|
|
263
|
+
const current = opened.value;
|
|
264
|
+
process = current;
|
|
265
|
+
if (args.afterSeq < 0) frames.started(current.processId, current.pid);
|
|
266
|
+
if (!args.keepStdin)
|
|
267
|
+
try {
|
|
268
|
+
current.closeStdin();
|
|
269
|
+
} catch {
|
|
270
|
+
}
|
|
271
|
+
current.wait().then(
|
|
272
|
+
(result) => frames.exit(
|
|
273
|
+
result.exitCode,
|
|
274
|
+
result.timedOut ? ExitReason.Timeout : killed || result.signal != null ? ExitReason.Killed : ExitReason.Exited,
|
|
275
|
+
signalName(result.signal)
|
|
276
|
+
),
|
|
277
|
+
(cause) => {
|
|
278
|
+
if (detached) return;
|
|
279
|
+
if (isVmError(cause) && (cause.code === "exec_unreachable" || cause.code === "exec_lost"))
|
|
280
|
+
frames.exit(null, ExitReason.ProviderLost, null);
|
|
281
|
+
else
|
|
282
|
+
frames.error(
|
|
283
|
+
SandboxRouterErrorCode.ProviderError,
|
|
284
|
+
cause instanceof Error ? cause.message : String(cause)
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
);
|
|
288
|
+
args.signal?.addEventListener("abort", () => sendKill(SIGNALS[ProcessSignal.Kill]), {
|
|
289
|
+
once: true
|
|
290
|
+
});
|
|
291
|
+
const input = (send) => call(async () => {
|
|
292
|
+
send();
|
|
293
|
+
});
|
|
294
|
+
return ok({
|
|
295
|
+
processId: current.processId,
|
|
296
|
+
frames: frames.frames,
|
|
297
|
+
write: (data) => input(() => current.write(data)),
|
|
298
|
+
closeStdin: () => input(() => current.closeStdin()),
|
|
299
|
+
kill: async (signal) => {
|
|
300
|
+
if (!frames.ended()) {
|
|
301
|
+
killed = true;
|
|
302
|
+
sendKill(SIGNALS[signal ?? ProcessSignal.Term]);
|
|
303
|
+
}
|
|
304
|
+
return ok(void 0);
|
|
305
|
+
},
|
|
306
|
+
detach: () => {
|
|
307
|
+
detached = true;
|
|
308
|
+
current.detach();
|
|
309
|
+
frames.stop();
|
|
310
|
+
},
|
|
311
|
+
resize: (size) => input(() => current.resize(size))
|
|
312
|
+
});
|
|
313
|
+
};
|
|
314
|
+
const fit = (spec) => {
|
|
315
|
+
const diskGib = spec.diskGib ?? DEFAULT_DISK_GIB;
|
|
316
|
+
const fitted = fitWithinLimits({ limits, spec: { ...spec, diskGib } });
|
|
317
|
+
if (spec.gpu != null) fitted.rejected.push({ field: "gpu", reason: "no GPUs" });
|
|
318
|
+
if (spec.region != null && !regions.includes(spec.region))
|
|
319
|
+
fitted.rejected.push({ field: "region", reason: `only ${regions.join(", ")}` });
|
|
320
|
+
return {
|
|
321
|
+
...fitted,
|
|
322
|
+
applied: spec.diskGib == null ? fitted.applied.filter((field) => field !== "diskGib") : fitted.applied
|
|
323
|
+
};
|
|
324
|
+
};
|
|
325
|
+
const availableRegions = async () => {
|
|
326
|
+
const listed = await call(() => client.machineTypes.list());
|
|
327
|
+
if (!listed.ok) return listed;
|
|
328
|
+
const listedRegions = new Set(listed.value.map((entry) => entry.regionZone));
|
|
329
|
+
return ok(regions.filter((region) => listedRegions.has(region)));
|
|
330
|
+
};
|
|
331
|
+
const prices = async (spec, context) => {
|
|
332
|
+
const parsed = finalOptionsSchema.safeParse(context.providerOptions ?? {});
|
|
333
|
+
if (!parsed.success) return fail(SandboxRouterErrorCode.InvalidRequest, parsed.error.message);
|
|
334
|
+
const { cpuLimit, memoryLimitMib, machine } = parsed.data;
|
|
335
|
+
const diskGib = spec.diskGib ?? DEFAULT_DISK_GIB;
|
|
336
|
+
const listed = await call(
|
|
337
|
+
() => client.machineTypes.list({
|
|
338
|
+
cpu: [spec.cpu, cpuLimit ?? spec.cpu],
|
|
339
|
+
memory: [spec.memoryMib, memoryLimitMib ?? spec.memoryMib],
|
|
340
|
+
diskGb: diskGib
|
|
341
|
+
})
|
|
342
|
+
);
|
|
343
|
+
if (!listed.ok) return listed;
|
|
344
|
+
const cheapest = listed.value.find(
|
|
345
|
+
(entry) => entry.price.hourly != null && entry.price.currency.toUpperCase() === "USD" && (machine?.types == null || machine.types.includes(entry.machineType)) && (machine?.cpuFamilies == null || machine.cpuFamilies.includes(entry.hardware.cpuFamily))
|
|
346
|
+
);
|
|
347
|
+
if (cheapest?.price.hourly == null)
|
|
348
|
+
return fail(SandboxRouterErrorCode.ProviderError, "no priced machine type fits the spec");
|
|
349
|
+
const diskGibMonth = cheapest.price.diskGibMonth;
|
|
350
|
+
return ok({
|
|
351
|
+
hourlyRunning: cheapest.price.hourly.baseline,
|
|
352
|
+
hourlyPaused: diskGibMonth == null ? null : formatUsd(diskGib * toNanos(diskGibMonth) / HOURS_PER_MONTH),
|
|
353
|
+
perCreate: "0",
|
|
354
|
+
// Names the exact prices (not where they run), so a price change is a new version.
|
|
355
|
+
priceVersion: `${PROVIDER}@${(await sha256Hex(canonicalJson(cheapest.price))).slice(0, 12)}`,
|
|
356
|
+
billingModel: BillingModel.MaxOfRequestAndUse,
|
|
357
|
+
hardware: {
|
|
358
|
+
chips: [cheapest.hardware.cpuModel],
|
|
359
|
+
host: null,
|
|
360
|
+
confidence: HardwareConfidence.Documented,
|
|
361
|
+
sourceUrl: null
|
|
362
|
+
},
|
|
363
|
+
sourceUrl: null
|
|
364
|
+
});
|
|
365
|
+
};
|
|
366
|
+
return defineProvider({
|
|
367
|
+
specificationVersion: SPECIFICATION_VERSION,
|
|
368
|
+
name: PROVIDER,
|
|
369
|
+
regions,
|
|
370
|
+
availableRegions,
|
|
371
|
+
capabilities,
|
|
372
|
+
limits,
|
|
373
|
+
providerOptions: finalOptionsSchema,
|
|
374
|
+
fit,
|
|
375
|
+
prices,
|
|
376
|
+
create: async (spec, context) => {
|
|
377
|
+
const providerOptions = finalOptionsSchema.parse(context.providerOptions ?? {});
|
|
378
|
+
const size = {
|
|
379
|
+
cpu: [spec.cpu, providerOptions.cpuLimit ?? spec.cpu],
|
|
380
|
+
memory: [spec.memoryMib, providerOptions.memoryLimitMib ?? spec.memoryMib]
|
|
381
|
+
};
|
|
382
|
+
const resolved = await call(
|
|
383
|
+
() => resolveSource({
|
|
384
|
+
spec,
|
|
385
|
+
size,
|
|
386
|
+
artifact: context.artifact,
|
|
387
|
+
snapshotId: context.snapshotId,
|
|
388
|
+
signal: context.signal
|
|
389
|
+
})
|
|
390
|
+
);
|
|
391
|
+
if (!resolved.ok) return resolved;
|
|
392
|
+
if (!resolved.value.ok) return resolved.value;
|
|
393
|
+
const plan = resolved.value.value;
|
|
394
|
+
const request = {
|
|
395
|
+
projectId: providerOptions.projectId,
|
|
396
|
+
source: plan.source,
|
|
397
|
+
workload: plan.workload,
|
|
398
|
+
cpu: plan.sized ? size.cpu : void 0,
|
|
399
|
+
memory: plan.sized ? size.memory : void 0,
|
|
400
|
+
diskGb: spec.diskGib,
|
|
401
|
+
machine: providerOptions.machine,
|
|
402
|
+
env: Object.keys(spec.env).length === 0 ? void 0 : spec.env,
|
|
403
|
+
ports: spec.ports,
|
|
404
|
+
publicPorts: providerOptions.publicPorts,
|
|
405
|
+
tools: providerOptions.tools,
|
|
406
|
+
...networkFields(spec.network),
|
|
407
|
+
...timerFields(spec),
|
|
408
|
+
labels: { name: context.name, ...context.labels },
|
|
409
|
+
signal: context.signal
|
|
410
|
+
};
|
|
411
|
+
const created = await attempt(
|
|
412
|
+
PROVIDER,
|
|
413
|
+
async () => remember(await client.sandboxes.create(request)),
|
|
414
|
+
classifyCreate
|
|
415
|
+
);
|
|
416
|
+
if (!created.ok) return created;
|
|
417
|
+
const handle = created.value;
|
|
418
|
+
const started = await call(async () => {
|
|
419
|
+
const sandbox = await ready(handle, context.signal);
|
|
420
|
+
if (plan.startTemplate != null)
|
|
421
|
+
await startTemplateService(handle, plan.startTemplate, spec.env);
|
|
422
|
+
return sandbox;
|
|
423
|
+
});
|
|
424
|
+
if (!started.ok) await handle.delete().catch(() => void 0);
|
|
425
|
+
return started;
|
|
426
|
+
},
|
|
427
|
+
get: async (id) => {
|
|
428
|
+
try {
|
|
429
|
+
const cached = handles.get(id);
|
|
430
|
+
const info = cached == null ? remember(await client.sandboxes.get(id)).info() : await cached.refresh();
|
|
431
|
+
return ok(toVendor(info));
|
|
432
|
+
} catch (cause) {
|
|
433
|
+
if (isMissing(cause)) return ok(null);
|
|
434
|
+
return failure(cause);
|
|
435
|
+
}
|
|
436
|
+
},
|
|
437
|
+
list: ({ labels }) => call(async () => {
|
|
438
|
+
const found = [];
|
|
439
|
+
let after;
|
|
440
|
+
for (; ; ) {
|
|
441
|
+
const page = await client.sandboxes.list({ labels, after, limit: LIST_PAGE });
|
|
442
|
+
for (const info of page) if (!GONE.has(info.state)) found.push(toVendor(info));
|
|
443
|
+
if (page.length < LIST_PAGE) return found;
|
|
444
|
+
after = page.at(-1)?.id;
|
|
445
|
+
}
|
|
446
|
+
}),
|
|
447
|
+
delete: async (id) => {
|
|
448
|
+
try {
|
|
449
|
+
const handle = await handleOf(id);
|
|
450
|
+
if (!GONE.has(handle.info().state)) await handle.delete();
|
|
451
|
+
handles.delete(id);
|
|
452
|
+
return ok(void 0);
|
|
453
|
+
} catch (cause) {
|
|
454
|
+
handles.delete(id);
|
|
455
|
+
if (isMissing(cause)) return ok(void 0);
|
|
456
|
+
return failure(cause);
|
|
457
|
+
}
|
|
458
|
+
},
|
|
459
|
+
pause: (id) => withHandle(id, async (handle) => {
|
|
460
|
+
await handle.pause();
|
|
461
|
+
await settle(handle, [VmState.Paused]);
|
|
462
|
+
return { kept: PauseKeep.Memory };
|
|
463
|
+
}),
|
|
464
|
+
resume: (id) => withHandle(id, async (handle) => {
|
|
465
|
+
const result = await handle.resume();
|
|
466
|
+
await settle(handle, [VmState.Running]);
|
|
467
|
+
return { coldRestart: result.resumed?.mode === "cold" };
|
|
468
|
+
}),
|
|
469
|
+
stop: (id) => withHandle(id, async (handle) => {
|
|
470
|
+
await handle.stop();
|
|
471
|
+
await settle(handle, [VmState.Stopped]);
|
|
472
|
+
}),
|
|
473
|
+
start: (id) => withHandle(id, async (handle) => {
|
|
474
|
+
await handle.start();
|
|
475
|
+
await settle(handle, [VmState.Running]);
|
|
476
|
+
}),
|
|
477
|
+
// The wall-clock limit, counted from now; Final VMs pause the sandbox when it runs out. The
|
|
478
|
+
// idle timeout is set at create only.
|
|
479
|
+
setTimeout: async (id, timeouts) => {
|
|
480
|
+
if (timeouts.idleS != null) return unsupported(PROVIDER, "changing the idle timeout");
|
|
481
|
+
const maxS = timeouts.maxS;
|
|
482
|
+
if (maxS == null) return ok(void 0);
|
|
483
|
+
return withHandle(id, async (handle) => {
|
|
484
|
+
await handle.setTimeout(maxS);
|
|
485
|
+
});
|
|
486
|
+
},
|
|
487
|
+
setNetwork: (id, network) => withHandle(id, async (handle) => {
|
|
488
|
+
const fields = networkFields(network);
|
|
489
|
+
let status = await handle.network.set({ ...fields, denyCidrs: [] });
|
|
490
|
+
const deadline = clock.now() + SETTLE_TIMEOUT_MS;
|
|
491
|
+
while (!status.applied && clock.now() < deadline) {
|
|
492
|
+
await clock.sleep(SETTLE_POLL_MS);
|
|
493
|
+
status = await handle.network.get();
|
|
494
|
+
}
|
|
495
|
+
if (!status.applied) throw new Error("the network policy was not applied in time");
|
|
496
|
+
}),
|
|
497
|
+
exec: (id, command, execOptions) => withHandle(
|
|
498
|
+
id,
|
|
499
|
+
(handle) => stream({
|
|
500
|
+
open: (handlers) => handle.exec({
|
|
501
|
+
cmd: command,
|
|
502
|
+
env: execOptions.env,
|
|
503
|
+
cwd: execOptions.cwd,
|
|
504
|
+
user: execOptions.user,
|
|
505
|
+
timeoutMs: execOptions.timeoutMs,
|
|
506
|
+
...handlers
|
|
507
|
+
}),
|
|
508
|
+
afterSeq: -1,
|
|
509
|
+
pty: false,
|
|
510
|
+
keepStdin: execOptions.stdin === true,
|
|
511
|
+
signal: execOptions.signal
|
|
512
|
+
})
|
|
513
|
+
).then((result) => result.ok ? result.value : result),
|
|
514
|
+
attach: (id, processId, { afterSeq }) => withHandle(
|
|
515
|
+
id,
|
|
516
|
+
(handle) => stream({
|
|
517
|
+
open: (handlers) => handle.attach({ processId, afterSeq: Math.max(afterSeq, 0), ...handlers }),
|
|
518
|
+
afterSeq: Math.max(afterSeq, 0),
|
|
519
|
+
pty: false,
|
|
520
|
+
keepStdin: true
|
|
521
|
+
})
|
|
522
|
+
).then((result) => result.ok ? result.value : result),
|
|
523
|
+
pty: (id, ptyOptions) => withHandle(
|
|
524
|
+
id,
|
|
525
|
+
(handle) => stream({
|
|
526
|
+
open: (handlers) => handle.exec({
|
|
527
|
+
cmd: ptyOptions.command ?? 'exec "${SHELL:-/bin/bash}" -l',
|
|
528
|
+
env: ptyOptions.env,
|
|
529
|
+
cwd: ptyOptions.cwd,
|
|
530
|
+
pty: { cols: ptyOptions.cols, rows: ptyOptions.rows },
|
|
531
|
+
...handlers
|
|
532
|
+
}),
|
|
533
|
+
afterSeq: -1,
|
|
534
|
+
pty: true,
|
|
535
|
+
keepStdin: true
|
|
536
|
+
})
|
|
537
|
+
).then((result) => result.ok ? result.value : result),
|
|
538
|
+
files: {
|
|
539
|
+
read: (id, path, range) => withHandle(
|
|
540
|
+
id,
|
|
541
|
+
(handle) => handle.files.read(path, { offset: range?.offset, length: range?.length })
|
|
542
|
+
),
|
|
543
|
+
write: (id, path, bytes, writeOptions) => withHandle(id, async (handle) => {
|
|
544
|
+
await handle.files.write(path, bytes, { mode: writeOptions?.mode });
|
|
545
|
+
}),
|
|
546
|
+
list: (id, path) => withHandle(id, async (handle) => (await handle.files.list(path)).entries.map(fileEntry)),
|
|
547
|
+
mkdir: (id, path, mkdirOptions) => withHandle(
|
|
548
|
+
id,
|
|
549
|
+
(handle) => handle.files.mkdir(path, { parents: mkdirOptions?.recursive ?? true })
|
|
550
|
+
),
|
|
551
|
+
remove: (id, path, removeOptions) => withHandle(id, async (handle) => {
|
|
552
|
+
try {
|
|
553
|
+
await handle.files.remove(path, { recursive: removeOptions?.recursive });
|
|
554
|
+
} catch (cause) {
|
|
555
|
+
if (!(isVmError(cause) && cause.status === 404)) throw cause;
|
|
556
|
+
}
|
|
557
|
+
}),
|
|
558
|
+
stat: (id, path) => withHandle(id, async (handle) => {
|
|
559
|
+
const stat = await handle.files.stat(path);
|
|
560
|
+
return stat == null ? null : fileEntry(stat);
|
|
561
|
+
})
|
|
562
|
+
},
|
|
563
|
+
ports: {
|
|
564
|
+
// A published port is public; any other answers to a preview token, sent in a header by
|
|
565
|
+
// programs (a browser opening the URL exchanges it for a session cookie).
|
|
566
|
+
url: (id, port) => withHandle(id, async (handle) => {
|
|
567
|
+
const [published, base] = await Promise.all([
|
|
568
|
+
handle.listPorts(),
|
|
569
|
+
handle.previewUrl(port)
|
|
570
|
+
]);
|
|
571
|
+
if (published.some((entry) => entry.port === port && entry.public))
|
|
572
|
+
return { url: base, auth: PortAuth.Public, token: null, expiresAt: null };
|
|
573
|
+
const token = await handle.createPreviewToken(port, { ttlS: PREVIEW_TOKEN_TTL_S });
|
|
574
|
+
const url = new URL(base);
|
|
575
|
+
url.searchParams.set(PREVIEW_TOKEN_QUERY, token.token);
|
|
576
|
+
return {
|
|
577
|
+
url: url.toString(),
|
|
578
|
+
auth: PortAuth.Header,
|
|
579
|
+
token: token.token,
|
|
580
|
+
header: PREVIEW_TOKEN_HEADER,
|
|
581
|
+
expiresAt: token.expiresAt.toISOString()
|
|
582
|
+
};
|
|
583
|
+
})
|
|
584
|
+
},
|
|
585
|
+
snapshot: (id, { name }) => withHandle(id, async (handle) => {
|
|
586
|
+
try {
|
|
587
|
+
return await handle.checkpoint({ name });
|
|
588
|
+
} catch (cause) {
|
|
589
|
+
if (!(isVmError(cause) && cause.code === "name_taken")) throw cause;
|
|
590
|
+
const earlier = (await client.snapshots.list()).find(
|
|
591
|
+
(snapshot) => snapshot.name === name && snapshot.sandboxId === id
|
|
592
|
+
);
|
|
593
|
+
if (earlier != null) return { snapshotId: earlier.id };
|
|
594
|
+
return handle.checkpoint({ name: `${name}-${crypto.randomUUID().slice(0, 8)}` });
|
|
595
|
+
}
|
|
596
|
+
}),
|
|
597
|
+
deleteSnapshot: async (snapshotId) => {
|
|
598
|
+
try {
|
|
599
|
+
await client.snapshots.delete(snapshotId);
|
|
600
|
+
return ok(void 0);
|
|
601
|
+
} catch (cause) {
|
|
602
|
+
if (isMissing(cause)) return ok(void 0);
|
|
603
|
+
return failure(cause);
|
|
604
|
+
}
|
|
605
|
+
},
|
|
606
|
+
fork: (id, { count, labels, name }) => withHandle(id, async (handle) => {
|
|
607
|
+
const { children } = await handle.fork(count);
|
|
608
|
+
return Promise.all(
|
|
609
|
+
children.map(async (child, index) => {
|
|
610
|
+
remember(child);
|
|
611
|
+
await child.updateLabels({ name: `${name}-${index}`, ...labels });
|
|
612
|
+
return ready(child);
|
|
613
|
+
})
|
|
614
|
+
);
|
|
615
|
+
}),
|
|
616
|
+
image: {
|
|
617
|
+
strategy: imageStrategy,
|
|
618
|
+
build: (spec, buildContext) => call(
|
|
619
|
+
() => buildImage(
|
|
620
|
+
{ client, clock, signal: buildContext.signal, onLog: buildContext.onLog },
|
|
621
|
+
spec
|
|
622
|
+
)
|
|
623
|
+
).then((result) => result.ok ? result.value : result),
|
|
624
|
+
remove: async (artifact) => {
|
|
625
|
+
try {
|
|
626
|
+
if (artifact.kind === "template") await client.templates.delete(artifact.id);
|
|
627
|
+
else if (artifact.kind === "snapshot") await client.snapshots.delete(artifact.id);
|
|
628
|
+
else await client.images.delete(artifact.id);
|
|
629
|
+
return ok(void 0);
|
|
630
|
+
} catch (cause) {
|
|
631
|
+
if (isMissing(cause)) return ok(void 0);
|
|
632
|
+
return failure(cause);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
},
|
|
636
|
+
connect: (id) => withHandle(id, async (handle) => {
|
|
637
|
+
const grant = await handle.connect();
|
|
638
|
+
return {
|
|
639
|
+
provider: PROVIDER,
|
|
640
|
+
providerSandboxId: id,
|
|
641
|
+
kind: "grant",
|
|
642
|
+
token: grant.token,
|
|
643
|
+
url: grant.endpoint.includes("://") ? grant.endpoint : `https://${grant.endpoint}`,
|
|
644
|
+
expiresAt: new Date(grant.expiresAt).toISOString(),
|
|
645
|
+
details: { generation: String(grant.generation) }
|
|
646
|
+
};
|
|
647
|
+
})
|
|
648
|
+
});
|
|
649
|
+
};
|
|
650
|
+
export {
|
|
651
|
+
final,
|
|
652
|
+
sandboxStateOf
|
|
653
|
+
};
|
|
654
|
+
//# sourceMappingURL=provider.mjs.map
|