@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,23 @@
|
|
|
1
|
+
export declare enum VmErrorSource {
|
|
2
|
+
Api = "api",
|
|
3
|
+
Ingress = "ingress",
|
|
4
|
+
Exec = "exec"
|
|
5
|
+
}
|
|
6
|
+
export interface VmErrorIface extends Error {
|
|
7
|
+
source: VmErrorSource;
|
|
8
|
+
status: number | null;
|
|
9
|
+
code: string;
|
|
10
|
+
retryAfterMs: number | null;
|
|
11
|
+
}
|
|
12
|
+
interface VmErrorFieldsIface {
|
|
13
|
+
source: VmErrorSource;
|
|
14
|
+
status: number | null;
|
|
15
|
+
code: string;
|
|
16
|
+
message: string;
|
|
17
|
+
retryAfterMs?: number | null;
|
|
18
|
+
}
|
|
19
|
+
export declare const VM_ERROR_NAME = "VmError";
|
|
20
|
+
export declare const vmError: (fields: VmErrorFieldsIface) => VmErrorIface;
|
|
21
|
+
export declare const isVmError: (cause: unknown) => cause is VmErrorIface;
|
|
22
|
+
export declare const parseRetryAfterMs: (value: string | null, now: number) => number | null;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
var VmErrorSource = /* @__PURE__ */ ((VmErrorSource2) => {
|
|
2
|
+
VmErrorSource2["Api"] = "api";
|
|
3
|
+
VmErrorSource2["Ingress"] = "ingress";
|
|
4
|
+
VmErrorSource2["Exec"] = "exec";
|
|
5
|
+
return VmErrorSource2;
|
|
6
|
+
})(VmErrorSource || {});
|
|
7
|
+
const VM_ERROR_NAME = "VmError";
|
|
8
|
+
const vmError = (fields) => Object.assign(new Error(fields.message), {
|
|
9
|
+
name: VM_ERROR_NAME,
|
|
10
|
+
source: fields.source,
|
|
11
|
+
status: fields.status,
|
|
12
|
+
code: fields.code,
|
|
13
|
+
retryAfterMs: fields.retryAfterMs ?? null
|
|
14
|
+
});
|
|
15
|
+
const isVmError = (cause) => cause instanceof Error && cause.name === VM_ERROR_NAME && "code" in cause;
|
|
16
|
+
const parseRetryAfterMs = (value, now) => {
|
|
17
|
+
if (value == null || value.trim() === "") return null;
|
|
18
|
+
const seconds = Number(value);
|
|
19
|
+
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
|
|
20
|
+
const at = Date.parse(value);
|
|
21
|
+
return Number.isFinite(at) ? Math.max(0, at - now) : null;
|
|
22
|
+
};
|
|
23
|
+
export {
|
|
24
|
+
VM_ERROR_NAME,
|
|
25
|
+
VmErrorSource,
|
|
26
|
+
isVmError,
|
|
27
|
+
parseRetryAfterMs,
|
|
28
|
+
vmError
|
|
29
|
+
};
|
|
30
|
+
//# sourceMappingURL=errors.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../../src/vm/errors.ts"],
|
|
4
|
+
"sourcesContent": ["// Every failure the client reports: an HTTP answer from the API or the data plane, a protocol\n// violation, or a broken exec stream. `code` is the server's `error` field when it sent one.\n\nexport enum VmErrorSource {\n Api = 'api',\n Ingress = 'ingress',\n Exec = 'exec',\n}\n\nexport interface VmErrorIface extends Error {\n source: VmErrorSource;\n // HTTP status, or null when no answer arrived.\n status: number | null;\n code: string;\n // Milliseconds the server asked to wait before retrying.\n retryAfterMs: number | null;\n}\n\ninterface VmErrorFieldsIface {\n source: VmErrorSource;\n status: number | null;\n code: string;\n message: string;\n retryAfterMs?: number | null;\n}\n\nexport const VM_ERROR_NAME = 'VmError';\n\nexport const vmError = (fields: VmErrorFieldsIface): VmErrorIface =>\n Object.assign(new Error(fields.message), {\n name: VM_ERROR_NAME,\n source: fields.source,\n status: fields.status,\n code: fields.code,\n retryAfterMs: fields.retryAfterMs ?? null,\n });\n\nexport const isVmError = (cause: unknown): cause is VmErrorIface =>\n cause instanceof Error && cause.name === VM_ERROR_NAME && 'code' in cause;\n\n// `Retry-After` in seconds or as an HTTP date.\nexport const parseRetryAfterMs = (value: string | null, now: number): number | null => {\n if (value == null || value.trim() === '') return null;\n const seconds = Number(value);\n if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);\n const at = Date.parse(value);\n return Number.isFinite(at) ? Math.max(0, at - now) : null;\n};\n"],
|
|
5
|
+
"mappings": "AAGO,IAAK,gBAAL,kBAAKA,mBAAL;AACL,EAAAA,eAAA,SAAM;AACN,EAAAA,eAAA,aAAU;AACV,EAAAA,eAAA,UAAO;AAHG,SAAAA;AAAA,GAAA;AAuBL,MAAM,gBAAgB;AAEtB,MAAM,UAAU,CAAC,WACtB,OAAO,OAAO,IAAI,MAAM,OAAO,OAAO,GAAG;AAAA,EACvC,MAAM;AAAA,EACN,QAAQ,OAAO;AAAA,EACf,QAAQ,OAAO;AAAA,EACf,MAAM,OAAO;AAAA,EACb,cAAc,OAAO,gBAAgB;AACvC,CAAC;AAEI,MAAM,YAAY,CAAC,UACxB,iBAAiB,SAAS,MAAM,SAAS,iBAAiB,UAAU;AAG/D,MAAM,oBAAoB,CAAC,OAAsB,QAA+B;AACrF,MAAI,SAAS,QAAQ,MAAM,KAAK,MAAM,GAAI,QAAO;AACjD,QAAM,UAAU,OAAO,KAAK;AAC5B,MAAI,OAAO,SAAS,OAAO,EAAG,QAAO,KAAK,IAAI,GAAG,UAAU,GAAI;AAC/D,QAAM,KAAK,KAAK,MAAM,KAAK;AAC3B,SAAO,OAAO,SAAS,EAAE,IAAI,KAAK,IAAI,GAAG,KAAK,GAAG,IAAI;AACvD;",
|
|
6
|
+
"names": ["VmErrorSource"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { ClockIface } from "./clock.mjs";
|
|
2
|
+
import { type GrantSourceIface } from "./grants.mjs";
|
|
3
|
+
export declare const EXEC_PING_INTERVAL_MS = 25000;
|
|
4
|
+
export interface PtySizeIface {
|
|
5
|
+
cols: number;
|
|
6
|
+
rows: number;
|
|
7
|
+
}
|
|
8
|
+
export interface ExecHandlersIface {
|
|
9
|
+
onStdout?: (data: Uint8Array, seq: number) => void;
|
|
10
|
+
onStderr?: (data: Uint8Array, seq: number) => void;
|
|
11
|
+
}
|
|
12
|
+
export interface ExecOptionsIface extends ExecHandlersIface {
|
|
13
|
+
cmd: string;
|
|
14
|
+
args?: string[];
|
|
15
|
+
env?: Record<string, string>;
|
|
16
|
+
cwd?: string;
|
|
17
|
+
user?: string;
|
|
18
|
+
pty?: PtySizeIface;
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
}
|
|
21
|
+
export interface ExecResultIface {
|
|
22
|
+
exitCode: number | null;
|
|
23
|
+
signal: number | null;
|
|
24
|
+
timedOut: boolean;
|
|
25
|
+
}
|
|
26
|
+
export interface ExecProcessIface {
|
|
27
|
+
processId: string;
|
|
28
|
+
pid: number | null;
|
|
29
|
+
write: (data: string | Uint8Array) => void;
|
|
30
|
+
closeStdin: () => void;
|
|
31
|
+
resize: (size: PtySizeIface) => void;
|
|
32
|
+
kill: (signal?: number) => void;
|
|
33
|
+
wait: () => Promise<ExecResultIface>;
|
|
34
|
+
detach: () => void;
|
|
35
|
+
lastSeq: () => number;
|
|
36
|
+
}
|
|
37
|
+
export interface ExecTransportIface {
|
|
38
|
+
grants: GrantSourceIface;
|
|
39
|
+
clock: ClockIface;
|
|
40
|
+
pingIntervalMs?: number;
|
|
41
|
+
}
|
|
42
|
+
export declare const startExec: (transport: ExecTransportIface, options: ExecOptionsIface) => Promise<ExecProcessIface>;
|
|
43
|
+
export interface AttachOptionsIface extends ExecHandlersIface {
|
|
44
|
+
processId: string;
|
|
45
|
+
afterSeq?: number;
|
|
46
|
+
}
|
|
47
|
+
export declare const attachExec: (transport: ExecTransportIface, options: AttachOptionsIface) => Promise<ExecProcessIface>;
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer";
|
|
2
|
+
import WebSocket from "ws";
|
|
3
|
+
import { parseRetryAfterMs, vmError, VmErrorSource } from "./errors.mjs";
|
|
4
|
+
import {
|
|
5
|
+
FullScope,
|
|
6
|
+
grantAllows,
|
|
7
|
+
grantRenewalDelayMs,
|
|
8
|
+
readOnlyGrantError
|
|
9
|
+
} from "./grants.mjs";
|
|
10
|
+
import { execServerFrameSchema } from "./ingress.mjs";
|
|
11
|
+
const EXEC_PING_INTERVAL_MS = 25e3;
|
|
12
|
+
const MAX_ATTEMPTS_WITHOUT_PROGRESS = 8;
|
|
13
|
+
const MAX_BACKOFF_MS = 2e3;
|
|
14
|
+
const ERROR_BODY_LIMIT = 4096;
|
|
15
|
+
const execFailure = (code, message) => vmError({ source: VmErrorSource.Exec, status: null, code, message });
|
|
16
|
+
const openSocket = (transport, url, token, listeners) => new Promise((resolve) => {
|
|
17
|
+
const socket = new WebSocket(url, { headers: { authorization: `Bearer ${token}` } });
|
|
18
|
+
socket.on("message", (data, isBinary) => {
|
|
19
|
+
listeners.activity();
|
|
20
|
+
listeners.message(data, isBinary);
|
|
21
|
+
});
|
|
22
|
+
socket.on("ping", listeners.activity);
|
|
23
|
+
socket.on("pong", listeners.activity);
|
|
24
|
+
let settled = false;
|
|
25
|
+
const settle = (value) => {
|
|
26
|
+
if (settled) return;
|
|
27
|
+
settled = true;
|
|
28
|
+
resolve(value);
|
|
29
|
+
};
|
|
30
|
+
socket.on("error", (error) => {
|
|
31
|
+
settle({
|
|
32
|
+
error: execFailure("connect_failed", `exec socket: ${error.message}`),
|
|
33
|
+
renewGrant: false,
|
|
34
|
+
retryAfterMs: null,
|
|
35
|
+
retryable: true
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
socket.once("open", () => settle(socket));
|
|
39
|
+
socket.once("unexpected-response", (request, response) => {
|
|
40
|
+
const status = response.statusCode ?? 0;
|
|
41
|
+
const chunks = [];
|
|
42
|
+
let size = 0;
|
|
43
|
+
response.on("data", (chunk) => {
|
|
44
|
+
if (size < ERROR_BODY_LIMIT) chunks.push(chunk);
|
|
45
|
+
size += chunk.length;
|
|
46
|
+
});
|
|
47
|
+
response.on("end", () => {
|
|
48
|
+
const text = Buffer.concat(chunks).toString("utf8").slice(0, ERROR_BODY_LIMIT);
|
|
49
|
+
const retryAfter = response.headers["retry-after"] ?? null;
|
|
50
|
+
settle({
|
|
51
|
+
error: vmError({
|
|
52
|
+
source: VmErrorSource.Ingress,
|
|
53
|
+
status,
|
|
54
|
+
code: /"error"\s*:\s*"([a-z_]+)"/.exec(text)?.[1] ?? `http_${status}`,
|
|
55
|
+
message: `exec handshake: ${status} ${text}`
|
|
56
|
+
}),
|
|
57
|
+
renewGrant: status === 401 || status === 409,
|
|
58
|
+
retryAfterMs: parseRetryAfterMs(retryAfter, transport.clock.now()),
|
|
59
|
+
retryable: status === 401 || status === 409 || status === 502 || status === 503
|
|
60
|
+
});
|
|
61
|
+
request.destroy();
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
const runSession = async (transport, init, handlers) => {
|
|
66
|
+
const pingIntervalMs = transport.pingIntervalMs ?? EXEC_PING_INTERVAL_MS;
|
|
67
|
+
let processId = init.processId;
|
|
68
|
+
let pid = null;
|
|
69
|
+
let lastSeq = init.afterSeq;
|
|
70
|
+
let socket = null;
|
|
71
|
+
let grant = null;
|
|
72
|
+
let finished = false;
|
|
73
|
+
let detached = false;
|
|
74
|
+
let startSent = false;
|
|
75
|
+
let attemptsWithoutProgress = 0;
|
|
76
|
+
let seqAtLastAttempt = lastSeq;
|
|
77
|
+
const outbox = [];
|
|
78
|
+
const started = Promise.withResolvers();
|
|
79
|
+
const exited = Promise.withResolvers();
|
|
80
|
+
started.promise.catch(() => {
|
|
81
|
+
});
|
|
82
|
+
exited.promise.catch(() => {
|
|
83
|
+
});
|
|
84
|
+
const fail = (error) => {
|
|
85
|
+
if (finished) return;
|
|
86
|
+
finished = true;
|
|
87
|
+
started.reject(error);
|
|
88
|
+
exited.reject(error);
|
|
89
|
+
socket?.terminate();
|
|
90
|
+
};
|
|
91
|
+
const send = (frame) => {
|
|
92
|
+
if (finished || detached) {
|
|
93
|
+
throw execFailure("exec_closed", "exec: the process has ended or was detached");
|
|
94
|
+
}
|
|
95
|
+
if (grant != null && !grantAllows(grant, FullScope.Exec)) {
|
|
96
|
+
throw readOnlyGrantError({ source: VmErrorSource.Exec, what: `exec ${frame.type}`, grant });
|
|
97
|
+
}
|
|
98
|
+
const text = JSON.stringify(frame);
|
|
99
|
+
if (socket?.readyState === WebSocket.OPEN) socket.send(text);
|
|
100
|
+
else outbox.push(text);
|
|
101
|
+
};
|
|
102
|
+
const onMessage = (data, isBinary) => {
|
|
103
|
+
if (isBinary || finished || detached) return;
|
|
104
|
+
let parsed;
|
|
105
|
+
try {
|
|
106
|
+
parsed = JSON.parse(data.toString());
|
|
107
|
+
} catch {
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const frame = execServerFrameSchema.safeParse(parsed);
|
|
111
|
+
if (!frame.success) return;
|
|
112
|
+
const value = frame.data;
|
|
113
|
+
if (value.type === "started") {
|
|
114
|
+
processId ??= value.process_id;
|
|
115
|
+
pid = value.pid;
|
|
116
|
+
started.resolve();
|
|
117
|
+
} else if (value.type === "stdout" || value.type === "stderr") {
|
|
118
|
+
if (value.seq <= lastSeq) return;
|
|
119
|
+
lastSeq = value.seq;
|
|
120
|
+
const bytes = Buffer.from(value.data_b64, "base64");
|
|
121
|
+
if (value.type === "stdout") handlers.onStdout?.(bytes, value.seq);
|
|
122
|
+
else handlers.onStderr?.(bytes, value.seq);
|
|
123
|
+
} else if (value.type === "exit") {
|
|
124
|
+
finished = true;
|
|
125
|
+
started.resolve();
|
|
126
|
+
exited.resolve({ exitCode: value.code, signal: value.signal, timedOut: value.timed_out });
|
|
127
|
+
socket?.close(1e3);
|
|
128
|
+
} else {
|
|
129
|
+
fail(execFailure("exec_failed", value.message));
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
const connect = async () => {
|
|
133
|
+
while (!finished && !detached) {
|
|
134
|
+
if (lastSeq !== seqAtLastAttempt) attemptsWithoutProgress = 0;
|
|
135
|
+
seqAtLastAttempt = lastSeq;
|
|
136
|
+
if (attemptsWithoutProgress >= MAX_ATTEMPTS_WITHOUT_PROGRESS) {
|
|
137
|
+
fail(execFailure("exec_unreachable", "exec: could not reach the sandbox to reattach"));
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
attemptsWithoutProgress += 1;
|
|
141
|
+
let current;
|
|
142
|
+
try {
|
|
143
|
+
current = await transport.grants.get();
|
|
144
|
+
} catch (error) {
|
|
145
|
+
fail(
|
|
146
|
+
execFailure(
|
|
147
|
+
"grant_failed",
|
|
148
|
+
`exec: no connect grant: ${error instanceof Error ? error.message : String(error)}`
|
|
149
|
+
)
|
|
150
|
+
);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
grant = current;
|
|
154
|
+
if (init.start != null && processId == null && !grantAllows(current, FullScope.Exec)) {
|
|
155
|
+
fail(readOnlyGrantError({ source: VmErrorSource.Exec, what: "exec", grant: current }));
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
const url = new URL(
|
|
159
|
+
`${current.origin.replace(/^http/, "ws")}/v1/sandboxes/${current.sandboxUuid}/exec`
|
|
160
|
+
);
|
|
161
|
+
if (processId != null) {
|
|
162
|
+
url.searchParams.set("process_id", processId);
|
|
163
|
+
url.searchParams.set("after_seq", String(lastSeq));
|
|
164
|
+
}
|
|
165
|
+
const liveness = { alive: true };
|
|
166
|
+
const opened = await openSocket(transport, url, current.token, {
|
|
167
|
+
message: onMessage,
|
|
168
|
+
activity: () => {
|
|
169
|
+
liveness.alive = true;
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
if (opened instanceof WebSocket) {
|
|
173
|
+
if (finished || detached) {
|
|
174
|
+
opened.close(1e3);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
attach(opened, liveness);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (!opened.retryable) {
|
|
181
|
+
fail(opened.error);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
if (opened.renewGrant) {
|
|
185
|
+
transport.grants.invalidate(current.token, opened.error.code === "moved");
|
|
186
|
+
}
|
|
187
|
+
await transport.clock.sleep(
|
|
188
|
+
opened.retryAfterMs ?? (opened.renewGrant ? grantRenewalDelayMs(attemptsWithoutProgress) : Math.min(100 * 2 ** attemptsWithoutProgress, MAX_BACKOFF_MS))
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
const attach = (opened, liveness) => {
|
|
193
|
+
socket = opened;
|
|
194
|
+
const openedAt = transport.clock.now();
|
|
195
|
+
const ping = setInterval(() => {
|
|
196
|
+
if (!liveness.alive) {
|
|
197
|
+
opened.terminate();
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
liveness.alive = false;
|
|
201
|
+
if (opened.readyState === WebSocket.OPEN) opened.ping();
|
|
202
|
+
}, pingIntervalMs);
|
|
203
|
+
opened.on("close", (code, reason) => {
|
|
204
|
+
clearInterval(ping);
|
|
205
|
+
if (socket === opened) socket = null;
|
|
206
|
+
if (finished || detached) return;
|
|
207
|
+
if (transport.clock.now() - openedAt >= pingIntervalMs) attemptsWithoutProgress = 0;
|
|
208
|
+
if (code === 1011) {
|
|
209
|
+
fail(execFailure("exec_failed", `exec closed: ${reason.toString()}`));
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (processId == null) {
|
|
213
|
+
fail(
|
|
214
|
+
execFailure(
|
|
215
|
+
"exec_lost",
|
|
216
|
+
"exec: the socket closed before the process started; it may be running"
|
|
217
|
+
)
|
|
218
|
+
);
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
void connect();
|
|
222
|
+
});
|
|
223
|
+
if (init.start == null) {
|
|
224
|
+
started.resolve();
|
|
225
|
+
} else if (!startSent) {
|
|
226
|
+
startSent = true;
|
|
227
|
+
opened.send(JSON.stringify(init.start));
|
|
228
|
+
}
|
|
229
|
+
const queued = outbox.splice(0);
|
|
230
|
+
if (grant != null && !grantAllows(grant, FullScope.Exec)) return;
|
|
231
|
+
for (const text of queued) opened.send(text);
|
|
232
|
+
};
|
|
233
|
+
await connect();
|
|
234
|
+
await started.promise;
|
|
235
|
+
return {
|
|
236
|
+
processId: processId ?? "",
|
|
237
|
+
pid,
|
|
238
|
+
write: (data) => {
|
|
239
|
+
send({
|
|
240
|
+
type: "stdin",
|
|
241
|
+
data_b64: Buffer.from(data).toString("base64"),
|
|
242
|
+
eof: false
|
|
243
|
+
});
|
|
244
|
+
},
|
|
245
|
+
closeStdin: () => {
|
|
246
|
+
send({ type: "stdin", data_b64: "", eof: true });
|
|
247
|
+
},
|
|
248
|
+
resize: (size) => {
|
|
249
|
+
send({ type: "resize", cols: size.cols, rows: size.rows });
|
|
250
|
+
},
|
|
251
|
+
kill: (signal = 15) => {
|
|
252
|
+
send({ type: "signal", signal });
|
|
253
|
+
},
|
|
254
|
+
wait: () => exited.promise,
|
|
255
|
+
detach: () => {
|
|
256
|
+
if (finished || detached) return;
|
|
257
|
+
detached = true;
|
|
258
|
+
socket?.close(1e3);
|
|
259
|
+
exited.reject(execFailure("detached", "exec: detached from the process"));
|
|
260
|
+
},
|
|
261
|
+
lastSeq: () => lastSeq
|
|
262
|
+
};
|
|
263
|
+
};
|
|
264
|
+
const startExec = async (transport, options) => runSession(
|
|
265
|
+
transport,
|
|
266
|
+
{
|
|
267
|
+
start: {
|
|
268
|
+
type: "start",
|
|
269
|
+
cmd: options.cmd,
|
|
270
|
+
args: options.args,
|
|
271
|
+
env: options.env,
|
|
272
|
+
cwd: options.cwd,
|
|
273
|
+
user: options.user,
|
|
274
|
+
pty: options.pty,
|
|
275
|
+
timeout_ms: options.timeoutMs
|
|
276
|
+
},
|
|
277
|
+
processId: null,
|
|
278
|
+
afterSeq: 0
|
|
279
|
+
},
|
|
280
|
+
options
|
|
281
|
+
);
|
|
282
|
+
const attachExec = async (transport, options) => runSession(
|
|
283
|
+
transport,
|
|
284
|
+
{ start: null, processId: options.processId, afterSeq: options.afterSeq ?? 0 },
|
|
285
|
+
options
|
|
286
|
+
);
|
|
287
|
+
export {
|
|
288
|
+
EXEC_PING_INTERVAL_MS,
|
|
289
|
+
attachExec,
|
|
290
|
+
startExec
|
|
291
|
+
};
|
|
292
|
+
//# sourceMappingURL=exec.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../../src/vm/exec.ts"],
|
|
4
|
+
"sourcesContent": ["import { Buffer } from 'node:buffer';\nimport WebSocket from 'ws';\nimport type { ClockIface } from \"./clock.mjs\";\nimport { parseRetryAfterMs, vmError, VmErrorSource, type VmErrorIface } from \"./errors.mjs\";\nimport {\n FullScope,\n grantAllows,\n grantRenewalDelayMs,\n readOnlyGrantError,\n type DataPlaneGrantIface,\n type GrantSourceIface,\n} from \"./grants.mjs\";\nimport { execServerFrameSchema } from \"./ingress.mjs\";\n\n// `GET \u2026/exec` over a WebSocket to the sandbox's data plane. Output frames carry a sequence\n// number and the sandbox keeps the output, so a socket that closes without `exit` (a network\n// drop, a server restart's 1012, a missed keep-alive) is reopened with\n// `?process_id=&after_seq=<last seq seen>` and nothing is lost or repeated. Both ends ping every\n// 25 s, well inside proxies' idle timeouts; a ping unanswered by the next one ends the socket so\n// it can be reopened.\n//\n// The `ws` package rather than the global WebSocket: a refused handshake's status, body and\n// `Retry-After` decide whether to renew the grant or wait, and liveness needs ping and pong\n// frames. The global WebSocket exposes neither.\n\nexport const EXEC_PING_INTERVAL_MS = 25_000;\nconst MAX_ATTEMPTS_WITHOUT_PROGRESS = 8;\nconst MAX_BACKOFF_MS = 2_000;\nconst ERROR_BODY_LIMIT = 4_096;\n\nexport interface PtySizeIface {\n cols: number;\n rows: number;\n}\n\n// `seq` numbers output frames from 1 across both streams; `attach` with `afterSeq` resumes\n// after the frame of that number.\nexport interface ExecHandlersIface {\n onStdout?: (data: Uint8Array, seq: number) => void;\n onStderr?: (data: Uint8Array, seq: number) => void;\n}\n\nexport interface ExecOptionsIface extends ExecHandlersIface {\n cmd: string;\n // Present (even empty) means argv form; absent means `sh -c cmd`.\n args?: string[];\n env?: Record<string, string>;\n cwd?: string;\n user?: string;\n pty?: PtySizeIface;\n // Enforced in the sandbox: the process is killed and `timedOut` reported.\n timeoutMs?: number;\n}\n\nexport interface ExecResultIface {\n exitCode: number | null;\n signal: number | null;\n timedOut: boolean;\n}\n\nexport interface ExecProcessIface {\n processId: string;\n pid: number | null;\n write: (data: string | Uint8Array) => void;\n closeStdin: () => void;\n resize: (size: PtySizeIface) => void;\n kill: (signal?: number) => void;\n wait: () => Promise<ExecResultIface>;\n // Closes the socket; the process keeps running and `attach` picks it up again.\n detach: () => void;\n lastSeq: () => number;\n}\n\nexport interface ExecTransportIface {\n grants: GrantSourceIface;\n clock: ClockIface;\n pingIntervalMs?: number;\n}\n\n// Client frames. Absent optional fields are left out of the JSON.\ninterface ExecStartFrameIface {\n type: 'start';\n cmd: string;\n args?: string[];\n env?: Record<string, string>;\n cwd?: string;\n user?: string;\n pty?: PtySizeIface;\n timeout_ms?: number;\n}\n\ntype ExecClientFrame =\n | ExecStartFrameIface\n | { type: 'stdin'; data_b64: string; eof: boolean }\n | { type: 'resize'; cols: number; rows: number }\n | { type: 'signal'; signal: number };\n\ninterface SessionInitIface {\n start: ExecStartFrameIface | null;\n processId: string | null;\n afterSeq: number;\n}\n\ninterface HandshakeFailureIface {\n error: VmErrorIface;\n // A fresh grant may get through (moved, unauthorized).\n renewGrant: boolean;\n retryAfterMs: number | null;\n retryable: boolean;\n}\n\nconst execFailure = (code: string, message: string): VmErrorIface =>\n vmError({ source: VmErrorSource.Exec, status: null, code, message });\n\ninterface SocketListenersIface {\n message: (data: WebSocket.RawData, isBinary: boolean) => void;\n // Any sign of life: a message, a ping or a pong.\n activity: () => void;\n}\n\n// Listeners go on before the handshake completes: a frame can arrive in the same read as the\n// upgrade answer, and `ws` drops messages nobody listens for.\nconst openSocket = (\n transport: ExecTransportIface,\n url: URL,\n token: string,\n listeners: SocketListenersIface,\n): Promise<WebSocket | HandshakeFailureIface> =>\n new Promise((resolve) => {\n const socket = new WebSocket(url, { headers: { authorization: `Bearer ${token}` } });\n socket.on('message', (data, isBinary) => {\n listeners.activity();\n listeners.message(data, isBinary);\n });\n socket.on('ping', listeners.activity);\n socket.on('pong', listeners.activity);\n let settled = false;\n const settle = (value: WebSocket | HandshakeFailureIface) => {\n if (settled) return;\n settled = true;\n resolve(value);\n };\n // Errors after the handshake surface as `close`.\n socket.on('error', (error) => {\n settle({\n error: execFailure('connect_failed', `exec socket: ${error.message}`),\n renewGrant: false,\n retryAfterMs: null,\n retryable: true,\n });\n });\n socket.once('open', () => settle(socket));\n socket.once('unexpected-response', (request, response) => {\n const status = response.statusCode ?? 0;\n const chunks: Buffer[] = [];\n let size = 0;\n response.on('data', (chunk: Buffer) => {\n if (size < ERROR_BODY_LIMIT) chunks.push(chunk);\n size += chunk.length;\n });\n response.on('end', () => {\n const text = Buffer.concat(chunks).toString('utf8').slice(0, ERROR_BODY_LIMIT);\n const retryAfter = response.headers['retry-after'] ?? null;\n settle({\n error: vmError({\n source: VmErrorSource.Ingress,\n status,\n code: /\"error\"\\s*:\\s*\"([a-z_]+)\"/.exec(text)?.[1] ?? `http_${status}`,\n message: `exec handshake: ${status} ${text}`,\n }),\n renewGrant: status === 401 || status === 409,\n retryAfterMs: parseRetryAfterMs(retryAfter, transport.clock.now()),\n retryable: status === 401 || status === 409 || status === 502 || status === 503,\n });\n request.destroy();\n });\n });\n });\n\nconst runSession = async (\n transport: ExecTransportIface,\n init: SessionInitIface,\n handlers: ExecHandlersIface,\n): Promise<ExecProcessIface> => {\n const pingIntervalMs = transport.pingIntervalMs ?? EXEC_PING_INTERVAL_MS;\n let processId = init.processId;\n let pid: number | null = null;\n let lastSeq = init.afterSeq;\n let socket: WebSocket | null = null;\n // The grant the socket last opened with.\n let grant: DataPlaneGrantIface | null = null;\n let finished = false;\n let detached = false;\n let startSent = false;\n // Reconnects give up only when several in a row bring no new output.\n let attemptsWithoutProgress = 0;\n let seqAtLastAttempt = lastSeq;\n const outbox: string[] = [];\n const started = Promise.withResolvers<void>();\n const exited = Promise.withResolvers<ExecResultIface>();\n // A failure nobody waits for must not become an unhandled rejection.\n started.promise.catch(() => {});\n exited.promise.catch(() => {});\n\n const fail = (error: VmErrorIface) => {\n if (finished) return;\n finished = true;\n started.reject(error);\n exited.reject(error);\n socket?.terminate();\n };\n\n const send = (frame: ExecClientFrame) => {\n if (finished || detached) {\n throw execFailure('exec_closed', 'exec: the process has ended or was detached');\n }\n // A read-only grant watches; the server would end the socket on any frame.\n if (grant != null && !grantAllows(grant, FullScope.Exec)) {\n throw readOnlyGrantError({ source: VmErrorSource.Exec, what: `exec ${frame.type}`, grant });\n }\n const text = JSON.stringify(frame);\n if (socket?.readyState === WebSocket.OPEN) socket.send(text);\n else outbox.push(text);\n };\n\n const onMessage = (data: WebSocket.RawData, isBinary: boolean) => {\n if (isBinary || finished || detached) return;\n let parsed: unknown;\n try {\n parsed = JSON.parse(data.toString());\n } catch {\n return;\n }\n const frame = execServerFrameSchema.safeParse(parsed);\n if (!frame.success) return;\n const value = frame.data;\n if (value.type === 'started') {\n processId ??= value.process_id;\n pid = value.pid;\n started.resolve();\n } else if (value.type === 'stdout' || value.type === 'stderr') {\n if (value.seq <= lastSeq) return;\n lastSeq = value.seq;\n const bytes = Buffer.from(value.data_b64, 'base64');\n if (value.type === 'stdout') handlers.onStdout?.(bytes, value.seq);\n else handlers.onStderr?.(bytes, value.seq);\n } else if (value.type === 'exit') {\n finished = true;\n // A reattach after exit gets `exit` straight away; `started` may never have come.\n started.resolve();\n exited.resolve({ exitCode: value.code, signal: value.signal, timedOut: value.timed_out });\n socket?.close(1000);\n } else {\n fail(execFailure('exec_failed', value.message));\n }\n };\n\n // Opens (or reopens) the socket. Resolves once one is open or the session has failed.\n const connect = async (): Promise<void> => {\n while (!finished && !detached) {\n if (lastSeq !== seqAtLastAttempt) attemptsWithoutProgress = 0;\n seqAtLastAttempt = lastSeq;\n if (attemptsWithoutProgress >= MAX_ATTEMPTS_WITHOUT_PROGRESS) {\n fail(execFailure('exec_unreachable', 'exec: could not reach the sandbox to reattach'));\n return;\n }\n attemptsWithoutProgress += 1;\n let current: DataPlaneGrantIface;\n try {\n current = await transport.grants.get();\n } catch (error) {\n fail(\n execFailure(\n 'grant_failed',\n `exec: no connect grant: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n return;\n }\n grant = current;\n if (init.start != null && processId == null && !grantAllows(current, FullScope.Exec)) {\n fail(readOnlyGrantError({ source: VmErrorSource.Exec, what: 'exec', grant: current }));\n return;\n }\n const url = new URL(\n `${current.origin.replace(/^http/, 'ws')}/v1/sandboxes/${current.sandboxUuid}/exec`,\n );\n if (processId != null) {\n url.searchParams.set('process_id', processId);\n url.searchParams.set('after_seq', String(lastSeq));\n }\n const liveness = { alive: true };\n const opened = await openSocket(transport, url, current.token, {\n message: onMessage,\n activity: () => {\n liveness.alive = true;\n },\n });\n if (opened instanceof WebSocket) {\n if (finished || detached) {\n opened.close(1000);\n return;\n }\n attach(opened, liveness);\n return;\n }\n if (!opened.retryable) {\n fail(opened.error);\n return;\n }\n if (opened.renewGrant) {\n transport.grants.invalidate(current.token, opened.error.code === 'moved');\n }\n await transport.clock.sleep(\n opened.retryAfterMs ??\n (opened.renewGrant\n ? grantRenewalDelayMs(attemptsWithoutProgress)\n : Math.min(100 * 2 ** attemptsWithoutProgress, MAX_BACKOFF_MS)),\n );\n }\n };\n\n const attach = (opened: WebSocket, liveness: { alive: boolean }) => {\n socket = opened;\n const openedAt = transport.clock.now();\n const ping = setInterval(() => {\n if (!liveness.alive) {\n opened.terminate();\n return;\n }\n liveness.alive = false;\n if (opened.readyState === WebSocket.OPEN) opened.ping();\n }, pingIntervalMs);\n opened.on('close', (code, reason) => {\n clearInterval(ping);\n if (socket === opened) socket = null;\n if (finished || detached) return;\n // A socket that lived a while was progress, even for a process printing nothing.\n if (transport.clock.now() - openedAt >= pingIntervalMs) attemptsWithoutProgress = 0;\n // 1011 follows an `error` frame, which already failed the session.\n if (code === 1011) {\n fail(execFailure('exec_failed', `exec closed: ${reason.toString()}`));\n return;\n }\n if (processId == null) {\n fail(\n execFailure(\n 'exec_lost',\n 'exec: the socket closed before the process started; it may be running',\n ),\n );\n return;\n }\n void connect();\n });\n if (init.start == null) {\n // Attaching by process id: the server sends `started` only without an `after_seq`.\n started.resolve();\n } else if (!startSent) {\n startSent = true;\n opened.send(JSON.stringify(init.start));\n }\n const queued = outbox.splice(0);\n // Input queued under a grant that has since lost `exec` would end this socket; the\n // process can't take it any more, but its output can still be watched.\n if (grant != null && !grantAllows(grant, FullScope.Exec)) return;\n for (const text of queued) opened.send(text);\n };\n\n await connect();\n await started.promise;\n return {\n processId: processId ?? '',\n pid,\n write: (data) => {\n send({\n type: 'stdin',\n data_b64: Buffer.from(data).toString('base64'),\n eof: false,\n });\n },\n closeStdin: () => {\n send({ type: 'stdin', data_b64: '', eof: true });\n },\n resize: (size) => {\n send({ type: 'resize', cols: size.cols, rows: size.rows });\n },\n kill: (signal = 15) => {\n send({ type: 'signal', signal });\n },\n wait: () => exited.promise,\n detach: () => {\n if (finished || detached) return;\n detached = true;\n socket?.close(1000);\n exited.reject(execFailure('detached', 'exec: detached from the process'));\n },\n lastSeq: () => lastSeq,\n };\n};\n\nexport const startExec = async (\n transport: ExecTransportIface,\n options: ExecOptionsIface,\n): Promise<ExecProcessIface> =>\n runSession(\n transport,\n {\n start: {\n type: 'start',\n cmd: options.cmd,\n args: options.args,\n env: options.env,\n cwd: options.cwd,\n user: options.user,\n pty: options.pty,\n timeout_ms: options.timeoutMs,\n },\n processId: null,\n afterSeq: 0,\n },\n options,\n );\n\nexport interface AttachOptionsIface extends ExecHandlersIface {\n processId: string;\n // Output with a seq above this is delivered; 0 replays everything retained.\n afterSeq?: number;\n}\n\nexport const attachExec = async (\n transport: ExecTransportIface,\n options: AttachOptionsIface,\n): Promise<ExecProcessIface> =>\n runSession(\n transport,\n { start: null, processId: options.processId, afterSeq: options.afterSeq ?? 0 },\n options,\n );\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,cAAc;AACvB,OAAO,eAAe;AAEtB,SAAS,mBAAmB,SAAS,qBAAwC;AAC7E;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,6BAA6B;AAa/B,MAAM,wBAAwB;AACrC,MAAM,gCAAgC;AACtC,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AAmFzB,MAAM,cAAc,CAAC,MAAc,YACjC,QAAQ,EAAE,QAAQ,cAAc,MAAM,QAAQ,MAAM,MAAM,QAAQ,CAAC;AAUrE,MAAM,aAAa,CACjB,WACA,KACA,OACA,cAEA,IAAI,QAAQ,CAAC,YAAY;AACvB,QAAM,SAAS,IAAI,UAAU,KAAK,EAAE,SAAS,EAAE,eAAe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AAE,MAAM,UAAU,MAAM,KAAK,MAAM,MAAM,KAAK,KAAK,CAAC;AAAA,IAC3D;AAAA,IACA,MAAM,CAAC,SAAS,OAAO;AACrB,WAAK,EAAE,MAAM,UAAU,OAAO,CAAC;AAAA,IACjC;AAAA,IACA,MAAM,MAAM,OAAO;AAAA,IACnB,QAAQ,MAAM;AACZ,UAAI,YAAY,SAAU;AAC1B,iBAAW;AACX,cAAQ,MAAM,GAAI;AAClB,aAAO,OAAO,YAAY,YAAY,iCAAiC,CAAC;AAAA,IAC1E;AAAA,IACA,SAAS,MAAM;AAAA,EACjB;AACF;AAEO,MAAM,YAAY,OACvB,WACA,YAEA;AAAA,EACE;AAAA,EACA;AAAA,IACE,OAAO;AAAA,MACL,MAAM;AAAA,MACN,KAAK,QAAQ;AAAA,MACb,MAAM,QAAQ;AAAA,MACd,KAAK,QAAQ;AAAA,MACb,KAAK,QAAQ;AAAA,MACb,MAAM,QAAQ;AAAA,MACd,KAAK,QAAQ;AAAA,MACb,YAAY,QAAQ;AAAA,IACtB;AAAA,IACA,WAAW;AAAA,IACX,UAAU;AAAA,EACZ;AAAA,EACA;AACF;AAQK,MAAM,aAAa,OACxB,WACA,YAEA;AAAA,EACE;AAAA,EACA,EAAE,OAAO,MAAM,WAAW,QAAQ,WAAW,UAAU,QAAQ,YAAY,EAAE;AAAA,EAC7E;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type ApiTransport } from "./api.mjs";
|
|
2
|
+
import type { FileStatIface, ReadOptionsIface } from "./ingress.mjs";
|
|
3
|
+
export declare const createFileReader: (args: {
|
|
4
|
+
api: ApiTransport;
|
|
5
|
+
sandboxId: string;
|
|
6
|
+
chunkBytes?: number;
|
|
7
|
+
}) => {
|
|
8
|
+
read: (path: string, options?: ReadOptionsIface) => Promise<Uint8Array>;
|
|
9
|
+
stat: (path: string, options?: {
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
}) => Promise<FileStatIface | null>;
|
|
12
|
+
list: (path: string, options?: {
|
|
13
|
+
signal?: AbortSignal;
|
|
14
|
+
}) => Promise<{
|
|
15
|
+
entries: FileStatIface[];
|
|
16
|
+
truncated: boolean;
|
|
17
|
+
}>;
|
|
18
|
+
};
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer";
|
|
2
|
+
import * as z from "zod";
|
|
3
|
+
import { HttpMethod } from "./api.mjs";
|
|
4
|
+
import { isVmError, vmError, VmErrorSource } from "./errors.mjs";
|
|
5
|
+
const READ_BYTES = 1024 * 1024;
|
|
6
|
+
const LIST_ENTRIES = 256;
|
|
7
|
+
const LIST_LIMIT = 1e4;
|
|
8
|
+
const entrySchema = z.object({
|
|
9
|
+
path_b64: z.string().base64().max(8192),
|
|
10
|
+
kind: z.string(),
|
|
11
|
+
size: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
|
12
|
+
mode: z.number().int().min(0).max(4095),
|
|
13
|
+
mtime_seconds: z.number().int(),
|
|
14
|
+
mtime_nanoseconds: z.number().int().min(0).max(999999999)
|
|
15
|
+
});
|
|
16
|
+
const identity = {
|
|
17
|
+
generation: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
|
|
18
|
+
snapshot_id: z.string().nullable(),
|
|
19
|
+
view_id: z.string().nullable().optional()
|
|
20
|
+
};
|
|
21
|
+
const readSchema = z.object({
|
|
22
|
+
...identity,
|
|
23
|
+
result: z.object({
|
|
24
|
+
kind: z.literal("read"),
|
|
25
|
+
entry: entrySchema,
|
|
26
|
+
offset: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
|
27
|
+
data_b64: z.string().base64().max(4 * Math.ceil(READ_BYTES / 3))
|
|
28
|
+
})
|
|
29
|
+
});
|
|
30
|
+
const statSchema = z.object({
|
|
31
|
+
...identity,
|
|
32
|
+
result: z.object({ kind: z.literal("stat"), entry: entrySchema })
|
|
33
|
+
});
|
|
34
|
+
const listSchema = z.object({
|
|
35
|
+
...identity,
|
|
36
|
+
result: z.object({
|
|
37
|
+
kind: z.literal("list"),
|
|
38
|
+
entries: z.array(entrySchema).max(LIST_ENTRIES),
|
|
39
|
+
next_b64: z.string().base64().max(340).nullable(),
|
|
40
|
+
truncated: z.boolean().default(false)
|
|
41
|
+
})
|
|
42
|
+
});
|
|
43
|
+
const viewQuery = (view) => ({
|
|
44
|
+
generation: view?.generation,
|
|
45
|
+
view_id: view?.view_id ?? void 0
|
|
46
|
+
});
|
|
47
|
+
const sameView = (before, after) => before == null || before.generation === after.generation && before.snapshot_id === after.snapshot_id && (before.view_id == null || before.view_id === after.view_id);
|
|
48
|
+
const invalid = (message) => vmError({
|
|
49
|
+
source: VmErrorSource.Api,
|
|
50
|
+
status: 200,
|
|
51
|
+
code: "invalid_answer",
|
|
52
|
+
message
|
|
53
|
+
});
|
|
54
|
+
const stat = (row) => ({
|
|
55
|
+
path: `/${Buffer.from(row.path_b64, "base64").toString("utf8")}`,
|
|
56
|
+
kind: row.kind,
|
|
57
|
+
size: row.size,
|
|
58
|
+
mode: row.mode,
|
|
59
|
+
modifiedAt: new Date(row.mtime_seconds * 1e3 + Math.floor(row.mtime_nanoseconds / 1e6))
|
|
60
|
+
});
|
|
61
|
+
const createFileReader = (args) => {
|
|
62
|
+
const endpoint = `/sandboxes/${encodeURIComponent(args.sandboxId)}/files`;
|
|
63
|
+
const chunkBytes = Math.min(args.chunkBytes ?? READ_BYTES, READ_BYTES);
|
|
64
|
+
if (!Number.isSafeInteger(chunkBytes) || chunkBytes < 1)
|
|
65
|
+
throw new RangeError("chunkBytes must be a positive safe integer");
|
|
66
|
+
const read = async (path, options = {}) => {
|
|
67
|
+
const start = options.offset ?? 0;
|
|
68
|
+
const length = options.length;
|
|
69
|
+
if (!Number.isSafeInteger(start) || start < 0 || length != null && (!Number.isSafeInteger(length) || length < 0 || !Number.isSafeInteger(start + length))) {
|
|
70
|
+
throw new RangeError("offset and length must be nonnegative safe integers");
|
|
71
|
+
}
|
|
72
|
+
if (length === 0) return new Uint8Array();
|
|
73
|
+
const chunks = [];
|
|
74
|
+
let view = null;
|
|
75
|
+
let size = null;
|
|
76
|
+
let position = start;
|
|
77
|
+
let end = length == null ? null : start + length;
|
|
78
|
+
while (end == null || position < end) {
|
|
79
|
+
const window = Math.min(chunkBytes, end == null ? chunkBytes : end - position);
|
|
80
|
+
const answer = await args.api({
|
|
81
|
+
method: HttpMethod.Get,
|
|
82
|
+
path: endpoint,
|
|
83
|
+
schema: readSchema,
|
|
84
|
+
signal: options.signal,
|
|
85
|
+
query: { op: "read", path, offset: position, length: window, ...viewQuery(view) }
|
|
86
|
+
});
|
|
87
|
+
const bytes = Buffer.from(answer.result.data_b64, "base64");
|
|
88
|
+
if (!sameView(view, answer) || answer.result.offset !== position || bytes.length > window || size != null && size !== answer.result.entry.size && answer.snapshot_id != null) {
|
|
89
|
+
throw invalid("Filesystem view changed during ranged read");
|
|
90
|
+
}
|
|
91
|
+
view = answer;
|
|
92
|
+
size = answer.result.entry.size;
|
|
93
|
+
end = Math.min(end ?? answer.result.entry.size, answer.result.entry.size);
|
|
94
|
+
const expected = Math.max(0, Math.min(window, end - position));
|
|
95
|
+
if (bytes.length !== expected) throw invalid("Filesystem read returned an incomplete window");
|
|
96
|
+
chunks.push(bytes);
|
|
97
|
+
position += bytes.length;
|
|
98
|
+
}
|
|
99
|
+
return Buffer.concat(chunks);
|
|
100
|
+
};
|
|
101
|
+
return {
|
|
102
|
+
read,
|
|
103
|
+
stat: async (path, options = {}) => {
|
|
104
|
+
try {
|
|
105
|
+
const answer = await args.api({
|
|
106
|
+
method: HttpMethod.Get,
|
|
107
|
+
path: endpoint,
|
|
108
|
+
query: { op: "stat", path },
|
|
109
|
+
schema: statSchema,
|
|
110
|
+
signal: options.signal
|
|
111
|
+
});
|
|
112
|
+
return stat(answer.result.entry);
|
|
113
|
+
} catch (error) {
|
|
114
|
+
if (isVmError(error) && error.status === 404 && error.code === "file_not_found")
|
|
115
|
+
return null;
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
},
|
|
119
|
+
list: async (path, options = {}) => {
|
|
120
|
+
const entries = [];
|
|
121
|
+
const seen = /* @__PURE__ */ new Set();
|
|
122
|
+
let cursor;
|
|
123
|
+
let view = null;
|
|
124
|
+
let truncated = false;
|
|
125
|
+
do {
|
|
126
|
+
const answer = await args.api({
|
|
127
|
+
method: HttpMethod.Get,
|
|
128
|
+
path: endpoint,
|
|
129
|
+
schema: listSchema,
|
|
130
|
+
signal: options.signal,
|
|
131
|
+
query: {
|
|
132
|
+
op: "list",
|
|
133
|
+
path,
|
|
134
|
+
cursor,
|
|
135
|
+
limit: Math.min(LIST_ENTRIES, LIST_LIMIT - entries.length),
|
|
136
|
+
...viewQuery(view)
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
if (!sameView(view, answer))
|
|
140
|
+
throw invalid("Filesystem view changed during directory listing");
|
|
141
|
+
view = answer;
|
|
142
|
+
entries.push(...answer.result.entries.map(stat));
|
|
143
|
+
truncated ||= answer.result.truncated;
|
|
144
|
+
cursor = answer.result.next_b64 ?? void 0;
|
|
145
|
+
if (cursor != null) {
|
|
146
|
+
if (seen.has(cursor) || answer.result.entries.length === 0)
|
|
147
|
+
throw invalid("Directory cursor did not advance");
|
|
148
|
+
seen.add(cursor);
|
|
149
|
+
}
|
|
150
|
+
if (entries.length >= LIST_LIMIT)
|
|
151
|
+
return { entries, truncated: truncated || cursor != null };
|
|
152
|
+
} while (cursor != null);
|
|
153
|
+
return { entries, truncated };
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
};
|
|
157
|
+
export {
|
|
158
|
+
createFileReader
|
|
159
|
+
};
|
|
160
|
+
//# sourceMappingURL=files.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../../src/vm/files.ts"],
|
|
4
|
+
"sourcesContent": ["import { Buffer } from 'node:buffer';\nimport * as z from 'zod';\nimport { HttpMethod, type ApiTransport } from \"./api.mjs\";\nimport { isVmError, vmError, VmErrorSource } from \"./errors.mjs\";\nimport type { FileStatIface, ReadOptionsIface } from \"./ingress.mjs\";\n\nconst READ_BYTES = 1024 * 1024;\nconst LIST_ENTRIES = 256;\nconst LIST_LIMIT = 10_000;\n\nconst entrySchema = z.object({\n path_b64: z.string().base64().max(8192),\n kind: z.string(),\n size: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),\n mode: z.number().int().min(0).max(0o7777),\n mtime_seconds: z.number().int(),\n mtime_nanoseconds: z.number().int().min(0).max(999_999_999),\n});\nconst identity = {\n generation: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),\n snapshot_id: z.string().nullable(),\n view_id: z.string().nullable().optional(),\n};\nconst readSchema = z.object({\n ...identity,\n result: z.object({\n kind: z.literal('read'),\n entry: entrySchema,\n offset: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),\n data_b64: z\n .string()\n .base64()\n .max(4 * Math.ceil(READ_BYTES / 3)),\n }),\n});\nconst statSchema = z.object({\n ...identity,\n result: z.object({ kind: z.literal('stat'), entry: entrySchema }),\n});\nconst listSchema = z.object({\n ...identity,\n result: z.object({\n kind: z.literal('list'),\n entries: z.array(entrySchema).max(LIST_ENTRIES),\n next_b64: z.string().base64().max(340).nullable(),\n truncated: z.boolean().default(false),\n }),\n});\n\ninterface FileViewIface {\n generation: number;\n snapshot_id: string | null;\n view_id?: string | null;\n}\n\nconst viewQuery = (view: FileViewIface | null) => ({\n generation: view?.generation,\n view_id: view?.view_id ?? undefined,\n});\nconst sameView = (before: FileViewIface | null, after: FileViewIface) =>\n before == null ||\n (before.generation === after.generation &&\n before.snapshot_id === after.snapshot_id &&\n (before.view_id == null || before.view_id === after.view_id));\nconst invalid = (message: string) =>\n vmError({\n source: VmErrorSource.Api,\n status: 200,\n code: 'invalid_answer',\n message,\n });\nconst stat = (row: z.output<typeof entrySchema>): FileStatIface => ({\n path: `/${Buffer.from(row.path_b64, 'base64').toString('utf8')}`,\n kind: row.kind,\n size: row.size,\n mode: row.mode,\n modifiedAt: new Date(row.mtime_seconds * 1000 + Math.floor(row.mtime_nanoseconds / 1_000_000)),\n});\n\n// All reads use the API, which reads a running sandbox or a saved capture of a paused or\n// stopped one. Obtaining a connect grant would wake a paused sandbox.\nexport const createFileReader = (args: {\n api: ApiTransport;\n sandboxId: string;\n chunkBytes?: number;\n}) => {\n const endpoint = `/sandboxes/${encodeURIComponent(args.sandboxId)}/files`;\n const chunkBytes = Math.min(args.chunkBytes ?? READ_BYTES, READ_BYTES);\n if (!Number.isSafeInteger(chunkBytes) || chunkBytes < 1)\n throw new RangeError('chunkBytes must be a positive safe integer');\n const read = async (path: string, options: ReadOptionsIface = {}): Promise<Uint8Array> => {\n const start = options.offset ?? 0;\n const length = options.length;\n if (\n !Number.isSafeInteger(start) ||\n start < 0 ||\n (length != null &&\n (!Number.isSafeInteger(length) || length < 0 || !Number.isSafeInteger(start + length)))\n ) {\n throw new RangeError('offset and length must be nonnegative safe integers');\n }\n if (length === 0) return new Uint8Array();\n const chunks: Uint8Array[] = [];\n let view: FileViewIface | null = null;\n let size: number | null = null;\n let position = start;\n let end = length == null ? null : start + length;\n while (end == null || position < end) {\n const window = Math.min(chunkBytes, end == null ? chunkBytes : end - position);\n const answer: z.output<typeof readSchema> = await args.api({\n method: HttpMethod.Get,\n path: endpoint,\n schema: readSchema,\n signal: options.signal,\n query: { op: 'read', path, offset: position, length: window, ...viewQuery(view) },\n });\n const bytes = Buffer.from(answer.result.data_b64, 'base64');\n if (\n !sameView(view, answer) ||\n answer.result.offset !== position ||\n bytes.length > window ||\n (size != null && size !== answer.result.entry.size && answer.snapshot_id != null)\n ) {\n throw invalid('Filesystem view changed during ranged read');\n }\n view = answer;\n size = answer.result.entry.size;\n end = Math.min(end ?? answer.result.entry.size, answer.result.entry.size);\n const expected = Math.max(0, Math.min(window, end - position));\n if (bytes.length !== expected) throw invalid('Filesystem read returned an incomplete window');\n chunks.push(bytes);\n position += bytes.length;\n }\n return Buffer.concat(chunks);\n };\n return {\n read,\n stat: async (\n path: string,\n options: { signal?: AbortSignal } = {},\n ): Promise<FileStatIface | null> => {\n try {\n const answer = await args.api({\n method: HttpMethod.Get,\n path: endpoint,\n query: { op: 'stat', path },\n schema: statSchema,\n signal: options.signal,\n });\n return stat(answer.result.entry);\n } catch (error) {\n if (isVmError(error) && error.status === 404 && error.code === 'file_not_found')\n return null;\n throw error;\n }\n },\n list: async (\n path: string,\n options: { signal?: AbortSignal } = {},\n ): Promise<{ entries: FileStatIface[]; truncated: boolean }> => {\n const entries: FileStatIface[] = [];\n const seen = new Set<string>();\n let cursor: string | undefined;\n let view: FileViewIface | null = null;\n let truncated = false;\n do {\n const answer: z.output<typeof listSchema> = await args.api({\n method: HttpMethod.Get,\n path: endpoint,\n schema: listSchema,\n signal: options.signal,\n query: {\n op: 'list',\n path,\n cursor,\n limit: Math.min(LIST_ENTRIES, LIST_LIMIT - entries.length),\n ...viewQuery(view),\n },\n });\n if (!sameView(view, answer))\n throw invalid('Filesystem view changed during directory listing');\n view = answer;\n entries.push(...answer.result.entries.map(stat));\n truncated ||= answer.result.truncated;\n cursor = answer.result.next_b64 ?? undefined;\n if (cursor != null) {\n if (seen.has(cursor) || answer.result.entries.length === 0)\n throw invalid('Directory cursor did not advance');\n seen.add(cursor);\n }\n if (entries.length >= LIST_LIMIT)\n return { entries, truncated: truncated || cursor != null };\n } while (cursor != null);\n return { entries, truncated };\n },\n };\n};\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,cAAc;AACvB,YAAY,OAAO;AACnB,SAAS,kBAAqC;AAC9C,SAAS,WAAW,SAAS,qBAAqB;AAGlD,MAAM,aAAa,OAAO;AAC1B,MAAM,eAAe;AACrB,MAAM,aAAa;AAEnB,MAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,IAAI;AAAA,EACtC,MAAM,EAAE,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