disk 1.13.0 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +149 -37
- package/dist/{archil-DJFgh83T.d.mts → archil-CenIy1WD.d.mts} +94 -1
- package/dist/{archil-md8t7zzg.d.cts → archil-DHPfg1b9.d.cts} +94 -1
- package/dist/archil-cli.mjs +591 -0
- package/dist/cli.mjs +6 -275
- package/dist/disk-command-CvRVHqnG.mjs +285 -0
- package/dist/index.cjs +26 -2
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +3 -2
- package/dist/internal/tools.d.cts +1 -1
- package/dist/internal/tools.d.mts +1 -1
- package/dist/node/index.cjs +3515 -0
- package/dist/node/index.mjs +3474 -0
- package/dist/node/internal/tools.cjs +328 -0
- package/dist/node/internal/tools.mjs +326 -0
- package/dist/node/paths-1c4QqbOB.cjs +33 -0
- package/dist/node/paths-Br9snUhy.mjs +28 -0
- package/dist/node/sandbox-desktop-CrvuoiGi.mjs +150 -0
- package/dist/node/sandbox-desktop-DBs8jhKW.cjs +197 -0
- package/dist/node/tunnel.cjs +253 -0
- package/dist/node/tunnel.mjs +248 -0
- package/dist/sandbox-cli.mjs +4 -496
- package/dist/sandbox-command-DJZqMVHm.mjs +1073 -0
- package/dist/sandbox-desktop-CrvuoiGi.mjs +150 -0
- package/dist/sandbox-desktop-DBs8jhKW.cjs +197 -0
- package/dist/{sandbox-options-D99F52j0.mjs → sandbox-options-AO9jKF4-.mjs} +182 -9
- package/dist/{src-CRvOOCjY.mjs → src-BFPiWUCL.mjs} +18 -2
- package/dist/tunnel.cjs +253 -0
- package/dist/tunnel.d.cts +77 -0
- package/dist/tunnel.d.mts +77 -0
- package/dist/tunnel.mjs +248 -0
- package/package.json +21 -3
|
@@ -0,0 +1,3515 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_sandbox_desktop = require("./sandbox-desktop-DBs8jhKW.cjs");
|
|
3
|
+
const require_paths = require("./paths-1c4QqbOB.cjs");
|
|
4
|
+
let _bufbuild_protobuf = require("@bufbuild/protobuf");
|
|
5
|
+
let _archildata_api_types_process = require("@archildata/api-types/process");
|
|
6
|
+
//#region src/api-fetch.ts
|
|
7
|
+
function buildPath(template, params = {}) {
|
|
8
|
+
return template.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
9
|
+
const value = params[name];
|
|
10
|
+
if (value === void 0) throw new Error(`Missing path parameter '${name}' for ${template}`);
|
|
11
|
+
return encodeURIComponent(String(value));
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
/** Serialize a query object; undefined/null values are omitted and arrays repeat the key. */
|
|
15
|
+
function buildQuery(query = {}) {
|
|
16
|
+
const parts = [];
|
|
17
|
+
for (const [name, value] of Object.entries(query)) for (const item of Array.isArray(value) ? value : [value]) {
|
|
18
|
+
if (item === void 0 || item === null) continue;
|
|
19
|
+
parts.push(`${encodeURIComponent(name)}=${encodeURIComponent(String(item))}`);
|
|
20
|
+
}
|
|
21
|
+
return parts.length > 0 ? `?${parts.join("&")}` : "";
|
|
22
|
+
}
|
|
23
|
+
function createClient(config) {
|
|
24
|
+
const baseUrl = config.baseUrl.replace(/\/+$/, "");
|
|
25
|
+
const send = (request) => (config.fetch ?? globalThis.fetch)(request);
|
|
26
|
+
const headersFor = (extra = {}) => {
|
|
27
|
+
const headers = new Headers(config.headers);
|
|
28
|
+
for (const [name, value] of Object.entries(extra)) if (value !== void 0) headers.set(name, value);
|
|
29
|
+
return headers;
|
|
30
|
+
};
|
|
31
|
+
const call = async (method, path, init = {}) => {
|
|
32
|
+
const url = baseUrl + buildPath(path, init.params?.path) + buildQuery(init.params?.query);
|
|
33
|
+
const headers = headersFor(init.params?.header);
|
|
34
|
+
let body;
|
|
35
|
+
if (init.body !== void 0) {
|
|
36
|
+
body = JSON.stringify(init.body);
|
|
37
|
+
if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json");
|
|
38
|
+
}
|
|
39
|
+
const response = await send(new Request(url, {
|
|
40
|
+
method,
|
|
41
|
+
headers,
|
|
42
|
+
body
|
|
43
|
+
}));
|
|
44
|
+
if (response.status === 204 || response.headers.get("Content-Length") === "0") {
|
|
45
|
+
await response.body?.cancel().catch(() => {});
|
|
46
|
+
return response.ok ? {
|
|
47
|
+
data: void 0,
|
|
48
|
+
response
|
|
49
|
+
} : {
|
|
50
|
+
error: void 0,
|
|
51
|
+
response
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
if (response.ok) return {
|
|
55
|
+
data: await response.json(),
|
|
56
|
+
response
|
|
57
|
+
};
|
|
58
|
+
const text = await response.text();
|
|
59
|
+
let error = text;
|
|
60
|
+
try {
|
|
61
|
+
error = JSON.parse(text);
|
|
62
|
+
} catch {}
|
|
63
|
+
return {
|
|
64
|
+
error,
|
|
65
|
+
response
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
const method = (name) => ((path, init) => call(name, path, init));
|
|
69
|
+
return {
|
|
70
|
+
GET: method("GET"),
|
|
71
|
+
PUT: method("PUT"),
|
|
72
|
+
POST: method("POST"),
|
|
73
|
+
DELETE: method("DELETE"),
|
|
74
|
+
PATCH: method("PATCH"),
|
|
75
|
+
raw: (methodName, url, init = {}) => send(new Request(url, {
|
|
76
|
+
method: methodName,
|
|
77
|
+
headers: headersFor(init.headers),
|
|
78
|
+
body: init.body
|
|
79
|
+
}))
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
//#endregion
|
|
83
|
+
//#region src/s3xml.ts
|
|
84
|
+
const ALWAYS_ARRAY = /* @__PURE__ */ new Set(["Contents", "CommonPrefixes"]);
|
|
85
|
+
const NAMED_ENTITIES = {
|
|
86
|
+
amp: "&",
|
|
87
|
+
lt: "<",
|
|
88
|
+
gt: ">",
|
|
89
|
+
quot: "\"",
|
|
90
|
+
apos: "'"
|
|
91
|
+
};
|
|
92
|
+
function decodeEntities(text) {
|
|
93
|
+
if (!text.includes("&")) return text;
|
|
94
|
+
return text.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g, (match, ref) => {
|
|
95
|
+
if (ref[0] === "#") {
|
|
96
|
+
const code = ref[1] === "x" || ref[1] === "X" ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);
|
|
97
|
+
return code > 1114111 ? match : String.fromCodePoint(code);
|
|
98
|
+
}
|
|
99
|
+
return Object.hasOwn(NAMED_ENTITIES, ref) ? NAMED_ENTITIES[ref] : match;
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
function setOwn(target, name, value) {
|
|
103
|
+
Object.defineProperty(target, name, {
|
|
104
|
+
value,
|
|
105
|
+
enumerable: true,
|
|
106
|
+
writable: true,
|
|
107
|
+
configurable: true
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
function addChild(parent, name, value) {
|
|
111
|
+
parent.hasChildren = true;
|
|
112
|
+
const existing = Object.hasOwn(parent.children, name) ? parent.children[name] : void 0;
|
|
113
|
+
if (existing === void 0) setOwn(parent.children, name, ALWAYS_ARRAY.has(name) ? [value] : value);
|
|
114
|
+
else if (Array.isArray(existing)) existing.push(value);
|
|
115
|
+
else setOwn(parent.children, name, [existing, value]);
|
|
116
|
+
}
|
|
117
|
+
/** Index just past `terminator`, searching from `from`; throws if it never appears. */
|
|
118
|
+
function skipPast(xml, terminator, from) {
|
|
119
|
+
const end = xml.indexOf(terminator, from);
|
|
120
|
+
if (end === -1) throw new Error(`Malformed XML: missing '${terminator}'`);
|
|
121
|
+
return end + terminator.length;
|
|
122
|
+
}
|
|
123
|
+
/** Parse an XML document into a plain object. Returns {} for empty/blank input. */
|
|
124
|
+
function parseXml(xml) {
|
|
125
|
+
const root = {
|
|
126
|
+
name: "",
|
|
127
|
+
children: {},
|
|
128
|
+
hasChildren: false,
|
|
129
|
+
text: ""
|
|
130
|
+
};
|
|
131
|
+
const stack = [root];
|
|
132
|
+
let position = 0;
|
|
133
|
+
while (position < xml.length) {
|
|
134
|
+
const current = stack[stack.length - 1];
|
|
135
|
+
const open = xml.indexOf("<", position);
|
|
136
|
+
current.text += decodeEntities(xml.slice(position, open === -1 ? xml.length : open));
|
|
137
|
+
if (open === -1) break;
|
|
138
|
+
if (xml.startsWith("<!--", open)) position = skipPast(xml, "-->", open + 4);
|
|
139
|
+
else if (xml.startsWith("<![CDATA[", open)) {
|
|
140
|
+
position = skipPast(xml, "]]>", open + 9);
|
|
141
|
+
current.text += xml.slice(open + 9, position - 3);
|
|
142
|
+
} else if (xml.startsWith("<?", open)) position = skipPast(xml, "?>", open + 2);
|
|
143
|
+
else if (xml.startsWith("<!", open)) throw new Error("Malformed XML: DOCTYPE and other declarations are not supported");
|
|
144
|
+
else {
|
|
145
|
+
position = skipPast(xml, ">", open + 1);
|
|
146
|
+
const tag = xml.slice(open + 1, position - 1);
|
|
147
|
+
const closing = tag.startsWith("/");
|
|
148
|
+
const selfClosing = !closing && tag.endsWith("/");
|
|
149
|
+
const name = /^[^\s/]+/.exec(closing ? tag.slice(1) : tag)?.[0];
|
|
150
|
+
if (!name) throw new Error(`Malformed XML: invalid tag <${tag}>`);
|
|
151
|
+
if (closing) {
|
|
152
|
+
if (current.name !== name || stack.length === 1) throw new Error(`Malformed XML: unexpected </${name}>`);
|
|
153
|
+
stack.pop();
|
|
154
|
+
addChild(stack[stack.length - 1], name, current.hasChildren ? current.children : current.text);
|
|
155
|
+
} else if (selfClosing) addChild(current, name, "");
|
|
156
|
+
else stack.push({
|
|
157
|
+
name,
|
|
158
|
+
children: {},
|
|
159
|
+
hasChildren: false,
|
|
160
|
+
text: ""
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (stack.length !== 1) throw new Error(`Malformed XML: unclosed <${stack[stack.length - 1].name}>`);
|
|
165
|
+
return root.children;
|
|
166
|
+
}
|
|
167
|
+
//#endregion
|
|
168
|
+
//#region src/errors.ts
|
|
169
|
+
/**
|
|
170
|
+
* Base class for every error the SDK throws. Catch with `instanceof ArchilError`
|
|
171
|
+
* to handle control-plane and S3 failures uniformly; `status` is the HTTP status
|
|
172
|
+
* code and `code` a machine-readable error code when the server provided one.
|
|
173
|
+
*/
|
|
174
|
+
var ArchilError = class extends Error {
|
|
175
|
+
/** HTTP status code associated with the failure. */
|
|
176
|
+
status;
|
|
177
|
+
/** Machine-readable error code (e.g. an S3 code like "NoSuchKey"), if known. */
|
|
178
|
+
code;
|
|
179
|
+
constructor(message, status, code) {
|
|
180
|
+
super(message);
|
|
181
|
+
this.name = "ArchilError";
|
|
182
|
+
this.status = status;
|
|
183
|
+
this.code = code;
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
/** Error from the control-plane REST API. */
|
|
187
|
+
var ArchilApiError = class extends ArchilError {
|
|
188
|
+
constructor(message, status, code) {
|
|
189
|
+
super(message, status, code);
|
|
190
|
+
this.name = "ArchilApiError";
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
var SandboxPauseError = class extends ArchilError {
|
|
194
|
+
latest;
|
|
195
|
+
constructor(latest) {
|
|
196
|
+
super(`Sandbox entered ${latest.status} before it paused${latest.exitReason ? `: ${latest.exitReason}` : ""}`, 409, "SANDBOX_PAUSE_FAILED");
|
|
197
|
+
this.latest = latest;
|
|
198
|
+
this.name = "SandboxPauseError";
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
var ImageBuildError = class extends ArchilError {
|
|
202
|
+
latest;
|
|
203
|
+
reason;
|
|
204
|
+
constructor(latest) {
|
|
205
|
+
super(`Image ${latest.imageId} build failed: ${latest.failureReason}`, 409, "IMAGE_BUILD_FAILED");
|
|
206
|
+
this.latest = latest;
|
|
207
|
+
this.name = "ImageBuildError";
|
|
208
|
+
this.reason = latest.failureReason;
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
var SandboxFileTransferError = class extends ArchilError {
|
|
212
|
+
operation;
|
|
213
|
+
path;
|
|
214
|
+
constructor(operation, path, cause) {
|
|
215
|
+
super(`Sandbox file ${operation} failed for ${path}: ${cause.message}`, 500, "SANDBOX_FILE_TRANSFER_FAILED");
|
|
216
|
+
this.name = "SandboxFileTransferError";
|
|
217
|
+
this.operation = operation;
|
|
218
|
+
this.path = path;
|
|
219
|
+
this.cause = cause;
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
/**
|
|
223
|
+
* Error from the S3-compatible object API (getObject/putObject/deleteObject/
|
|
224
|
+
* headObject/listObjects). The gateway returns an S3-style XML `<Error>` body;
|
|
225
|
+
* this surfaces its parts as structured fields (`status`, `code`, `requestId`)
|
|
226
|
+
* rather than a raw blob, while keeping the full body on `raw` for debugging.
|
|
227
|
+
*/
|
|
228
|
+
var ArchilS3Error = class extends ArchilError {
|
|
229
|
+
/** S3 request id, if the gateway returned one. */
|
|
230
|
+
requestId;
|
|
231
|
+
/** Raw response body (the XML document), for debugging. */
|
|
232
|
+
raw;
|
|
233
|
+
constructor(opts) {
|
|
234
|
+
const detail = opts.message ?? opts.statusText ?? "";
|
|
235
|
+
const codePart = opts.code ? ` ${opts.code}` : "";
|
|
236
|
+
super(`S3 ${opts.operation} failed: ${opts.statusCode}${codePart}${detail ? ` — ${detail}` : ""}`, opts.statusCode, opts.code);
|
|
237
|
+
this.name = "ArchilS3Error";
|
|
238
|
+
this.requestId = opts.requestId;
|
|
239
|
+
this.raw = opts.raw;
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
function tagString(obj, tag) {
|
|
243
|
+
const value = obj[tag];
|
|
244
|
+
return value === void 0 || value === null ? void 0 : String(value);
|
|
245
|
+
}
|
|
246
|
+
/** Build an ArchilS3Error from a failed S3 response, parsing the XML body. */
|
|
247
|
+
function parseS3Error(operation, statusCode, statusText, body) {
|
|
248
|
+
let err = {};
|
|
249
|
+
try {
|
|
250
|
+
err = parseXml(body).Error ?? {};
|
|
251
|
+
} catch {
|
|
252
|
+
err = {};
|
|
253
|
+
}
|
|
254
|
+
return new ArchilS3Error({
|
|
255
|
+
operation,
|
|
256
|
+
statusCode,
|
|
257
|
+
statusText,
|
|
258
|
+
code: tagString(err, "Code"),
|
|
259
|
+
message: tagString(err, "Message"),
|
|
260
|
+
requestId: tagString(err, "RequestId"),
|
|
261
|
+
raw: body
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
//#endregion
|
|
265
|
+
//#region src/regions.ts
|
|
266
|
+
const REGION_URLS = {
|
|
267
|
+
"aws-us-east-1": "https://control.green.us-east-1.aws.prod.archil.com",
|
|
268
|
+
"aws-us-west-2": "https://control.green.us-west-2.aws.prod.archil.com",
|
|
269
|
+
"aws-eu-west-1": "https://control.green.eu-west-1.aws.prod.archil.com",
|
|
270
|
+
"gcp-us-central1": "https://control.blue.us-central1.gcp.prod.archil.com"
|
|
271
|
+
};
|
|
272
|
+
function resolveBaseUrl(region) {
|
|
273
|
+
const url = REGION_URLS[region];
|
|
274
|
+
if (!url) throw new Error(`Unknown region "${region}". Valid regions: ${Object.keys(REGION_URLS).join(", ")}`);
|
|
275
|
+
return url;
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Derive the S3-compatible endpoint from a control-plane base URL by swapping a
|
|
279
|
+
* leading `control.` hostname segment for `s3.` (e.g.
|
|
280
|
+
* `control.green.us-east-1.…` → `s3.green.us-east-1.…`). Returns undefined if the
|
|
281
|
+
* URL can't be parsed. A host without a `control.` prefix is returned unchanged.
|
|
282
|
+
*/
|
|
283
|
+
function deriveS3BaseUrl(controlBaseUrl) {
|
|
284
|
+
try {
|
|
285
|
+
const u = new URL(controlBaseUrl);
|
|
286
|
+
u.hostname = u.hostname.replace(/^control\./, "s3.");
|
|
287
|
+
return u.toString().replace(/\/$/, "");
|
|
288
|
+
} catch {
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
//#endregion
|
|
293
|
+
//#region src/version.ts
|
|
294
|
+
const VERSION = "1.15.0";
|
|
295
|
+
const USER_AGENT = `archil-js/${VERSION}`;
|
|
296
|
+
//#endregion
|
|
297
|
+
//#region src/client.ts
|
|
298
|
+
function isNodeRuntime() {
|
|
299
|
+
return typeof process !== "undefined" && typeof process.versions?.node === "string";
|
|
300
|
+
}
|
|
301
|
+
const isBun = isNodeRuntime() && process.versions.bun !== void 0;
|
|
302
|
+
const undiciModule = isNodeRuntime() ? isBun ? import("undici/index.js") : import("undici") : void 0;
|
|
303
|
+
const CONTROL_PLANE_CONNECTIONS = 1;
|
|
304
|
+
const IDLE_SESSION_TIMEOUT_MS = 3e4;
|
|
305
|
+
function isAsyncIterableBody(body) {
|
|
306
|
+
return body != null && typeof body === "object" && Symbol.asyncIterator in body;
|
|
307
|
+
}
|
|
308
|
+
async function bufferBody(body) {
|
|
309
|
+
const chunks = [];
|
|
310
|
+
for await (const chunk of body) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
|
|
311
|
+
return Buffer.concat(chunks);
|
|
312
|
+
}
|
|
313
|
+
const bufferRequestBodies = (dispatch) => (options, handler) => {
|
|
314
|
+
if (!isAsyncIterableBody(options.body)) return dispatch(options, handler);
|
|
315
|
+
bufferBody(options.body).then((body) => dispatch({
|
|
316
|
+
...options,
|
|
317
|
+
body
|
|
318
|
+
}, handler), (error) => handler.onResponseError?.({
|
|
319
|
+
aborted: false,
|
|
320
|
+
paused: false,
|
|
321
|
+
reason: null,
|
|
322
|
+
abort() {},
|
|
323
|
+
pause() {},
|
|
324
|
+
resume() {}
|
|
325
|
+
}, error instanceof Error ? error : new Error(String(error))));
|
|
326
|
+
return true;
|
|
327
|
+
};
|
|
328
|
+
const sharedTransports = /* @__PURE__ */ new Map();
|
|
329
|
+
function dispatcherKey(baseUrl, authorization, ca) {
|
|
330
|
+
return JSON.stringify([
|
|
331
|
+
new URL(baseUrl).origin,
|
|
332
|
+
authorization,
|
|
333
|
+
ca?.map((cert) => cert.toString("base64"))
|
|
334
|
+
]);
|
|
335
|
+
}
|
|
336
|
+
function getSharedTransport(key, ca) {
|
|
337
|
+
const existing = sharedTransports.get(key);
|
|
338
|
+
if (existing) return existing;
|
|
339
|
+
const transport = (async () => {
|
|
340
|
+
if (!undiciModule) throw new Error("The pooled control-plane transport requires Node.js");
|
|
341
|
+
const { Agent, fetch } = await undiciModule;
|
|
342
|
+
return {
|
|
343
|
+
fetch,
|
|
344
|
+
dispatcher: new Agent({
|
|
345
|
+
allowH2: true,
|
|
346
|
+
connections: CONTROL_PLANE_CONNECTIONS,
|
|
347
|
+
keepAliveTimeout: IDLE_SESSION_TIMEOUT_MS,
|
|
348
|
+
...ca === void 0 ? {} : { connect: { ca } }
|
|
349
|
+
}).compose(bufferRequestBodies)
|
|
350
|
+
};
|
|
351
|
+
})();
|
|
352
|
+
sharedTransports.set(key, transport);
|
|
353
|
+
transport.catch(() => {
|
|
354
|
+
if (sharedTransports.get(key) === transport) sharedTransports.delete(key);
|
|
355
|
+
});
|
|
356
|
+
return transport;
|
|
357
|
+
}
|
|
358
|
+
function createPooledFetch(baseUrl, authorization, tls) {
|
|
359
|
+
if (!isNodeRuntime()) {
|
|
360
|
+
if (tls?.ca !== void 0) throw new Error("Custom TLS CAs require Node.js");
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
const ca = tls?.ca === void 0 ? void 0 : (Array.isArray(tls.ca) ? tls.ca : [tls.ca]).map((cert) => Buffer.from(cert));
|
|
364
|
+
const key = dispatcherKey(baseUrl, authorization, ca);
|
|
365
|
+
return async (request) => {
|
|
366
|
+
const { fetch, dispatcher } = await getSharedTransport(key, ca);
|
|
367
|
+
const body = request.body === null ? null : new Uint8Array(await request.arrayBuffer());
|
|
368
|
+
return await fetch(request.url, {
|
|
369
|
+
method: request.method,
|
|
370
|
+
headers: [...request.headers],
|
|
371
|
+
body,
|
|
372
|
+
redirect: request.redirect,
|
|
373
|
+
signal: request.signal,
|
|
374
|
+
dispatcher
|
|
375
|
+
});
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* The `Authorization` value for an API key: the key exactly as given, as a
|
|
380
|
+
* bearer token. Credential-injecting proxies substitute a placeholder only when
|
|
381
|
+
* it is the whole token, so the SDK must not add a prefix to it. The control
|
|
382
|
+
* plane accepts the key with or without its `key-` prefix after `Bearer`.
|
|
383
|
+
*/
|
|
384
|
+
function apiKeyAuthorization(apiKey) {
|
|
385
|
+
return `Bearer ${apiKey}`;
|
|
386
|
+
}
|
|
387
|
+
function createApiClient(opts) {
|
|
388
|
+
const baseUrl = opts.baseUrl ?? resolveBaseUrl(opts.region);
|
|
389
|
+
const authorization = apiKeyAuthorization(opts.apiKey);
|
|
390
|
+
return createClient({
|
|
391
|
+
baseUrl,
|
|
392
|
+
fetch: createPooledFetch(baseUrl, authorization, opts.tls),
|
|
393
|
+
headers: {
|
|
394
|
+
Authorization: authorization,
|
|
395
|
+
"User-Agent": USER_AGENT
|
|
396
|
+
}
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Unwrap the API envelope: return data on success, throw ArchilApiError on failure.
|
|
401
|
+
*/
|
|
402
|
+
async function unwrap(promise) {
|
|
403
|
+
return (await unwrapPage(promise)).data;
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Unwrap a paginated list envelope: like {@link unwrap}, but also surface the
|
|
407
|
+
* envelope's `nextCursor` (undefined on the last page or from a server that
|
|
408
|
+
* doesn't paginate).
|
|
409
|
+
*/
|
|
410
|
+
async function unwrapPage(promise) {
|
|
411
|
+
const { data: body, error, response } = await promise;
|
|
412
|
+
if (error || !body) {
|
|
413
|
+
const errBody = error;
|
|
414
|
+
throw new ArchilApiError(errBody?.error ?? `API request failed with status ${response.status}`, response.status, errBody?.code);
|
|
415
|
+
}
|
|
416
|
+
if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status, body.code);
|
|
417
|
+
return {
|
|
418
|
+
data: body.data,
|
|
419
|
+
nextCursor: body.nextCursor
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Unwrap an API response that has no data payload (e.g., delete operations).
|
|
424
|
+
*/
|
|
425
|
+
async function unwrapEmpty(promise) {
|
|
426
|
+
const { data: body, error, response } = await promise;
|
|
427
|
+
if (!error && response.status === 204) return;
|
|
428
|
+
if (error || !body) {
|
|
429
|
+
const errBody = error;
|
|
430
|
+
throw new ArchilApiError(errBody?.error ?? `API request failed with status ${response.status}`, response.status, errBody?.code);
|
|
431
|
+
}
|
|
432
|
+
if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status, body.code);
|
|
433
|
+
}
|
|
434
|
+
//#endregion
|
|
435
|
+
//#region src/exec-options.ts
|
|
436
|
+
/**
|
|
437
|
+
* @internal Copies only the known option keys into a request body. Every key
|
|
438
|
+
* is required here, so an option added to the API fails to compile until it is
|
|
439
|
+
* copied.
|
|
440
|
+
*/
|
|
441
|
+
function execVmBody(options) {
|
|
442
|
+
return {
|
|
443
|
+
baseImage: options?.baseImage,
|
|
444
|
+
imageId: options?.imageId,
|
|
445
|
+
vcpuCount: options?.vcpuCount,
|
|
446
|
+
memSizeMib: options?.memSizeMib,
|
|
447
|
+
network: options?.network
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
const RETRY_BASE_MS = 100;
|
|
451
|
+
const RETRY_CAP_MS = 2e3;
|
|
452
|
+
const TRANSIENT_STATUSES = /* @__PURE__ */ new Set([
|
|
453
|
+
429,
|
|
454
|
+
500,
|
|
455
|
+
502,
|
|
456
|
+
503,
|
|
457
|
+
504
|
|
458
|
+
]);
|
|
459
|
+
const CONNECT_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
460
|
+
"CERT_HAS_EXPIRED",
|
|
461
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
462
|
+
"EAI_AGAIN",
|
|
463
|
+
"ECONNREFUSED",
|
|
464
|
+
"EHOSTUNREACH",
|
|
465
|
+
"ENETUNREACH",
|
|
466
|
+
"ENOTFOUND",
|
|
467
|
+
"ETIMEDOUT",
|
|
468
|
+
"ERR_TLS_CERT_ALTNAME_INVALID",
|
|
469
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
470
|
+
"UNABLE_TO_GET_ISSUER_CERT",
|
|
471
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
472
|
+
"UND_ERR_CONNECT_TIMEOUT"
|
|
473
|
+
]);
|
|
474
|
+
function isTransientStatus(status) {
|
|
475
|
+
return TRANSIENT_STATUSES.has(status);
|
|
476
|
+
}
|
|
477
|
+
function retryDelayMs(attempt) {
|
|
478
|
+
const ceiling = Math.min(RETRY_CAP_MS, RETRY_BASE_MS * 2 ** attempt);
|
|
479
|
+
return Math.random() * ceiling;
|
|
480
|
+
}
|
|
481
|
+
function retrySleep(attempt) {
|
|
482
|
+
return new Promise((resolve) => setTimeout(resolve, retryDelayMs(attempt)));
|
|
483
|
+
}
|
|
484
|
+
function isConnectionEstablishmentError(error) {
|
|
485
|
+
const seen = /* @__PURE__ */ new Set();
|
|
486
|
+
const pending = [error];
|
|
487
|
+
while (pending.length > 0) {
|
|
488
|
+
const current = pending.pop();
|
|
489
|
+
if (!current || seen.has(current)) continue;
|
|
490
|
+
seen.add(current);
|
|
491
|
+
if (typeof current !== "object") continue;
|
|
492
|
+
const value = current;
|
|
493
|
+
const code = typeof value.code === "string" ? value.code : "";
|
|
494
|
+
if (CONNECT_ERROR_CODES.has(code) || code.startsWith("ERR_SSL_") || code.startsWith("ERR_TLS_")) return true;
|
|
495
|
+
if (typeof value.message === "string" && value.message.includes("before secure TLS connection was established")) return true;
|
|
496
|
+
if (value.cause) pending.push(value.cause);
|
|
497
|
+
if (Array.isArray(value.errors)) pending.push(...value.errors);
|
|
498
|
+
}
|
|
499
|
+
return false;
|
|
500
|
+
}
|
|
501
|
+
async function retryApiRequest(request, mode) {
|
|
502
|
+
for (let attempt = 0;; attempt++) {
|
|
503
|
+
try {
|
|
504
|
+
const result = await request();
|
|
505
|
+
if (mode !== "transient" || !isTransientStatus(result.response.status) || attempt >= 3) return result;
|
|
506
|
+
} catch (error) {
|
|
507
|
+
if (!(mode === "transient" || mode === "connect" && isConnectionEstablishmentError(error)) || attempt >= 3) throw error;
|
|
508
|
+
}
|
|
509
|
+
await retrySleep(attempt);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
//#endregion
|
|
513
|
+
//#region src/disk.ts
|
|
514
|
+
var Disk = class {
|
|
515
|
+
id;
|
|
516
|
+
name;
|
|
517
|
+
organization;
|
|
518
|
+
status;
|
|
519
|
+
provider;
|
|
520
|
+
region;
|
|
521
|
+
createdAt;
|
|
522
|
+
fsHandlerStatus;
|
|
523
|
+
lastAccessed;
|
|
524
|
+
activeDataBytes;
|
|
525
|
+
totalDataBytes;
|
|
526
|
+
/** @deprecated Use {@link activeDataBytes}. */
|
|
527
|
+
dataSize;
|
|
528
|
+
monthlyUsage;
|
|
529
|
+
mounts;
|
|
530
|
+
metrics;
|
|
531
|
+
connectedClients;
|
|
532
|
+
authorizedUsers;
|
|
533
|
+
allowedIps;
|
|
534
|
+
/** Root-directory POSIX attributes recorded at creation, if any. */
|
|
535
|
+
rootAttrs;
|
|
536
|
+
/** @internal */
|
|
537
|
+
_client;
|
|
538
|
+
/** @internal */
|
|
539
|
+
_archilRegion;
|
|
540
|
+
/** Base URL for the S3-compatible API (port 9000 ingress). Empty if unset. */
|
|
541
|
+
_s3BaseUrl;
|
|
542
|
+
/** Lazily-constructed multipart namespace (see {@link multipart}). @internal */
|
|
543
|
+
_multipart;
|
|
544
|
+
/** @internal */
|
|
545
|
+
constructor(data, client, archilRegion, s3BaseUrl) {
|
|
546
|
+
this.id = data.id;
|
|
547
|
+
this.name = data.name;
|
|
548
|
+
this.organization = data.organization;
|
|
549
|
+
this.status = data.status;
|
|
550
|
+
this.provider = data.provider;
|
|
551
|
+
this.region = data.region;
|
|
552
|
+
this.createdAt = data.createdAt;
|
|
553
|
+
this.fsHandlerStatus = data.fsHandlerStatus;
|
|
554
|
+
this.lastAccessed = data.lastAccessed;
|
|
555
|
+
this.activeDataBytes = data.activeDataBytes;
|
|
556
|
+
this.totalDataBytes = data.totalDataBytes;
|
|
557
|
+
this.dataSize = data.activeDataBytes;
|
|
558
|
+
this.monthlyUsage = data.monthlyUsage;
|
|
559
|
+
this.mounts = data.mounts;
|
|
560
|
+
this.metrics = data.metrics;
|
|
561
|
+
this.connectedClients = data.connectedClients;
|
|
562
|
+
this.authorizedUsers = data.authorizedUsers;
|
|
563
|
+
this.allowedIps = data.allowedIps;
|
|
564
|
+
this.rootAttrs = data.rootAttrs;
|
|
565
|
+
this._client = client;
|
|
566
|
+
this._archilRegion = archilRegion;
|
|
567
|
+
this._s3BaseUrl = s3BaseUrl ?? "";
|
|
568
|
+
}
|
|
569
|
+
toJSON() {
|
|
570
|
+
return {
|
|
571
|
+
id: this.id,
|
|
572
|
+
name: this.name,
|
|
573
|
+
organization: this.organization,
|
|
574
|
+
status: this.status,
|
|
575
|
+
provider: this.provider,
|
|
576
|
+
region: this.region,
|
|
577
|
+
createdAt: this.createdAt,
|
|
578
|
+
fsHandlerStatus: this.fsHandlerStatus,
|
|
579
|
+
lastAccessed: this.lastAccessed,
|
|
580
|
+
activeDataBytes: this.activeDataBytes,
|
|
581
|
+
totalDataBytes: this.totalDataBytes,
|
|
582
|
+
monthlyUsage: this.monthlyUsage,
|
|
583
|
+
mounts: this.mounts,
|
|
584
|
+
metrics: this.metrics,
|
|
585
|
+
connectedClients: this.connectedClients,
|
|
586
|
+
authorizedUsers: this.authorizedUsers,
|
|
587
|
+
allowedIps: this.allowedIps,
|
|
588
|
+
rootAttrs: this.rootAttrs
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
async addUser(user) {
|
|
592
|
+
return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/users", {
|
|
593
|
+
params: { path: { id: this.id } },
|
|
594
|
+
body: user
|
|
595
|
+
}), "connect"));
|
|
596
|
+
}
|
|
597
|
+
async removeUser(userType, identifier) {
|
|
598
|
+
await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/disks/{id}/users/{userType}", { params: {
|
|
599
|
+
path: {
|
|
600
|
+
id: this.id,
|
|
601
|
+
userType
|
|
602
|
+
},
|
|
603
|
+
query: { identifier }
|
|
604
|
+
} }), "connect"));
|
|
605
|
+
}
|
|
606
|
+
async createToken(nickname) {
|
|
607
|
+
const user = await unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/users", {
|
|
608
|
+
params: { path: { id: this.id } },
|
|
609
|
+
body: {
|
|
610
|
+
type: "token",
|
|
611
|
+
nickname
|
|
612
|
+
}
|
|
613
|
+
}), "connect"));
|
|
614
|
+
if (!user.token || !user.identifier) throw new Error("Server did not return a generated token");
|
|
615
|
+
return user;
|
|
616
|
+
}
|
|
617
|
+
async removeTokenUser(identifier) {
|
|
618
|
+
await this.removeUser("token", identifier);
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* Create an S3 access key pair for this disk's S3 API. The secret key is
|
|
622
|
+
* returned only here. The keys reach the whole disk, read-write unless
|
|
623
|
+
* `readOnly` is set, so keep them server-side and give browsers presigned
|
|
624
|
+
* URLs instead.
|
|
625
|
+
*/
|
|
626
|
+
async createS3Credentials(options = {}) {
|
|
627
|
+
const user = await this.addUser({
|
|
628
|
+
...options,
|
|
629
|
+
type: "s3"
|
|
630
|
+
});
|
|
631
|
+
if (!user.s3AccessKeyId || !user.s3SecretKey || !user.identifier) throw new Error("Server did not return generated S3 credentials");
|
|
632
|
+
return user;
|
|
633
|
+
}
|
|
634
|
+
async removeS3Credentials(accessKeyId) {
|
|
635
|
+
await this.removeUser("s3", accessKeyId);
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* List all delegations currently held on this disk. A delegation grants a
|
|
639
|
+
* client exclusive write access to an inode; it has no ID of its own and is
|
|
640
|
+
* identified by the (clientId, inodeId) pair — pass those to
|
|
641
|
+
* `revokeDelegation` to release one. Entries with `isOrphaned: true` are
|
|
642
|
+
* held by clients no longer connected to the disk (disconnected without
|
|
643
|
+
* checking in). `path` is resolved best-effort by the server and may be
|
|
644
|
+
* absent.
|
|
645
|
+
*/
|
|
646
|
+
async listDelegations() {
|
|
647
|
+
return (await unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}/delegations", { params: { path: { id: this.id } } }), "transient"))).delegations;
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Forcibly revoke a delegation, reclaiming write access from a client that
|
|
651
|
+
* is unreachable or crashed without checking its delegations in.
|
|
652
|
+
*
|
|
653
|
+
* Takes the `(clientId, inodeId)` pair identifying the delegation — pass an
|
|
654
|
+
* entry from `listDelegations` directly:
|
|
655
|
+
*
|
|
656
|
+
* ```ts
|
|
657
|
+
* for (const d of await disk.listDelegations()) {
|
|
658
|
+
* if (d.isOrphaned) await disk.revokeDelegation(d);
|
|
659
|
+
* }
|
|
660
|
+
* ```
|
|
661
|
+
*/
|
|
662
|
+
async revokeDelegation(delegation) {
|
|
663
|
+
const { clientId, inodeId } = delegation;
|
|
664
|
+
await unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/revoke-delegation", {
|
|
665
|
+
params: { path: { id: this.id } },
|
|
666
|
+
body: {
|
|
667
|
+
clientId,
|
|
668
|
+
inodeId
|
|
669
|
+
}
|
|
670
|
+
}), "connect"));
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* Create a branch: an independent, writable fork of this disk that starts
|
|
674
|
+
* from a committed checkpoint. Writes on the branch don't affect its source.
|
|
675
|
+
*
|
|
676
|
+
* Fails with a 409 if a branch with this name already exists or the
|
|
677
|
+
* checkpoint is not yet committed, and a 404 if the checkpoint or
|
|
678
|
+
* `fromBranch` doesn't exist.
|
|
679
|
+
*/
|
|
680
|
+
async createBranch(options) {
|
|
681
|
+
const idempotencyKey = options.idempotencyKey ?? globalThis.crypto.randomUUID();
|
|
682
|
+
return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/branches", {
|
|
683
|
+
params: {
|
|
684
|
+
path: { id: this.id },
|
|
685
|
+
header: { "Idempotency-Key": idempotencyKey }
|
|
686
|
+
},
|
|
687
|
+
body: {
|
|
688
|
+
branch_name: options.name,
|
|
689
|
+
from_checkpoint_name: options.fromCheckpoint,
|
|
690
|
+
from_branch: options.fromBranch
|
|
691
|
+
}
|
|
692
|
+
}), "transient"));
|
|
693
|
+
}
|
|
694
|
+
/** List every branch of this disk, including branches of branches, in no particular order. */
|
|
695
|
+
async listBranches() {
|
|
696
|
+
return unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}/branches", { params: { path: { id: this.id } } }), "transient"));
|
|
697
|
+
}
|
|
698
|
+
async getBranch(name) {
|
|
699
|
+
return unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}/branches/{name}", { params: { path: {
|
|
700
|
+
id: this.id,
|
|
701
|
+
name
|
|
702
|
+
} } }), "transient"));
|
|
703
|
+
}
|
|
704
|
+
async getAllowedIPs() {
|
|
705
|
+
return (await unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}/allowed-ips", { params: { path: { id: this.id } } }), "transient"))).allowedIps;
|
|
706
|
+
}
|
|
707
|
+
async setAllowedIPs(allowedIps) {
|
|
708
|
+
return (await unwrap(retryApiRequest(() => this._client.PUT("/api/disks/{id}/allowed-ips", {
|
|
709
|
+
params: { path: { id: this.id } },
|
|
710
|
+
body: { allowedIps }
|
|
711
|
+
}), "transient"))).allowedIps;
|
|
712
|
+
}
|
|
713
|
+
async addAllowedIP(ip) {
|
|
714
|
+
const current = await this.getAllowedIPs();
|
|
715
|
+
if (current.includes(ip)) return current;
|
|
716
|
+
return this.setAllowedIPs([...current, ip]);
|
|
717
|
+
}
|
|
718
|
+
async removeAllowedIP(ip) {
|
|
719
|
+
const current = await this.getAllowedIPs();
|
|
720
|
+
return this.setAllowedIPs(current.filter((i) => i !== ip));
|
|
721
|
+
}
|
|
722
|
+
async delete() {
|
|
723
|
+
await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/disks/{id}", { params: { path: { id: this.id } } }), "connect"));
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* Execute a command in a container with this disk mounted.
|
|
727
|
+
* Blocks until the command completes and returns stdout, stderr, and exit code.
|
|
728
|
+
*/
|
|
729
|
+
async exec(command, options) {
|
|
730
|
+
return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/exec", {
|
|
731
|
+
params: { path: { id: this.id } },
|
|
732
|
+
body: {
|
|
733
|
+
...execVmBody(options),
|
|
734
|
+
command
|
|
735
|
+
}
|
|
736
|
+
}), "connect"));
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Constant-time parallel grep across files on this disk. Listing and
|
|
740
|
+
* matching are fanned out across ephemeral exec containers; the request
|
|
741
|
+
* finishes within the supplied time budget regardless of dataset size.
|
|
742
|
+
*
|
|
743
|
+
* The returned `stoppedReason` says whether the search ran to completion
|
|
744
|
+
* or short-circuited on `maxResults` / `maxDurationSeconds`. When
|
|
745
|
+
* stopping early, the matches returned are a sample (whichever workers
|
|
746
|
+
* reported first), not the lexicographically first N.
|
|
747
|
+
*/
|
|
748
|
+
async grep(opts) {
|
|
749
|
+
return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/grep", {
|
|
750
|
+
params: { path: { id: this.id } },
|
|
751
|
+
body: {
|
|
752
|
+
directory: opts.directory,
|
|
753
|
+
pattern: opts.pattern,
|
|
754
|
+
recursive: opts.recursive ?? false,
|
|
755
|
+
maxDurationSeconds: opts.maxDurationSeconds ?? 30,
|
|
756
|
+
concurrency: opts.concurrency ?? 50,
|
|
757
|
+
maxResults: opts.maxResults ?? 1e3,
|
|
758
|
+
ignoreCase: opts.ignoreCase,
|
|
759
|
+
multiline: opts.multiline,
|
|
760
|
+
globs: opts.globs,
|
|
761
|
+
types: opts.types,
|
|
762
|
+
typesNot: opts.typesNot,
|
|
763
|
+
contextBefore: opts.contextBefore ?? 0,
|
|
764
|
+
contextAfter: opts.contextAfter ?? 0
|
|
765
|
+
}
|
|
766
|
+
}), "transient"));
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Create a signed, time-limited URL that lets anyone download a single file
|
|
770
|
+
* from this disk without authentication. The returned URL embeds a
|
|
771
|
+
* cryptographically signed token carrying the disk, the file's key, and an
|
|
772
|
+
* expiry — share it directly; no API key is needed to redeem it.
|
|
773
|
+
*
|
|
774
|
+
* @param key Path to the file on the disk (e.g. "reports/2026-01/data.pdf").
|
|
775
|
+
* @param opts `expiresIn` sets the URL lifetime in seconds (any positive
|
|
776
|
+
* integer, max 604800 = 7 days). Defaults to 24h.
|
|
777
|
+
*/
|
|
778
|
+
async share(key, opts = {}) {
|
|
779
|
+
const body = { key };
|
|
780
|
+
if (opts.expiresIn !== void 0) body.expiresIn = opts.expiresIn;
|
|
781
|
+
const call = this._client.POST;
|
|
782
|
+
return unwrap(retryApiRequest(() => call(`/api/disks/${this.id}/share`, { body }), "connect"));
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* Read an object from the disk via the S3-compatible GetObject API and return
|
|
786
|
+
* its full contents as bytes. Throws `ArchilS3Error` if the object does not
|
|
787
|
+
* exist (status 404, code "NoSuchKey") or the request is rejected; use
|
|
788
|
+
* `headObject`/`objectExists` to check existence without throwing.
|
|
789
|
+
*
|
|
790
|
+
* @param key Path on the disk (e.g. "reports/2026-01/data.json")
|
|
791
|
+
*/
|
|
792
|
+
async getObject(key) {
|
|
793
|
+
const resp = await this._s3Request("GET", key);
|
|
794
|
+
if (!resp.ok) throw parseS3Error("GetObject", resp.status, resp.statusText, decodeText(resp.body));
|
|
795
|
+
return resp.body;
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
* Fetch an object's metadata (size, etag, content type, last-modified) without
|
|
799
|
+
* downloading its contents, via the S3-compatible HeadObject API. Returns
|
|
800
|
+
* `null` if the object does not exist.
|
|
801
|
+
*
|
|
802
|
+
* @param key Path on the disk (e.g. "reports/2026-01/data.json")
|
|
803
|
+
*/
|
|
804
|
+
async headObject(key) {
|
|
805
|
+
const resp = await this._s3Request("HEAD", key);
|
|
806
|
+
if (resp.status === 404) return null;
|
|
807
|
+
if (!resp.ok) throw parseS3Error("HeadObject", resp.status, resp.statusText, decodeText(resp.body));
|
|
808
|
+
const lastModified = resp.headers.get("last-modified");
|
|
809
|
+
return {
|
|
810
|
+
size: Number(resp.headers.get("content-length") ?? 0),
|
|
811
|
+
etag: resp.headers.get("etag") ?? void 0,
|
|
812
|
+
contentType: resp.headers.get("content-type") ?? void 0,
|
|
813
|
+
lastModified: lastModified ? new Date(lastModified) : void 0
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
/** Whether an object exists on the disk (a HeadObject that maps 404 → false). */
|
|
817
|
+
async objectExists(key) {
|
|
818
|
+
return await this.headObject(key) !== null;
|
|
819
|
+
}
|
|
820
|
+
/**
|
|
821
|
+
* Write an object to the disk via the S3-compatible API. Handles any size:
|
|
822
|
+
* bodies at or below `multipartThreshold` (defaults to `partSize`, i.e.
|
|
823
|
+
* 16 MiB) go through a single PutObject request; larger bodies are uploaded as
|
|
824
|
+
* a multipart upload — split into `partSize` parts, uploaded with bounded
|
|
825
|
+
* `concurrency` (default 4), and assembled. A failed part aborts the upload so
|
|
826
|
+
* nothing is left half-staged. For manual control over the multipart
|
|
827
|
+
* lifecycle, use the {@link multipart} namespace.
|
|
828
|
+
*
|
|
829
|
+
* Faster than exec for large files — no container overhead, no command-length
|
|
830
|
+
* limits. Returns the entity tag the server assigned (a multipart upload's tag
|
|
831
|
+
* is S3's `md5(concat(partMd5s))-N` form rather than a plain MD5).
|
|
832
|
+
*
|
|
833
|
+
* Optional `mode` / `uid` / `gid` set the POSIX attributes of the published
|
|
834
|
+
* file (e.g. `{ mode: 0o644, uid: 1000, gid: 1000 }` for a non-root agent
|
|
835
|
+
* sandbox). Missing parent directories inherit `uid` / `gid` with mode
|
|
836
|
+
* `0755`; existing directories remain unchanged. A key ending in `/` creates
|
|
837
|
+
* an explicit directory marker whose leaf uses the requested attributes.
|
|
838
|
+
* Defaults are `root:root 0644` for files and `root:root 0755` for directories.
|
|
839
|
+
*
|
|
840
|
+
* @param key Path on the disk (e.g. "reports/2026-01/data.json")
|
|
841
|
+
* @param body Contents as a string, Uint8Array/Buffer, or ArrayBuffer
|
|
842
|
+
* @param options Either a content-type string, or {@link PutObjectOptions}
|
|
843
|
+
* (`contentType`, `multipartThreshold`, `partSize`,
|
|
844
|
+
* `concurrency`, `mode`, `uid`, `gid`). Content type defaults
|
|
845
|
+
* to "application/octet-stream".
|
|
846
|
+
*/
|
|
847
|
+
async putObject(key, body, options) {
|
|
848
|
+
const opts = typeof options === "string" ? { contentType: options } : options ?? {};
|
|
849
|
+
const contentType = opts.contentType ?? "application/octet-stream";
|
|
850
|
+
const partSize = Math.max(opts.partSize ?? DEFAULT_PART_SIZE, MIN_PART_SIZE);
|
|
851
|
+
const threshold = opts.multipartThreshold ?? partSize;
|
|
852
|
+
const bytes = toBytes(body);
|
|
853
|
+
if (bytes.length <= threshold) {
|
|
854
|
+
const resp = await this._s3Request("PUT", key, {
|
|
855
|
+
body,
|
|
856
|
+
contentType,
|
|
857
|
+
extraHeaders: posixCreateHeaders(opts)
|
|
858
|
+
});
|
|
859
|
+
if (!resp.ok) throw parseS3Error("PutObject", resp.status, resp.statusText, decodeText(resp.body));
|
|
860
|
+
return { etag: resp.headers.get("etag") ?? void 0 };
|
|
861
|
+
}
|
|
862
|
+
return this._putMultipart(key, bytes, contentType, partSize, Math.max(1, opts.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY), opts);
|
|
863
|
+
}
|
|
864
|
+
/**
|
|
865
|
+
* Upload a large body through the multipart lifecycle: split into `partSize`
|
|
866
|
+
* parts, upload them with bounded concurrency, then complete — aborting the
|
|
867
|
+
* upload if any part fails so nothing is left half-staged. @internal
|
|
868
|
+
*/
|
|
869
|
+
async _putMultipart(key, bytes, contentType, partSize, concurrency, attrs = {}) {
|
|
870
|
+
const effectivePartSize = effectiveUploadPartSize(bytes.length, partSize);
|
|
871
|
+
const mp = this.multipart;
|
|
872
|
+
const upload = await mp.create(key, contentType, attrs);
|
|
873
|
+
try {
|
|
874
|
+
const partCount = Math.ceil(bytes.length / effectivePartSize);
|
|
875
|
+
const parts = new Array(partCount);
|
|
876
|
+
let next = 0;
|
|
877
|
+
const worker = async () => {
|
|
878
|
+
for (;;) {
|
|
879
|
+
const index = next++;
|
|
880
|
+
if (index >= partCount) return;
|
|
881
|
+
const start = index * effectivePartSize;
|
|
882
|
+
const slice = bytes.subarray(start, Math.min(start + effectivePartSize, bytes.length));
|
|
883
|
+
parts[index] = await mp.uploadPart(key, upload.uploadId, index + 1, slice);
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, partCount) }, worker));
|
|
887
|
+
return { etag: (await mp.complete(key, upload.uploadId, parts)).etag };
|
|
888
|
+
} catch (err) {
|
|
889
|
+
await mp.abort(key, upload.uploadId).catch(() => {});
|
|
890
|
+
throw err;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* Append bytes to an object via the S3-compatible PutObject append extension
|
|
895
|
+
* (`?append=true`). If the object already exists the bytes are appended to it;
|
|
896
|
+
* if it doesn't, it is created. Returns the entity tag of the full object
|
|
897
|
+
* after the append.
|
|
898
|
+
*
|
|
899
|
+
* Each call may append at most 1 MiB — the server rejects a larger body with
|
|
900
|
+
* `EntityTooLarge`. To grow an object past that, append in chunks (or use
|
|
901
|
+
* {@link putObject} for a one-shot large write).
|
|
902
|
+
*
|
|
903
|
+
* Unlike most operations this is NOT auto-retried on a transient error:
|
|
904
|
+
* append isn't idempotent, so retrying a succeeded-but-unacknowledged append
|
|
905
|
+
* would duplicate the bytes. On a transient failure, re-append yourself only
|
|
906
|
+
* after confirming the object's size.
|
|
907
|
+
*
|
|
908
|
+
* When the object does not yet exist, optional `mode` / `uid` / `gid` set the
|
|
909
|
+
* POSIX attributes of the newly created file (same headers as
|
|
910
|
+
* {@link putObject}); missing parents inherit `uid` / `gid` with mode `0755`.
|
|
911
|
+
* Existing files and directories are unchanged.
|
|
912
|
+
*
|
|
913
|
+
* @param key Path on the disk (e.g. "logs/app.log")
|
|
914
|
+
* @param body Bytes to append (string, Uint8Array/Buffer, or ArrayBuffer)
|
|
915
|
+
* @param options Either a content-type string, or {@link AppendObjectOptions}
|
|
916
|
+
* (`contentType`, `mode`, `uid`, `gid`). Content type defaults
|
|
917
|
+
* to "application/octet-stream" and applies only when the
|
|
918
|
+
* object is newly created.
|
|
919
|
+
*/
|
|
920
|
+
async appendObject(key, body, options) {
|
|
921
|
+
const opts = typeof options === "string" ? { contentType: options } : options ?? {};
|
|
922
|
+
const resp = await this._s3Request("PUT", key, {
|
|
923
|
+
body,
|
|
924
|
+
contentType: opts.contentType ?? "application/octet-stream",
|
|
925
|
+
query: { append: "true" },
|
|
926
|
+
retry: false,
|
|
927
|
+
extraHeaders: posixCreateHeaders(opts)
|
|
928
|
+
});
|
|
929
|
+
if (!resp.ok) throw parseS3Error("AppendObject", resp.status, resp.statusText, decodeText(resp.body));
|
|
930
|
+
return { etag: resp.headers.get("etag") ?? void 0 };
|
|
931
|
+
}
|
|
932
|
+
/**
|
|
933
|
+
* Delete an object from the disk via the S3-compatible DeleteObject API.
|
|
934
|
+
* Idempotent: deleting a key that doesn't exist resolves successfully, per
|
|
935
|
+
* S3 semantics.
|
|
936
|
+
*
|
|
937
|
+
* @param key Path on the disk (e.g. "project/dist/server.cjs")
|
|
938
|
+
*/
|
|
939
|
+
async deleteObject(key) {
|
|
940
|
+
const resp = await this._s3Request("DELETE", key);
|
|
941
|
+
if (!resp.ok && resp.status !== 404) throw parseS3Error("DeleteObject", resp.status, resp.statusText, decodeText(resp.body));
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* List objects on the disk via the S3-compatible ListObjectsV2 API. By
|
|
945
|
+
* default this follows continuation tokens until the listing is exhausted and
|
|
946
|
+
* returns every matching key. Use `limit` to cap the total, `singlePage` for a
|
|
947
|
+
* single request, or {@link listObjectsPages} to stream pages without loading
|
|
948
|
+
* everything into memory.
|
|
949
|
+
*
|
|
950
|
+
* @param prefix Only return keys beginning with this prefix (omit for all).
|
|
951
|
+
* @param opts Listing and pagination options.
|
|
952
|
+
*/
|
|
953
|
+
async listObjects(prefix, opts = {}) {
|
|
954
|
+
if (opts.singlePage) return this._listObjectsPage(prefix, opts);
|
|
955
|
+
const objects = [];
|
|
956
|
+
const commonPrefixes = [];
|
|
957
|
+
const seenPrefixes = /* @__PURE__ */ new Set();
|
|
958
|
+
let echoedPrefix;
|
|
959
|
+
let truncated = false;
|
|
960
|
+
outer: for await (const page of this.listObjectsPages(prefix, opts)) {
|
|
961
|
+
echoedPrefix = page.prefix;
|
|
962
|
+
for (const cp of page.commonPrefixes) if (!seenPrefixes.has(cp)) {
|
|
963
|
+
seenPrefixes.add(cp);
|
|
964
|
+
commonPrefixes.push(cp);
|
|
965
|
+
}
|
|
966
|
+
for (const obj of page.objects) {
|
|
967
|
+
if (opts.limit !== void 0 && objects.length >= opts.limit) {
|
|
968
|
+
truncated = true;
|
|
969
|
+
break outer;
|
|
970
|
+
}
|
|
971
|
+
objects.push(obj);
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
return {
|
|
975
|
+
objects,
|
|
976
|
+
commonPrefixes,
|
|
977
|
+
isTruncated: truncated,
|
|
978
|
+
keyCount: objects.length,
|
|
979
|
+
prefix: echoedPrefix
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
/**
|
|
983
|
+
* Yield ListObjectsV2 pages lazily, following continuation tokens. A
|
|
984
|
+
* memory-friendly way to process a large listing without materializing it:
|
|
985
|
+
*
|
|
986
|
+
* ```ts
|
|
987
|
+
* for await (const page of disk.listObjectsPages("logs/")) {
|
|
988
|
+
* for (const obj of page.objects) process(obj);
|
|
989
|
+
* }
|
|
990
|
+
* ```
|
|
991
|
+
*
|
|
992
|
+
* @param prefix Only return keys beginning with this prefix (omit for all).
|
|
993
|
+
* @param opts Listing options (`limit` / `singlePage` are ignored here —
|
|
994
|
+
* control your own loop).
|
|
995
|
+
*/
|
|
996
|
+
async *listObjectsPages(prefix, opts = {}) {
|
|
997
|
+
const seenTokens = /* @__PURE__ */ new Set();
|
|
998
|
+
let continuationToken = opts.continuationToken;
|
|
999
|
+
for (;;) {
|
|
1000
|
+
const page = await this._listObjectsPage(prefix, {
|
|
1001
|
+
...opts,
|
|
1002
|
+
continuationToken
|
|
1003
|
+
});
|
|
1004
|
+
yield page;
|
|
1005
|
+
const next = page.isTruncated ? page.nextContinuationToken : void 0;
|
|
1006
|
+
if (!next || seenTokens.has(next)) break;
|
|
1007
|
+
seenTokens.add(next);
|
|
1008
|
+
continuationToken = next;
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
/** Fetch a single ListObjectsV2 page. @internal */
|
|
1012
|
+
async _listObjectsPage(prefix, opts) {
|
|
1013
|
+
const query = { "list-type": 2 };
|
|
1014
|
+
if (prefix !== void 0) query.prefix = prefix;
|
|
1015
|
+
if (!opts.recursive) query.delimiter = "/";
|
|
1016
|
+
if (opts.continuationToken !== void 0) query["continuation-token"] = opts.continuationToken;
|
|
1017
|
+
if (opts.startAfter !== void 0) query["start-after"] = opts.startAfter;
|
|
1018
|
+
const resp = await this._s3Request("GET", "", { query });
|
|
1019
|
+
if (!resp.ok) throw parseS3Error("ListObjectsV2", resp.status, resp.statusText, decodeText(resp.body));
|
|
1020
|
+
return parseListObjectsResult(decodeText(resp.body));
|
|
1021
|
+
}
|
|
1022
|
+
/**
|
|
1023
|
+
* Delete up to many objects in a single S3-compatible DeleteObjects request.
|
|
1024
|
+
* Unlike {@link deleteObject}, failures are reported per key rather than
|
|
1025
|
+
* thrown: the result's `deleted` lists the keys that were removed and
|
|
1026
|
+
* `errors` lists the ones that weren't (with the server's code/message). A
|
|
1027
|
+
* key that didn't exist still counts as deleted, per S3 semantics.
|
|
1028
|
+
*
|
|
1029
|
+
* The server caps a single request at 1000 keys; this method transparently
|
|
1030
|
+
* splits larger inputs into 1000-key batches and merges the results.
|
|
1031
|
+
*
|
|
1032
|
+
* @param keys Object keys to delete.
|
|
1033
|
+
* @param opts `quiet` suppresses the per-key success list server-side.
|
|
1034
|
+
*/
|
|
1035
|
+
async deleteObjects(keys, opts = {}) {
|
|
1036
|
+
const deleted = [];
|
|
1037
|
+
const errors = [];
|
|
1038
|
+
for (let i = 0; i < keys.length; i += MAX_DELETE_OBJECTS_PER_REQUEST) {
|
|
1039
|
+
const xml = buildDeleteObjectsXml(keys.slice(i, i + MAX_DELETE_OBJECTS_PER_REQUEST), opts.quiet ?? false);
|
|
1040
|
+
const resp = await this._s3Request("POST", "", {
|
|
1041
|
+
query: { delete: "" },
|
|
1042
|
+
body: xml,
|
|
1043
|
+
contentType: "application/xml"
|
|
1044
|
+
});
|
|
1045
|
+
if (!resp.ok) throw parseS3Error("DeleteObjects", resp.status, resp.statusText, decodeText(resp.body));
|
|
1046
|
+
const parsed = parseDeleteObjectsResult(decodeText(resp.body));
|
|
1047
|
+
deleted.push(...parsed.deleted);
|
|
1048
|
+
errors.push(...parsed.errors);
|
|
1049
|
+
}
|
|
1050
|
+
return {
|
|
1051
|
+
deleted,
|
|
1052
|
+
errors
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* The advanced, opt-in multipart-upload API. Drive the raw lifecycle
|
|
1057
|
+
* yourself — `create` → `uploadPart` → `complete` (or `abort`), plus
|
|
1058
|
+
* `listParts` / `listUploads`. Most callers don't need this: {@link putObject}
|
|
1059
|
+
* runs the whole lifecycle automatically for large bodies. Reach for it only
|
|
1060
|
+
* when you need manual control (e.g. uploading parts from separate processes),
|
|
1061
|
+
* and note you then own part-size, memory, and concurrency management.
|
|
1062
|
+
*/
|
|
1063
|
+
get multipart() {
|
|
1064
|
+
return this._multipart ??= new DiskMultipart(this.id, this._s3Request.bind(this));
|
|
1065
|
+
}
|
|
1066
|
+
/**
|
|
1067
|
+
* Send a single request to the disk's S3-compatible endpoint. This reuses the
|
|
1068
|
+
* control-plane client purely for its credential and transport — the same
|
|
1069
|
+
* `Authorization` header is sent and verified by the same code server-side —
|
|
1070
|
+
* pointed at the S3 host. Returns the response status and fully-buffered body
|
|
1071
|
+
* so callers can inspect both regardless of the verb used.
|
|
1072
|
+
*
|
|
1073
|
+
* The S3 routes (`/{diskId}/{key}` for objects, `/{diskId}` for the bucket)
|
|
1074
|
+
* are not part of the typed control-plane API, so the path and per-request
|
|
1075
|
+
* options are passed untyped. An empty `key` targets the bucket itself (used
|
|
1076
|
+
* by listObjects).
|
|
1077
|
+
*
|
|
1078
|
+
* @internal
|
|
1079
|
+
*/
|
|
1080
|
+
async _s3Request(method, key, opts = {}) {
|
|
1081
|
+
if (!this._s3BaseUrl) throw new Error("S3 base URL not configured. Pass s3BaseUrl to new Archil({...}) or set ARCHIL_S3_BASE_URL.");
|
|
1082
|
+
const encodedKey = key.replace(/^\//, "").split("/").map(encodeURIComponent).join("/");
|
|
1083
|
+
const path = encodedKey ? `/${this.id}/${encodedKey}` : `/${this.id}`;
|
|
1084
|
+
const url = `${this._s3BaseUrl.replace(/\/+$/, "")}${path}${buildQuery(opts.query)}`;
|
|
1085
|
+
const init = {
|
|
1086
|
+
body: opts.body,
|
|
1087
|
+
headers: {
|
|
1088
|
+
...opts.contentType ? { "Content-Type": opts.contentType } : {},
|
|
1089
|
+
...opts.extraHeaders
|
|
1090
|
+
}
|
|
1091
|
+
};
|
|
1092
|
+
const hasBody = method === "GET" || method === "POST";
|
|
1093
|
+
const maxRetries = opts.retry === false ? 0 : 3;
|
|
1094
|
+
for (let attempt = 0;; attempt++) {
|
|
1095
|
+
let response;
|
|
1096
|
+
try {
|
|
1097
|
+
response = await this._client.raw(method, url, init);
|
|
1098
|
+
} catch (transportError) {
|
|
1099
|
+
if (attempt < maxRetries) {
|
|
1100
|
+
await retrySleep(attempt);
|
|
1101
|
+
continue;
|
|
1102
|
+
}
|
|
1103
|
+
throw transportError;
|
|
1104
|
+
}
|
|
1105
|
+
if (!response.ok) {
|
|
1106
|
+
if (isTransientStatus(response.status) && attempt < maxRetries) {
|
|
1107
|
+
await response.body?.cancel().catch(() => {});
|
|
1108
|
+
await retrySleep(attempt);
|
|
1109
|
+
continue;
|
|
1110
|
+
}
|
|
1111
|
+
return {
|
|
1112
|
+
ok: false,
|
|
1113
|
+
status: response.status,
|
|
1114
|
+
statusText: response.statusText,
|
|
1115
|
+
headers: response.headers,
|
|
1116
|
+
body: new Uint8Array(await response.arrayBuffer())
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
1119
|
+
if (!hasBody) await response.body?.cancel().catch(() => {});
|
|
1120
|
+
const bytes = hasBody ? new Uint8Array(await response.arrayBuffer()) : /* @__PURE__ */ new Uint8Array(0);
|
|
1121
|
+
return {
|
|
1122
|
+
ok: true,
|
|
1123
|
+
status: response.status,
|
|
1124
|
+
statusText: response.statusText,
|
|
1125
|
+
headers: response.headers,
|
|
1126
|
+
body: bytes
|
|
1127
|
+
};
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
/**
|
|
1131
|
+
* Connect to this disk's data plane via the native ArchilClient.
|
|
1132
|
+
*
|
|
1133
|
+
* Requires the native module to be available (platform-specific .node binary).
|
|
1134
|
+
*/
|
|
1135
|
+
async mount(opts) {
|
|
1136
|
+
let ArchilClient;
|
|
1137
|
+
try {
|
|
1138
|
+
const native = await import("@archildata/native");
|
|
1139
|
+
ArchilClient = native.ArchilClient ?? native.default?.ArchilClient;
|
|
1140
|
+
if (!ArchilClient) throw new Error("@archildata/native did not export ArchilClient");
|
|
1141
|
+
} catch {
|
|
1142
|
+
throw new Error("Native client not available. Install @archildata/native (platform-specific binary) or use ArchilClient.connect() directly. mount() is not supported in browsers.");
|
|
1143
|
+
}
|
|
1144
|
+
return ArchilClient.connect({
|
|
1145
|
+
region: this._archilRegion,
|
|
1146
|
+
diskName: `${this.organization}/${this.name}`,
|
|
1147
|
+
authToken: opts?.authToken,
|
|
1148
|
+
logLevel: opts?.logLevel,
|
|
1149
|
+
serverAddress: opts?.serverAddress,
|
|
1150
|
+
insecure: opts?.insecure
|
|
1151
|
+
});
|
|
1152
|
+
}
|
|
1153
|
+
};
|
|
1154
|
+
/**
|
|
1155
|
+
* The advanced, opt-in multipart-upload namespace, reached via {@link Disk.multipart}.
|
|
1156
|
+
* Drives the raw S3 multipart lifecycle — `create` → `uploadPart` → `complete`
|
|
1157
|
+
* (or `abort`), plus `listParts` / `listUploads`. Prefer {@link Disk.putObject},
|
|
1158
|
+
* which runs this lifecycle automatically for large bodies; use this only when
|
|
1159
|
+
* you need manual control, in which case you own part-size, memory, and
|
|
1160
|
+
* concurrency management.
|
|
1161
|
+
*/
|
|
1162
|
+
var DiskMultipart = class {
|
|
1163
|
+
diskId;
|
|
1164
|
+
s3Request;
|
|
1165
|
+
/** @internal */
|
|
1166
|
+
constructor(diskId, s3Request) {
|
|
1167
|
+
this.diskId = diskId;
|
|
1168
|
+
this.s3Request = s3Request;
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* Start a multipart upload (CreateMultipartUpload) and return its `uploadId`.
|
|
1172
|
+
*
|
|
1173
|
+
* @param key Path on the disk the finished object will live at.
|
|
1174
|
+
* @param contentType MIME type to store the object with.
|
|
1175
|
+
* @param attrs Optional POSIX `mode` / `uid` / `gid` for the completed
|
|
1176
|
+
* object (see {@link PosixCreateAttrs}).
|
|
1177
|
+
*/
|
|
1178
|
+
async create(key, contentType, attrs = {}) {
|
|
1179
|
+
const resp = await this.s3Request("POST", key, {
|
|
1180
|
+
query: { uploads: "" },
|
|
1181
|
+
contentType,
|
|
1182
|
+
extraHeaders: posixCreateHeaders(attrs)
|
|
1183
|
+
});
|
|
1184
|
+
if (!resp.ok) throw parseS3Error("CreateMultipartUpload", resp.status, resp.statusText, decodeText(resp.body));
|
|
1185
|
+
const root = parseXml(decodeText(resp.body)).InitiateMultipartUploadResult ?? {};
|
|
1186
|
+
const uploadId = optionalString(root.UploadId);
|
|
1187
|
+
if (!uploadId) throw new ArchilS3Error({
|
|
1188
|
+
operation: "CreateMultipartUpload",
|
|
1189
|
+
statusCode: resp.status,
|
|
1190
|
+
message: "response did not contain an UploadId",
|
|
1191
|
+
raw: decodeText(resp.body)
|
|
1192
|
+
});
|
|
1193
|
+
return {
|
|
1194
|
+
uploadId,
|
|
1195
|
+
key: optionalString(root.Key) ?? key,
|
|
1196
|
+
bucket: optionalString(root.Bucket) ?? this.diskId
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
/**
|
|
1200
|
+
* Upload one part (UploadPart) and return its entity tag, which you must
|
|
1201
|
+
* collect (with its part number) and pass to {@link complete}. Every part
|
|
1202
|
+
* except the last must be at least 5 MiB.
|
|
1203
|
+
*
|
|
1204
|
+
* @param key The upload's object key.
|
|
1205
|
+
* @param uploadId The id from {@link create}.
|
|
1206
|
+
* @param partNumber 1-based part number (1..=10000).
|
|
1207
|
+
* @param body Part contents as a string, Uint8Array/Buffer, or ArrayBuffer.
|
|
1208
|
+
*/
|
|
1209
|
+
async uploadPart(key, uploadId, partNumber, body) {
|
|
1210
|
+
const resp = await this.s3Request("PUT", key, {
|
|
1211
|
+
query: {
|
|
1212
|
+
uploadId,
|
|
1213
|
+
partNumber
|
|
1214
|
+
},
|
|
1215
|
+
body
|
|
1216
|
+
});
|
|
1217
|
+
if (!resp.ok) throw parseS3Error("UploadPart", resp.status, resp.statusText, decodeText(resp.body));
|
|
1218
|
+
return {
|
|
1219
|
+
partNumber,
|
|
1220
|
+
etag: resp.headers.get("etag") ?? ""
|
|
1221
|
+
};
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Finish a multipart upload (CompleteMultipartUpload), assembling the listed
|
|
1225
|
+
* parts into one object. Parts are sorted by part number before submission
|
|
1226
|
+
* (the server requires strictly-increasing order).
|
|
1227
|
+
*
|
|
1228
|
+
* Unlike the other operations this is NOT auto-retried on a transient error:
|
|
1229
|
+
* the gateway isn't idempotent for completion, so a retry after a
|
|
1230
|
+
* successful-but-unacknowledged complete would return a spurious NoSuchUpload.
|
|
1231
|
+
* On a transient failure, re-drive completion yourself only after confirming
|
|
1232
|
+
* the object isn't already present.
|
|
1233
|
+
*
|
|
1234
|
+
* @param key The upload's object key.
|
|
1235
|
+
* @param uploadId The id from {@link create}.
|
|
1236
|
+
* @param parts The `{ partNumber, etag }` pairs from {@link uploadPart}.
|
|
1237
|
+
*/
|
|
1238
|
+
async complete(key, uploadId, parts) {
|
|
1239
|
+
const xml = buildCompleteMultipartUploadXml([...parts].sort((a, b) => a.partNumber - b.partNumber));
|
|
1240
|
+
const resp = await this.s3Request("POST", key, {
|
|
1241
|
+
query: { uploadId },
|
|
1242
|
+
body: xml,
|
|
1243
|
+
contentType: "application/xml",
|
|
1244
|
+
retry: false
|
|
1245
|
+
});
|
|
1246
|
+
if (!resp.ok) throw parseS3Error("CompleteMultipartUpload", resp.status, resp.statusText, decodeText(resp.body));
|
|
1247
|
+
const root = parseXml(decodeText(resp.body)).CompleteMultipartUploadResult ?? {};
|
|
1248
|
+
return {
|
|
1249
|
+
etag: optionalString(root.ETag),
|
|
1250
|
+
location: optionalString(root.Location),
|
|
1251
|
+
bucket: optionalString(root.Bucket),
|
|
1252
|
+
key: optionalString(root.Key)
|
|
1253
|
+
};
|
|
1254
|
+
}
|
|
1255
|
+
/**
|
|
1256
|
+
* Abort a multipart upload (AbortMultipartUpload), discarding every staged
|
|
1257
|
+
* part. Idempotent against an upload that's already gone (404 / NoSuchUpload
|
|
1258
|
+
* resolves successfully).
|
|
1259
|
+
*
|
|
1260
|
+
* @param key The upload's object key.
|
|
1261
|
+
* @param uploadId The id from {@link create}.
|
|
1262
|
+
*/
|
|
1263
|
+
async abort(key, uploadId) {
|
|
1264
|
+
const resp = await this.s3Request("DELETE", key, { query: { uploadId } });
|
|
1265
|
+
if (!resp.ok && resp.status !== 404) throw parseS3Error("AbortMultipartUpload", resp.status, resp.statusText, decodeText(resp.body));
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* List the parts already uploaded for an in-progress upload (ListParts).
|
|
1269
|
+
* Returns a single page; follow `nextPartNumberMarker` (when `isTruncated`)
|
|
1270
|
+
* to page through the rest.
|
|
1271
|
+
*
|
|
1272
|
+
* @param key The upload's object key.
|
|
1273
|
+
* @param uploadId The id from {@link create}.
|
|
1274
|
+
* @param opts `maxParts` / `partNumberMarker` pagination controls.
|
|
1275
|
+
*/
|
|
1276
|
+
async listParts(key, uploadId, opts = {}) {
|
|
1277
|
+
const query = { uploadId };
|
|
1278
|
+
if (opts.maxParts !== void 0) query["max-parts"] = opts.maxParts;
|
|
1279
|
+
if (opts.partNumberMarker !== void 0) query["part-number-marker"] = opts.partNumberMarker;
|
|
1280
|
+
const resp = await this.s3Request("GET", key, { query });
|
|
1281
|
+
if (!resp.ok) throw parseS3Error("ListParts", resp.status, resp.statusText, decodeText(resp.body));
|
|
1282
|
+
return parseListPartsResult(decodeText(resp.body));
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* List in-progress multipart uploads on the disk (ListMultipartUploads).
|
|
1286
|
+
* Returns a single page; follow `nextKeyMarker` / `nextUploadIdMarker` (when
|
|
1287
|
+
* `isTruncated`) for the rest.
|
|
1288
|
+
*
|
|
1289
|
+
* @param opts Prefix/delimiter filter and pagination markers.
|
|
1290
|
+
*/
|
|
1291
|
+
async listUploads(opts = {}) {
|
|
1292
|
+
const query = { uploads: "" };
|
|
1293
|
+
if (opts.prefix !== void 0) query.prefix = opts.prefix;
|
|
1294
|
+
if (opts.delimiter !== void 0) query.delimiter = opts.delimiter;
|
|
1295
|
+
if (opts.keyMarker !== void 0) query["key-marker"] = opts.keyMarker;
|
|
1296
|
+
if (opts.uploadIdMarker !== void 0) query["upload-id-marker"] = opts.uploadIdMarker;
|
|
1297
|
+
if (opts.maxUploads !== void 0) query["max-uploads"] = opts.maxUploads;
|
|
1298
|
+
const resp = await this.s3Request("GET", "", { query });
|
|
1299
|
+
if (!resp.ok) throw parseS3Error("ListMultipartUploads", resp.status, resp.statusText, decodeText(resp.body));
|
|
1300
|
+
return parseListMultipartUploadsResult(decodeText(resp.body));
|
|
1301
|
+
}
|
|
1302
|
+
};
|
|
1303
|
+
/**
|
|
1304
|
+
* Headers the S3 gateway accepts to set POSIX mode/owner on newly created
|
|
1305
|
+
* objects (see fshandler `x-archil-*` PutObject attrs).
|
|
1306
|
+
*/
|
|
1307
|
+
const ARCHIL_MODE_HEADER = "x-archil-mode";
|
|
1308
|
+
const ARCHIL_UID_HEADER = "x-archil-uid";
|
|
1309
|
+
const ARCHIL_GID_HEADER = "x-archil-gid";
|
|
1310
|
+
/**
|
|
1311
|
+
* Build the `x-archil-*` headers for {@link PosixCreateAttrs}. `mode` is sent
|
|
1312
|
+
* in octal (`0o640` → "640"), matching the gateway's parser and the Python SDK.
|
|
1313
|
+
* Returns undefined when no attribute is set, so no headers are added.
|
|
1314
|
+
*/
|
|
1315
|
+
function posixCreateHeaders(attrs) {
|
|
1316
|
+
const headers = {};
|
|
1317
|
+
if (attrs.mode !== void 0) headers[ARCHIL_MODE_HEADER] = attrs.mode.toString(8);
|
|
1318
|
+
if (attrs.uid !== void 0) headers[ARCHIL_UID_HEADER] = String(attrs.uid);
|
|
1319
|
+
if (attrs.gid !== void 0) headers[ARCHIL_GID_HEADER] = String(attrs.gid);
|
|
1320
|
+
return Object.keys(headers).length > 0 ? headers : void 0;
|
|
1321
|
+
}
|
|
1322
|
+
/** S3's per-request cap on DeleteObjects keys; larger inputs are batched. */
|
|
1323
|
+
const MAX_DELETE_OBJECTS_PER_REQUEST = 1e3;
|
|
1324
|
+
/** S3's minimum size for every multipart part but the last (5 MiB). */
|
|
1325
|
+
const MIN_PART_SIZE = 5 * 1024 * 1024;
|
|
1326
|
+
/** Default part size {@link Disk.putObject} uses on the multipart path (16 MiB). */
|
|
1327
|
+
const DEFAULT_PART_SIZE = 16 * 1024 * 1024;
|
|
1328
|
+
/** Default number of parts {@link Disk.putObject} uploads in parallel. */
|
|
1329
|
+
const DEFAULT_UPLOAD_CONCURRENCY = 4;
|
|
1330
|
+
/** The server's cap on parts in a single multipart upload (MAX_PARTS_PER_UPLOAD). */
|
|
1331
|
+
const MAX_PARTS_PER_UPLOAD = 1e4;
|
|
1332
|
+
/**
|
|
1333
|
+
* Choose the part size for a `totalBytes` multipart upload. Returns
|
|
1334
|
+
* `requestedPartSize` unless splitting at that size would exceed the server's
|
|
1335
|
+
* 10,000-part cap, in which case it grows the part size (rounded up to a whole
|
|
1336
|
+
* MiB) so the body fits in ≤ 10,000 parts — mirroring boto3's chunk-size
|
|
1337
|
+
* adjustment. Parts only ever get larger, so they stay above the 5 MiB floor.
|
|
1338
|
+
*/
|
|
1339
|
+
function effectiveUploadPartSize(totalBytes, requestedPartSize) {
|
|
1340
|
+
if (Math.ceil(totalBytes / requestedPartSize) <= MAX_PARTS_PER_UPLOAD) return requestedPartSize;
|
|
1341
|
+
const MiB = 1024 * 1024;
|
|
1342
|
+
const needed = Math.ceil(totalBytes / MAX_PARTS_PER_UPLOAD);
|
|
1343
|
+
return Math.ceil(needed / MiB) * MiB;
|
|
1344
|
+
}
|
|
1345
|
+
/** Normalize an upload body to bytes so it can be sized and sliced into parts. */
|
|
1346
|
+
function toBytes(body) {
|
|
1347
|
+
if (typeof body === "string") return new TextEncoder().encode(body);
|
|
1348
|
+
if (body instanceof Uint8Array) return body;
|
|
1349
|
+
return new Uint8Array(body);
|
|
1350
|
+
}
|
|
1351
|
+
/** Escape text for safe inclusion in XML element content. */
|
|
1352
|
+
function escapeXml(value) {
|
|
1353
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
1354
|
+
}
|
|
1355
|
+
/** Build a `<Delete>` request body for the DeleteObjects API. */
|
|
1356
|
+
function buildDeleteObjectsXml(keys, quiet) {
|
|
1357
|
+
return `<?xml version="1.0" encoding="UTF-8"?><Delete>${keys.map((k) => `<Object><Key>${escapeXml(k)}</Key></Object>`).join("")}${quiet ? "<Quiet>true</Quiet>" : ""}</Delete>`;
|
|
1358
|
+
}
|
|
1359
|
+
/** Build a `<CompleteMultipartUpload>` request body from the uploaded parts. */
|
|
1360
|
+
function buildCompleteMultipartUploadXml(parts) {
|
|
1361
|
+
return `<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${parts.map((p) => `<Part><PartNumber>${p.partNumber}</PartNumber><ETag>${escapeXml(p.etag)}</ETag></Part>`).join("")}</CompleteMultipartUpload>`;
|
|
1362
|
+
}
|
|
1363
|
+
/** Coerce a parser value that may be a single object or an array into an array. */
|
|
1364
|
+
function asArray(value) {
|
|
1365
|
+
if (value === void 0 || value === null) return [];
|
|
1366
|
+
return Array.isArray(value) ? value : [value];
|
|
1367
|
+
}
|
|
1368
|
+
function optionalNumber(value) {
|
|
1369
|
+
return value === void 0 || value === null ? void 0 : Number(value);
|
|
1370
|
+
}
|
|
1371
|
+
function optionalString(value) {
|
|
1372
|
+
return value === void 0 || value === null ? void 0 : String(value);
|
|
1373
|
+
}
|
|
1374
|
+
function optionalDate(value) {
|
|
1375
|
+
return value === void 0 || value === null ? void 0 : new Date(String(value));
|
|
1376
|
+
}
|
|
1377
|
+
/** Decode response bytes to a UTF-8 string (used for XML error/result bodies). */
|
|
1378
|
+
function decodeText(bytes) {
|
|
1379
|
+
return new TextDecoder().decode(bytes);
|
|
1380
|
+
}
|
|
1381
|
+
/** Parse an S3 ListObjectsV2 `<ListBucketResult>` XML document. */
|
|
1382
|
+
function parseListObjectsResult(xml) {
|
|
1383
|
+
const root = parseXml(xml).ListBucketResult ?? {};
|
|
1384
|
+
const objects = (root.Contents ?? []).map((c) => ({
|
|
1385
|
+
key: String(c.Key ?? ""),
|
|
1386
|
+
size: Number(c.Size ?? 0),
|
|
1387
|
+
etag: optionalString(c.ETag),
|
|
1388
|
+
lastModified: optionalDate(c.LastModified)
|
|
1389
|
+
}));
|
|
1390
|
+
return {
|
|
1391
|
+
objects,
|
|
1392
|
+
commonPrefixes: (root.CommonPrefixes ?? []).map((cp) => optionalString(cp.Prefix)).filter((p) => p !== void 0),
|
|
1393
|
+
isTruncated: root.IsTruncated === "true" || root.IsTruncated === true,
|
|
1394
|
+
nextContinuationToken: optionalString(root.NextContinuationToken),
|
|
1395
|
+
keyCount: root.KeyCount !== void 0 ? Number(root.KeyCount) : objects.length,
|
|
1396
|
+
prefix: optionalString(root.Prefix)
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
function xmlIsTruncated(value) {
|
|
1400
|
+
return value === "true" || value === true;
|
|
1401
|
+
}
|
|
1402
|
+
/** Parse an S3 DeleteObjects `<DeleteResult>` XML document. */
|
|
1403
|
+
function parseDeleteObjectsResult(xml) {
|
|
1404
|
+
const root = parseXml(xml).DeleteResult ?? {};
|
|
1405
|
+
return {
|
|
1406
|
+
deleted: asArray(root.Deleted).map((d) => optionalString(d.Key)).filter((k) => k !== void 0),
|
|
1407
|
+
errors: asArray(root.Error).map((e) => ({
|
|
1408
|
+
key: String(e.Key ?? ""),
|
|
1409
|
+
code: optionalString(e.Code),
|
|
1410
|
+
message: optionalString(e.Message)
|
|
1411
|
+
}))
|
|
1412
|
+
};
|
|
1413
|
+
}
|
|
1414
|
+
/** Parse an S3 `<ListPartsResult>` XML document. */
|
|
1415
|
+
function parseListPartsResult(xml) {
|
|
1416
|
+
const root = parseXml(xml).ListPartsResult ?? {};
|
|
1417
|
+
const parts = asArray(root.Part).map((p) => ({
|
|
1418
|
+
partNumber: Number(p.PartNumber ?? 0),
|
|
1419
|
+
etag: optionalString(p.ETag),
|
|
1420
|
+
size: Number(p.Size ?? 0),
|
|
1421
|
+
lastModified: optionalDate(p.LastModified)
|
|
1422
|
+
}));
|
|
1423
|
+
return {
|
|
1424
|
+
bucket: optionalString(root.Bucket),
|
|
1425
|
+
key: optionalString(root.Key),
|
|
1426
|
+
uploadId: optionalString(root.UploadId),
|
|
1427
|
+
parts,
|
|
1428
|
+
isTruncated: xmlIsTruncated(root.IsTruncated),
|
|
1429
|
+
partNumberMarker: Number(root.PartNumberMarker ?? 0),
|
|
1430
|
+
nextPartNumberMarker: optionalNumber(root.NextPartNumberMarker),
|
|
1431
|
+
maxParts: Number(root.MaxParts ?? parts.length)
|
|
1432
|
+
};
|
|
1433
|
+
}
|
|
1434
|
+
/** Parse an S3 `<ListMultipartUploadsResult>` XML document. */
|
|
1435
|
+
function parseListMultipartUploadsResult(xml) {
|
|
1436
|
+
const root = parseXml(xml).ListMultipartUploadsResult ?? {};
|
|
1437
|
+
const uploads = asArray(root.Upload).map((u) => ({
|
|
1438
|
+
key: String(u.Key ?? ""),
|
|
1439
|
+
uploadId: String(u.UploadId ?? ""),
|
|
1440
|
+
initiated: optionalDate(u.Initiated)
|
|
1441
|
+
}));
|
|
1442
|
+
const commonPrefixes = asArray(root.CommonPrefixes).map((cp) => optionalString(cp.Prefix)).filter((p) => p !== void 0);
|
|
1443
|
+
return {
|
|
1444
|
+
bucket: optionalString(root.Bucket),
|
|
1445
|
+
uploads,
|
|
1446
|
+
commonPrefixes,
|
|
1447
|
+
isTruncated: xmlIsTruncated(root.IsTruncated),
|
|
1448
|
+
keyMarker: optionalString(root.KeyMarker),
|
|
1449
|
+
uploadIdMarker: optionalString(root.UploadIdMarker),
|
|
1450
|
+
nextKeyMarker: optionalString(root.NextKeyMarker),
|
|
1451
|
+
nextUploadIdMarker: optionalString(root.NextUploadIdMarker),
|
|
1452
|
+
prefix: optionalString(root.Prefix),
|
|
1453
|
+
delimiter: optionalString(root.Delimiter),
|
|
1454
|
+
maxUploads: optionalNumber(root.MaxUploads)
|
|
1455
|
+
};
|
|
1456
|
+
}
|
|
1457
|
+
//#endregion
|
|
1458
|
+
//#region src/disks.ts
|
|
1459
|
+
/** Server-side maximum page size for GET /api/disks. */
|
|
1460
|
+
const DISK_PAGE_LIMIT = 100;
|
|
1461
|
+
var Disks = class {
|
|
1462
|
+
/** @internal */
|
|
1463
|
+
_client;
|
|
1464
|
+
/** @internal */
|
|
1465
|
+
_region;
|
|
1466
|
+
/** @internal */
|
|
1467
|
+
_s3BaseUrl;
|
|
1468
|
+
/** @internal */
|
|
1469
|
+
constructor(client, region, s3BaseUrl) {
|
|
1470
|
+
this._client = client;
|
|
1471
|
+
this._region = region;
|
|
1472
|
+
this._s3BaseUrl = s3BaseUrl;
|
|
1473
|
+
}
|
|
1474
|
+
/**
|
|
1475
|
+
* List the account's disks. Fetches in cursor-driven pages (bounded server
|
|
1476
|
+
* work per request) and follows `nextCursor` until exhausted, so the result
|
|
1477
|
+
* is complete even for very large accounts. Use `limit` to cap the total, or
|
|
1478
|
+
* {@link listPage} to walk pages yourself.
|
|
1479
|
+
*/
|
|
1480
|
+
async list(opts) {
|
|
1481
|
+
if (opts?.name !== void 0) return (await this.listPage(opts)).disks;
|
|
1482
|
+
const limit = opts?.limit;
|
|
1483
|
+
let cursor = opts?.cursor;
|
|
1484
|
+
const disks = [];
|
|
1485
|
+
for (;;) {
|
|
1486
|
+
const remaining = limit === void 0 ? void 0 : limit - disks.length;
|
|
1487
|
+
if (remaining !== void 0 && remaining <= 0) return disks;
|
|
1488
|
+
const pageLimit = remaining === void 0 ? DISK_PAGE_LIMIT : Math.min(remaining, DISK_PAGE_LIMIT);
|
|
1489
|
+
const page = await this.listPage({
|
|
1490
|
+
limit: pageLimit,
|
|
1491
|
+
cursor
|
|
1492
|
+
});
|
|
1493
|
+
disks.push(...remaining === void 0 ? page.disks : page.disks.slice(0, remaining));
|
|
1494
|
+
if (!page.nextCursor || page.nextCursor === cursor) return disks;
|
|
1495
|
+
cursor = page.nextCursor;
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
/**
|
|
1499
|
+
* Fetch a single page of disks. `nextCursor` on the result resumes the
|
|
1500
|
+
* listing (it can also be persisted, e.g. across requests of a paginated UI).
|
|
1501
|
+
*/
|
|
1502
|
+
async listPage(opts) {
|
|
1503
|
+
const { data, nextCursor } = await unwrapPage(retryApiRequest(() => this._client.GET("/api/disks", { params: { query: {
|
|
1504
|
+
limit: opts?.limit,
|
|
1505
|
+
cursor: opts?.cursor,
|
|
1506
|
+
name: opts?.name
|
|
1507
|
+
} } }), "transient"));
|
|
1508
|
+
const disks = (data ?? []).map((d) => new Disk(d, this._client, this._region, this._s3BaseUrl));
|
|
1509
|
+
return nextCursor ? {
|
|
1510
|
+
disks,
|
|
1511
|
+
nextCursor
|
|
1512
|
+
} : { disks };
|
|
1513
|
+
}
|
|
1514
|
+
async get(id) {
|
|
1515
|
+
return new Disk(await unwrap(retryApiRequest(() => this._client.GET("/api/disks/{id}", { params: { path: { id } } }), "transient")), this._client, this._region, this._s3BaseUrl);
|
|
1516
|
+
}
|
|
1517
|
+
/**
|
|
1518
|
+
* Create a new disk with an auto-generated mount token.
|
|
1519
|
+
*
|
|
1520
|
+
* Returns the Disk, the one-time token (save it — it cannot be retrieved
|
|
1521
|
+
* again), and the token identifier for later management.
|
|
1522
|
+
*
|
|
1523
|
+
* `rootAttrs` sets the POSIX owner and mode of the disk's root directory
|
|
1524
|
+
* (e.g. `{ uid: 1000, gid: 1000, mode: 0o755 }` so an unprivileged process
|
|
1525
|
+
* can create entries under the mount root without a post-mount `chown`).
|
|
1526
|
+
* Creation-time only.
|
|
1527
|
+
*/
|
|
1528
|
+
async create(req) {
|
|
1529
|
+
const resp = await unwrap(retryApiRequest(() => this._client.POST("/api/disks", { body: req }), "connect"));
|
|
1530
|
+
if (!resp.diskId) throw new Error("API returned success but no diskId");
|
|
1531
|
+
const authorizedUsers = resp.authorizedUsers ?? [];
|
|
1532
|
+
const tokenUser = authorizedUsers.find((u) => u.token);
|
|
1533
|
+
return {
|
|
1534
|
+
disk: await this.get(resp.diskId),
|
|
1535
|
+
token: tokenUser?.token ?? null,
|
|
1536
|
+
tokenIdentifier: tokenUser?.identifier ?? null,
|
|
1537
|
+
authorizedUsers
|
|
1538
|
+
};
|
|
1539
|
+
}
|
|
1540
|
+
/**
|
|
1541
|
+
* Execute a command on a disk that is already known to exist. Accepts the
|
|
1542
|
+
* disk ID directly so callers that do not need its metadata can execute
|
|
1543
|
+
* without fetching the disk first.
|
|
1544
|
+
*/
|
|
1545
|
+
async exec(id, command, options) {
|
|
1546
|
+
return unwrap(retryApiRequest(() => this._client.POST("/api/disks/{id}/exec", {
|
|
1547
|
+
params: { path: { id } },
|
|
1548
|
+
body: {
|
|
1549
|
+
...execVmBody(options),
|
|
1550
|
+
command
|
|
1551
|
+
}
|
|
1552
|
+
}), "connect"));
|
|
1553
|
+
}
|
|
1554
|
+
};
|
|
1555
|
+
//#endregion
|
|
1556
|
+
//#region src/images.ts
|
|
1557
|
+
const DEFAULT_BUILD_TIMEOUT_SECONDS = 1800;
|
|
1558
|
+
const MAX_INTERRUPTED_RETRIES = 3;
|
|
1559
|
+
const REQUEST_AGAIN_MS = 2 * 6e4;
|
|
1560
|
+
const FIRST_POLL_MS = 1e3;
|
|
1561
|
+
const MAX_POLL_MS = 5e3;
|
|
1562
|
+
function imageFromWire(data) {
|
|
1563
|
+
return {
|
|
1564
|
+
imageId: data.image_id,
|
|
1565
|
+
source: data.source,
|
|
1566
|
+
private: data.private,
|
|
1567
|
+
status: data.status,
|
|
1568
|
+
digest: data.digest,
|
|
1569
|
+
canonicalSource: data.canonical_source,
|
|
1570
|
+
failureReason: data.failure_reason,
|
|
1571
|
+
vcpuCount: data.vcpu_count,
|
|
1572
|
+
memSizeMiB: data.mem_size_mib,
|
|
1573
|
+
createdAt: new Date(data.created_at),
|
|
1574
|
+
updatedAt: new Date(data.updated_at)
|
|
1575
|
+
};
|
|
1576
|
+
}
|
|
1577
|
+
var Images = class {
|
|
1578
|
+
/** @internal */
|
|
1579
|
+
_client;
|
|
1580
|
+
/** @internal */
|
|
1581
|
+
constructor(client) {
|
|
1582
|
+
this._client = client;
|
|
1583
|
+
}
|
|
1584
|
+
async get(imageId) {
|
|
1585
|
+
return imageFromWire(await unwrap(retryApiRequest(() => this._client.GET("/api/images/{image_id}", { params: { path: { image_id: imageId } } }), "transient")));
|
|
1586
|
+
}
|
|
1587
|
+
/**
|
|
1588
|
+
* Build a sandbox image from an OCI reference and wait until it is ready.
|
|
1589
|
+
* Returns at once when the image is already built from a digest reference
|
|
1590
|
+
* and joins a build that is already running. A tag is rebuilt on each call
|
|
1591
|
+
* in case it moved, so call this once and reuse `imageId`. Interrupted
|
|
1592
|
+
* builds are requested again up to three times; other failures throw
|
|
1593
|
+
* {@link ImageBuildError}.
|
|
1594
|
+
*/
|
|
1595
|
+
async build(request, options = {}) {
|
|
1596
|
+
const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_BUILD_TIMEOUT_SECONDS;
|
|
1597
|
+
const deadline = Date.now() + timeoutSeconds * 1e3;
|
|
1598
|
+
let image = await this._request(request);
|
|
1599
|
+
let lastRequest = Date.now();
|
|
1600
|
+
let retries = 0;
|
|
1601
|
+
let pollMs = FIRST_POLL_MS;
|
|
1602
|
+
for (;;) {
|
|
1603
|
+
if (image.status === "ready") return image;
|
|
1604
|
+
if (image.status === "failed") {
|
|
1605
|
+
if (image.failureReason !== "interrupted" || retries >= MAX_INTERRUPTED_RETRIES) throw new ImageBuildError(image);
|
|
1606
|
+
retries++;
|
|
1607
|
+
image = await this._request(request);
|
|
1608
|
+
lastRequest = Date.now();
|
|
1609
|
+
continue;
|
|
1610
|
+
}
|
|
1611
|
+
if (Date.now() >= deadline) throw new ArchilError(`Image ${image.imageId} was not ready after ${timeoutSeconds} seconds`, 408, "IMAGE_BUILD_TIMEOUT");
|
|
1612
|
+
await new Promise((resolve) => setTimeout(resolve, pollMs));
|
|
1613
|
+
pollMs = Math.min(pollMs * 2, MAX_POLL_MS);
|
|
1614
|
+
image = await this.get(image.imageId);
|
|
1615
|
+
if (image.status === "building" && Date.now() - lastRequest >= REQUEST_AGAIN_MS) {
|
|
1616
|
+
image = await this._request(request);
|
|
1617
|
+
lastRequest = Date.now();
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
async _request(request) {
|
|
1622
|
+
return imageFromWire(await unwrap(retryApiRequest(() => this._client.POST("/api/images", { body: {
|
|
1623
|
+
source: request.source,
|
|
1624
|
+
registry_auth: request.registryAuth,
|
|
1625
|
+
vcpu_count: request.vcpuCount,
|
|
1626
|
+
mem_size_mib: request.memSizeMiB
|
|
1627
|
+
} }), "transient")));
|
|
1628
|
+
}
|
|
1629
|
+
};
|
|
1630
|
+
//#endregion
|
|
1631
|
+
//#region src/process-output-buffer.ts
|
|
1632
|
+
/**
|
|
1633
|
+
* Output each process has received but its iterator has not taken yet.
|
|
1634
|
+
* Flow control bounds it to one channel window per process, so it never
|
|
1635
|
+
* needs to refuse output. Output a handle never reads goes with the handle.
|
|
1636
|
+
*/
|
|
1637
|
+
var ProcessOutputBuffer = class {
|
|
1638
|
+
queues = /* @__PURE__ */ new WeakMap();
|
|
1639
|
+
has(subscription) {
|
|
1640
|
+
return !!this.queues.get(subscription)?.length;
|
|
1641
|
+
}
|
|
1642
|
+
push(subscription, output) {
|
|
1643
|
+
const queue = this.queues.get(subscription) ?? [];
|
|
1644
|
+
queue.push(output);
|
|
1645
|
+
this.queues.set(subscription, queue);
|
|
1646
|
+
}
|
|
1647
|
+
take(subscription) {
|
|
1648
|
+
const queue = this.queues.get(subscription);
|
|
1649
|
+
const output = queue?.shift();
|
|
1650
|
+
if (queue && !queue.length) this.queues.delete(subscription);
|
|
1651
|
+
return output;
|
|
1652
|
+
}
|
|
1653
|
+
discard(subscription) {
|
|
1654
|
+
this.queues.delete(subscription);
|
|
1655
|
+
}
|
|
1656
|
+
};
|
|
1657
|
+
//#endregion
|
|
1658
|
+
//#region src/process-connection.ts
|
|
1659
|
+
async function waitForSocketOpen(socket) {
|
|
1660
|
+
if (socket.readyState === WebSocket.OPEN) return;
|
|
1661
|
+
await new Promise((resolve, reject) => {
|
|
1662
|
+
const cleanup = () => {
|
|
1663
|
+
socket.removeEventListener("open", opened);
|
|
1664
|
+
socket.removeEventListener("error", failed);
|
|
1665
|
+
socket.removeEventListener("close", closed);
|
|
1666
|
+
};
|
|
1667
|
+
const opened = () => {
|
|
1668
|
+
cleanup();
|
|
1669
|
+
resolve();
|
|
1670
|
+
};
|
|
1671
|
+
const failed = () => {
|
|
1672
|
+
cleanup();
|
|
1673
|
+
reject(/* @__PURE__ */ new Error("Process connection failed"));
|
|
1674
|
+
};
|
|
1675
|
+
const closed = () => {
|
|
1676
|
+
cleanup();
|
|
1677
|
+
reject(/* @__PURE__ */ new Error("Process connection closed before opening"));
|
|
1678
|
+
};
|
|
1679
|
+
socket.addEventListener("open", opened, { once: true });
|
|
1680
|
+
socket.addEventListener("error", failed, { once: true });
|
|
1681
|
+
socket.addEventListener("close", closed, { once: true });
|
|
1682
|
+
});
|
|
1683
|
+
}
|
|
1684
|
+
async function openProcessSocket(connectionEndpoint) {
|
|
1685
|
+
for (let attempt = 0;; attempt++) {
|
|
1686
|
+
const endpoint = await connectionEndpoint();
|
|
1687
|
+
let socket;
|
|
1688
|
+
try {
|
|
1689
|
+
socket = new WebSocket(endpoint.url, [PROTOCOL, `${TOKEN_PROTOCOL_PREFIX}${endpoint.token}`]);
|
|
1690
|
+
socket.binaryType = "arraybuffer";
|
|
1691
|
+
await waitForSocketOpen(socket);
|
|
1692
|
+
return socket;
|
|
1693
|
+
} catch (error) {
|
|
1694
|
+
try {
|
|
1695
|
+
socket?.close();
|
|
1696
|
+
} catch {}
|
|
1697
|
+
if (attempt >= 3) throw new Error(`Process connection failed after ${attempt + 1} attempts`, { cause: error });
|
|
1698
|
+
}
|
|
1699
|
+
await retrySleep(attempt);
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
/** Bound queued socket writes across all channels of a connection. */
|
|
1703
|
+
async function waitForProcessWrite(socket) {
|
|
1704
|
+
while (socket.bufferedAmount > 256 * 1024) {
|
|
1705
|
+
if (socket.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
|
|
1706
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
const PROTOCOL = "archil.connect.v2";
|
|
1710
|
+
const TOKEN_PROTOCOL_PREFIX = "archil.token.";
|
|
1711
|
+
const MAX_DATA = _archildata_api_types_process.Limits.MAX_DATA_BYTES;
|
|
1712
|
+
const INITIAL_WINDOW = _archildata_api_types_process.Limits.INITIAL_WINDOW;
|
|
1713
|
+
const MIN_DATA_COST = _archildata_api_types_process.Limits.MIN_DATA_COST;
|
|
1714
|
+
const dataCost = (length) => Math.max(length, MIN_DATA_COST);
|
|
1715
|
+
const MAX_CHANNELS = 128;
|
|
1716
|
+
const IDLE_MS = 5e3;
|
|
1717
|
+
/** Owns only the client connection. A disconnected transport never retries START. */
|
|
1718
|
+
var ProcessConnection = class {
|
|
1719
|
+
endpoint;
|
|
1720
|
+
opening;
|
|
1721
|
+
binary;
|
|
1722
|
+
/** Every open connection, including ones a drain or full channel table left behind. */
|
|
1723
|
+
live = /* @__PURE__ */ new Set();
|
|
1724
|
+
generation = 0;
|
|
1725
|
+
constructor(endpoint) {
|
|
1726
|
+
this.endpoint = endpoint;
|
|
1727
|
+
}
|
|
1728
|
+
async open() {
|
|
1729
|
+
for (;;) {
|
|
1730
|
+
if (this.binary?.canOpen) return this.binary.channel();
|
|
1731
|
+
if (!this.opening) {
|
|
1732
|
+
const opening = this.connect().finally(() => {
|
|
1733
|
+
if (this.opening === opening) this.opening = void 0;
|
|
1734
|
+
});
|
|
1735
|
+
this.opening = opening;
|
|
1736
|
+
}
|
|
1737
|
+
const binary = await this.opening;
|
|
1738
|
+
if (binary.canOpen) return binary.channel();
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
async connect() {
|
|
1742
|
+
const generation = this.generation;
|
|
1743
|
+
const socket = await openProcessSocket(this.endpoint);
|
|
1744
|
+
if (generation !== this.generation) {
|
|
1745
|
+
socket.close();
|
|
1746
|
+
throw new Error("Process connection opening cancelled");
|
|
1747
|
+
}
|
|
1748
|
+
if (socket.protocol !== PROTOCOL) {
|
|
1749
|
+
socket.close();
|
|
1750
|
+
throw new Error(`Sandbox runtime does not support the ${PROTOCOL} process protocol`);
|
|
1751
|
+
}
|
|
1752
|
+
const binary = new BinaryConnection(socket, () => this.live.delete(binary));
|
|
1753
|
+
this.live.add(binary);
|
|
1754
|
+
this.binary = binary;
|
|
1755
|
+
return binary;
|
|
1756
|
+
}
|
|
1757
|
+
disconnect() {
|
|
1758
|
+
this.generation++;
|
|
1759
|
+
this.opening = void 0;
|
|
1760
|
+
for (const binary of [...this.live]) binary.close();
|
|
1761
|
+
this.binary = void 0;
|
|
1762
|
+
}
|
|
1763
|
+
};
|
|
1764
|
+
var BinaryConnection = class {
|
|
1765
|
+
socket;
|
|
1766
|
+
onClosed;
|
|
1767
|
+
channels = /* @__PURE__ */ new Map();
|
|
1768
|
+
next = 1;
|
|
1769
|
+
draining = false;
|
|
1770
|
+
idle;
|
|
1771
|
+
get canOpen() {
|
|
1772
|
+
return !this.draining && this.socket.readyState === WebSocket.OPEN && this.next < 4294967295 && this.channels.size < MAX_CHANNELS;
|
|
1773
|
+
}
|
|
1774
|
+
constructor(socket, onClosed) {
|
|
1775
|
+
this.socket = socket;
|
|
1776
|
+
this.onClosed = onClosed;
|
|
1777
|
+
socket.addEventListener("message", (message) => {
|
|
1778
|
+
try {
|
|
1779
|
+
const frame = (0, _bufbuild_protobuf.fromBinary)(_archildata_api_types_process.ServerFrameSchema, new Uint8Array(message.data));
|
|
1780
|
+
if (frame.channelId === 0) {
|
|
1781
|
+
if (frame.body.case !== "drain") return;
|
|
1782
|
+
this.draining = true;
|
|
1783
|
+
if (!this.channels.size) this.close();
|
|
1784
|
+
} else this.channels.get(frame.channelId)?.receive(frame);
|
|
1785
|
+
} catch (error) {
|
|
1786
|
+
this.close(error);
|
|
1787
|
+
}
|
|
1788
|
+
});
|
|
1789
|
+
socket.addEventListener("close", () => this.close(/* @__PURE__ */ new Error("Process connection closed before exit")), { once: true });
|
|
1790
|
+
socket.addEventListener("error", () => this.close(/* @__PURE__ */ new Error("Process connection failed")), { once: true });
|
|
1791
|
+
}
|
|
1792
|
+
channel() {
|
|
1793
|
+
if (!this.canOpen) throw new Error("Process connection is draining or full");
|
|
1794
|
+
clearTimeout(this.idle);
|
|
1795
|
+
const channel = new BinaryChannel(this, this.next++);
|
|
1796
|
+
this.channels.set(channel.id, channel);
|
|
1797
|
+
return channel;
|
|
1798
|
+
}
|
|
1799
|
+
send(id, body) {
|
|
1800
|
+
this.socket.send((0, _bufbuild_protobuf.toBinary)(_archildata_api_types_process.ClientFrameSchema, (0, _bufbuild_protobuf.create)(_archildata_api_types_process.ClientFrameSchema, {
|
|
1801
|
+
channelId: id,
|
|
1802
|
+
body
|
|
1803
|
+
})));
|
|
1804
|
+
}
|
|
1805
|
+
async writable() {
|
|
1806
|
+
await waitForProcessWrite(this.socket);
|
|
1807
|
+
}
|
|
1808
|
+
remove(id) {
|
|
1809
|
+
this.channels.delete(id);
|
|
1810
|
+
if (!this.channels.size) if (this.draining) this.close();
|
|
1811
|
+
else this.idle = setTimeout(() => this.close(), IDLE_MS);
|
|
1812
|
+
}
|
|
1813
|
+
close(reason) {
|
|
1814
|
+
this.draining = true;
|
|
1815
|
+
this.onClosed();
|
|
1816
|
+
clearTimeout(this.idle);
|
|
1817
|
+
for (const channel of [...this.channels.values()]) channel.finish(reason);
|
|
1818
|
+
if (this.socket.readyState < WebSocket.CLOSING) this.socket.close();
|
|
1819
|
+
}
|
|
1820
|
+
};
|
|
1821
|
+
/** @internal WebSocket-shaped channel; generated protobuf owns all wire encoding. */
|
|
1822
|
+
var BinaryChannel = class {
|
|
1823
|
+
connection;
|
|
1824
|
+
id;
|
|
1825
|
+
readyState = WebSocket.OPEN;
|
|
1826
|
+
binaryType = "arraybuffer";
|
|
1827
|
+
events = new EventTarget();
|
|
1828
|
+
addEventListener = this.events.addEventListener.bind(this.events);
|
|
1829
|
+
sending = Promise.resolve();
|
|
1830
|
+
/** Stdin the runtime will accept. */
|
|
1831
|
+
sendCredit = INITIAL_WINDOW;
|
|
1832
|
+
/** Output the runtime may still send. */
|
|
1833
|
+
receiveCredit = INITIAL_WINDOW;
|
|
1834
|
+
/** Output consumed since credit was last returned. */
|
|
1835
|
+
consumed = 0;
|
|
1836
|
+
creditChanged;
|
|
1837
|
+
constructor(connection, id) {
|
|
1838
|
+
this.connection = connection;
|
|
1839
|
+
this.id = id;
|
|
1840
|
+
}
|
|
1841
|
+
sendRequest(request) {
|
|
1842
|
+
switch (request.type) {
|
|
1843
|
+
case "start": {
|
|
1844
|
+
const terminal = request.terminal === true ? {
|
|
1845
|
+
rows: 24,
|
|
1846
|
+
cols: 80
|
|
1847
|
+
} : request.terminal || void 0;
|
|
1848
|
+
this.connection.send(this.id, (0, _bufbuild_protobuf.create)(_archildata_api_types_process.ClientFrameSchema, { body: {
|
|
1849
|
+
case: "start",
|
|
1850
|
+
value: {
|
|
1851
|
+
command: request.command,
|
|
1852
|
+
cwd: request.cwd,
|
|
1853
|
+
terminal,
|
|
1854
|
+
env: request.env,
|
|
1855
|
+
timeoutSeconds: request.timeout_seconds === void 0 ? void 0 : BigInt(request.timeout_seconds)
|
|
1856
|
+
}
|
|
1857
|
+
} }).body);
|
|
1858
|
+
break;
|
|
1859
|
+
}
|
|
1860
|
+
case "attach":
|
|
1861
|
+
this.connection.send(this.id, (0, _bufbuild_protobuf.create)(_archildata_api_types_process.ClientFrameSchema, { body: {
|
|
1862
|
+
case: "attach",
|
|
1863
|
+
value: {
|
|
1864
|
+
processId: request.process_id,
|
|
1865
|
+
offset: BigInt(request.offset),
|
|
1866
|
+
shared: request.shared ?? false
|
|
1867
|
+
}
|
|
1868
|
+
} }).body);
|
|
1869
|
+
break;
|
|
1870
|
+
case "kill":
|
|
1871
|
+
this.connection.send(this.id, (0, _bufbuild_protobuf.create)(_archildata_api_types_process.ClientFrameSchema, { body: {
|
|
1872
|
+
case: "kill",
|
|
1873
|
+
value: { processId: request.process_id }
|
|
1874
|
+
} }).body);
|
|
1875
|
+
break;
|
|
1876
|
+
case "resize":
|
|
1877
|
+
this.connection.send(this.id, (0, _bufbuild_protobuf.create)(_archildata_api_types_process.ClientFrameSchema, { body: {
|
|
1878
|
+
case: "resize",
|
|
1879
|
+
value: {
|
|
1880
|
+
processId: request.process_id,
|
|
1881
|
+
terminal: {
|
|
1882
|
+
rows: request.rows,
|
|
1883
|
+
cols: request.cols
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1886
|
+
} }).body);
|
|
1887
|
+
break;
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
send(bytes) {
|
|
1891
|
+
const sending = this.sending.then(async () => {
|
|
1892
|
+
for (let offset = 0; offset < bytes.length; offset += MAX_DATA) {
|
|
1893
|
+
const chunk = bytes.subarray(offset, offset + MAX_DATA);
|
|
1894
|
+
while (this.sendCredit < dataCost(chunk.length)) {
|
|
1895
|
+
if (this.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
|
|
1896
|
+
await new Promise((resolve) => {
|
|
1897
|
+
this.creditChanged = resolve;
|
|
1898
|
+
});
|
|
1899
|
+
}
|
|
1900
|
+
if (this.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
|
|
1901
|
+
this.sendCredit -= dataCost(chunk.length);
|
|
1902
|
+
this.connection.send(this.id, {
|
|
1903
|
+
case: "stdin",
|
|
1904
|
+
value: chunk
|
|
1905
|
+
});
|
|
1906
|
+
await this.connection.writable();
|
|
1907
|
+
}
|
|
1908
|
+
});
|
|
1909
|
+
this.sending = sending.catch(() => {});
|
|
1910
|
+
return sending;
|
|
1911
|
+
}
|
|
1912
|
+
/** Returns credit for output the application has taken. */
|
|
1913
|
+
release(cost) {
|
|
1914
|
+
if (this.readyState === WebSocket.CLOSED) return;
|
|
1915
|
+
this.consumed += cost;
|
|
1916
|
+
if (this.consumed < INITIAL_WINDOW / 2) return;
|
|
1917
|
+
this.receiveCredit += this.consumed;
|
|
1918
|
+
this.connection.send(this.id, {
|
|
1919
|
+
case: "windowUpdate",
|
|
1920
|
+
value: (0, _bufbuild_protobuf.create)(_archildata_api_types_process.WindowUpdateSchema, { bytes: this.consumed })
|
|
1921
|
+
});
|
|
1922
|
+
this.consumed = 0;
|
|
1923
|
+
}
|
|
1924
|
+
async closeStdin() {
|
|
1925
|
+
await this.sending;
|
|
1926
|
+
if (this.readyState !== WebSocket.OPEN) throw new Error("Process is disconnected");
|
|
1927
|
+
this.connection.send(this.id, (0, _bufbuild_protobuf.create)(_archildata_api_types_process.ClientFrameSchema, { body: {
|
|
1928
|
+
case: "closeStdin",
|
|
1929
|
+
value: {}
|
|
1930
|
+
} }).body);
|
|
1931
|
+
}
|
|
1932
|
+
close() {
|
|
1933
|
+
if (this.readyState !== WebSocket.OPEN) return;
|
|
1934
|
+
this.readyState = WebSocket.CLOSING;
|
|
1935
|
+
this.connection.send(this.id, (0, _bufbuild_protobuf.create)(_archildata_api_types_process.ClientFrameSchema, { body: {
|
|
1936
|
+
case: "detach",
|
|
1937
|
+
value: {}
|
|
1938
|
+
} }).body);
|
|
1939
|
+
}
|
|
1940
|
+
receive(frame) {
|
|
1941
|
+
const body = frame.body;
|
|
1942
|
+
let event;
|
|
1943
|
+
switch (body.case) {
|
|
1944
|
+
case "started":
|
|
1945
|
+
case "attached":
|
|
1946
|
+
event = {
|
|
1947
|
+
type: body.case,
|
|
1948
|
+
process_id: body.value.processId
|
|
1949
|
+
};
|
|
1950
|
+
break;
|
|
1951
|
+
case "windowUpdate":
|
|
1952
|
+
this.sendCredit += body.value.bytes;
|
|
1953
|
+
this.creditChanged?.();
|
|
1954
|
+
return;
|
|
1955
|
+
case "stdout":
|
|
1956
|
+
case "stderr": {
|
|
1957
|
+
if (body.value.data.length > MAX_DATA) throw new Error("Process output exceeds chunk size");
|
|
1958
|
+
const cost = dataCost(body.value.data.length);
|
|
1959
|
+
if (cost > this.receiveCredit) throw new Error("Process output exceeded its flow-control window");
|
|
1960
|
+
this.receiveCredit -= cost;
|
|
1961
|
+
const offset = Number(body.value.offset);
|
|
1962
|
+
if (!Number.isSafeInteger(offset)) {
|
|
1963
|
+
this.fail("output_offset_overflow", "Process offset exceeds JavaScript integer precision");
|
|
1964
|
+
return;
|
|
1965
|
+
}
|
|
1966
|
+
this.events.dispatchEvent(new MessageEvent("message", { data: {
|
|
1967
|
+
stream: body.case,
|
|
1968
|
+
offset,
|
|
1969
|
+
data: body.value.data,
|
|
1970
|
+
cost
|
|
1971
|
+
} }));
|
|
1972
|
+
return;
|
|
1973
|
+
}
|
|
1974
|
+
case "exit": {
|
|
1975
|
+
const status = {
|
|
1976
|
+
[_archildata_api_types_process.Exit_Status.COMPLETED]: "completed",
|
|
1977
|
+
[_archildata_api_types_process.Exit_Status.FAILED]: "failed",
|
|
1978
|
+
[_archildata_api_types_process.Exit_Status.CANCELLED]: "cancelled",
|
|
1979
|
+
[_archildata_api_types_process.Exit_Status.TIMED_OUT]: "timed_out"
|
|
1980
|
+
}[body.value.status];
|
|
1981
|
+
if (!status) {
|
|
1982
|
+
this.fail("unsupported_exit_status", `Unknown process exit status ${body.value.status}`);
|
|
1983
|
+
return;
|
|
1984
|
+
}
|
|
1985
|
+
event = {
|
|
1986
|
+
type: "exit",
|
|
1987
|
+
status,
|
|
1988
|
+
exit_code: body.value.exitCode,
|
|
1989
|
+
exit_reason: body.value.exitReason,
|
|
1990
|
+
cursor: Number(body.value.cursor)
|
|
1991
|
+
};
|
|
1992
|
+
break;
|
|
1993
|
+
}
|
|
1994
|
+
case "error":
|
|
1995
|
+
event = {
|
|
1996
|
+
type: "error",
|
|
1997
|
+
error: body.value.code,
|
|
1998
|
+
message: body.value.message
|
|
1999
|
+
};
|
|
2000
|
+
break;
|
|
2001
|
+
case "killed":
|
|
2002
|
+
case "resized":
|
|
2003
|
+
event = { type: body.case };
|
|
2004
|
+
break;
|
|
2005
|
+
case "detached":
|
|
2006
|
+
this.finish();
|
|
2007
|
+
return;
|
|
2008
|
+
case void 0: return;
|
|
2009
|
+
default: throw new Error("Unexpected process channel message");
|
|
2010
|
+
}
|
|
2011
|
+
this.events.dispatchEvent(new MessageEvent("message", { data: event }));
|
|
2012
|
+
if ([
|
|
2013
|
+
"exit",
|
|
2014
|
+
"error",
|
|
2015
|
+
"killed",
|
|
2016
|
+
"resized"
|
|
2017
|
+
].includes(body.case)) this.finish();
|
|
2018
|
+
}
|
|
2019
|
+
/** Fails only this channel, for a message whose value it cannot represent. */
|
|
2020
|
+
fail(error, message) {
|
|
2021
|
+
if (this.readyState === WebSocket.OPEN) this.connection.send(this.id, (0, _bufbuild_protobuf.create)(_archildata_api_types_process.ClientFrameSchema, { body: {
|
|
2022
|
+
case: "detach",
|
|
2023
|
+
value: {}
|
|
2024
|
+
} }).body);
|
|
2025
|
+
this.events.dispatchEvent(new MessageEvent("message", { data: {
|
|
2026
|
+
type: "error",
|
|
2027
|
+
error,
|
|
2028
|
+
message
|
|
2029
|
+
} }));
|
|
2030
|
+
this.finish();
|
|
2031
|
+
}
|
|
2032
|
+
finish(reason) {
|
|
2033
|
+
if (this.readyState === WebSocket.CLOSED) return;
|
|
2034
|
+
if (reason) this.events.dispatchEvent(new MessageEvent("message", { data: {
|
|
2035
|
+
type: "error",
|
|
2036
|
+
error: "connection_closed",
|
|
2037
|
+
message: String(reason)
|
|
2038
|
+
} }));
|
|
2039
|
+
this.readyState = WebSocket.CLOSED;
|
|
2040
|
+
this.creditChanged?.();
|
|
2041
|
+
this.connection.remove(this.id);
|
|
2042
|
+
this.events.dispatchEvent(new Event("close"));
|
|
2043
|
+
}
|
|
2044
|
+
};
|
|
2045
|
+
//#endregion
|
|
2046
|
+
//#region src/sandbox-process.ts
|
|
2047
|
+
/** @deprecated Use Sandbox.run() and Sandbox.attach(). Removed in the next version. */
|
|
2048
|
+
var SandboxProcesses = class {
|
|
2049
|
+
_sandbox;
|
|
2050
|
+
_disconnect;
|
|
2051
|
+
/** @internal */
|
|
2052
|
+
constructor(_sandbox, _disconnect) {
|
|
2053
|
+
this._sandbox = _sandbox;
|
|
2054
|
+
this._disconnect = _disconnect;
|
|
2055
|
+
}
|
|
2056
|
+
/** @deprecated Use sandbox.run(). Removed in the next version. */
|
|
2057
|
+
start(command, options = {}) {
|
|
2058
|
+
return this._sandbox.run(command, options);
|
|
2059
|
+
}
|
|
2060
|
+
/** @deprecated Use sandbox.attach(). Removed in the next version. */
|
|
2061
|
+
connect(processId, options = {}) {
|
|
2062
|
+
return this._sandbox.attach(processId, options);
|
|
2063
|
+
}
|
|
2064
|
+
/** Disconnect process transport without terminating guest processes. */
|
|
2065
|
+
async disconnect() {
|
|
2066
|
+
this._disconnect();
|
|
2067
|
+
}
|
|
2068
|
+
};
|
|
2069
|
+
var SandboxProcess = class {
|
|
2070
|
+
_collectOutput;
|
|
2071
|
+
_buffer;
|
|
2072
|
+
_openConnection;
|
|
2073
|
+
_controlProcess;
|
|
2074
|
+
status = "running";
|
|
2075
|
+
stdout = "";
|
|
2076
|
+
stderr = "";
|
|
2077
|
+
_id;
|
|
2078
|
+
_cursor;
|
|
2079
|
+
_deliveredCursor;
|
|
2080
|
+
_stdoutDecoder = new TextDecoder();
|
|
2081
|
+
_stderrDecoder = new TextDecoder();
|
|
2082
|
+
_socket;
|
|
2083
|
+
_closed;
|
|
2084
|
+
_manual = false;
|
|
2085
|
+
_stdinClosed = false;
|
|
2086
|
+
_iteratorTaken = false;
|
|
2087
|
+
/** Settles once onOutput has handled the last chunk. */
|
|
2088
|
+
_delivered;
|
|
2089
|
+
_wake;
|
|
2090
|
+
_error;
|
|
2091
|
+
_exit;
|
|
2092
|
+
_result;
|
|
2093
|
+
/** Returns each buffered binary output's credit once the iterator takes it. */
|
|
2094
|
+
_releases = /* @__PURE__ */ new WeakMap();
|
|
2095
|
+
_resolveDone;
|
|
2096
|
+
_done = new Promise((resolve) => {
|
|
2097
|
+
this._resolveDone = resolve;
|
|
2098
|
+
});
|
|
2099
|
+
/** Pull output from the shared buffer. One iterator may consume each handle. */
|
|
2100
|
+
output = { [Symbol.asyncIterator]: () => {
|
|
2101
|
+
if (this._iteratorTaken) throw new Error("Process output already has a consumer: an output iterator or onOutput");
|
|
2102
|
+
this._iteratorTaken = true;
|
|
2103
|
+
return this._iterateOutput();
|
|
2104
|
+
} };
|
|
2105
|
+
/** @internal */
|
|
2106
|
+
constructor(processId, cursor, _collectOutput, _buffer, _openConnection, _controlProcess) {
|
|
2107
|
+
this._collectOutput = _collectOutput;
|
|
2108
|
+
this._buffer = _buffer;
|
|
2109
|
+
this._openConnection = _openConnection;
|
|
2110
|
+
this._controlProcess = _controlProcess;
|
|
2111
|
+
this._id = processId;
|
|
2112
|
+
this._cursor = cursor;
|
|
2113
|
+
this._deliveredCursor = cursor;
|
|
2114
|
+
}
|
|
2115
|
+
get id() {
|
|
2116
|
+
return this._id;
|
|
2117
|
+
}
|
|
2118
|
+
/** Next byte after output accepted into the SDK buffer. */
|
|
2119
|
+
get cursor() {
|
|
2120
|
+
return this._cursor;
|
|
2121
|
+
}
|
|
2122
|
+
get connected() {
|
|
2123
|
+
return this._socket?.readyState === WebSocket.OPEN;
|
|
2124
|
+
}
|
|
2125
|
+
/** Resolves once the runtime has accepted the input; waits while the process is not reading. */
|
|
2126
|
+
async sendInput(data) {
|
|
2127
|
+
if (this._stdinClosed) throw new Error("Process stdin is closed");
|
|
2128
|
+
const bytes = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
|
|
2129
|
+
await this._openSocket().send(bytes);
|
|
2130
|
+
}
|
|
2131
|
+
async closeStdin() {
|
|
2132
|
+
if (this._stdinClosed) return;
|
|
2133
|
+
this._stdinClosed = true;
|
|
2134
|
+
try {
|
|
2135
|
+
await this._openSocket().closeStdin();
|
|
2136
|
+
} catch (error) {
|
|
2137
|
+
this._stdinClosed = false;
|
|
2138
|
+
throw error;
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
async resize(size) {
|
|
2142
|
+
if (this.status !== "running") throw new Error("Process has exited");
|
|
2143
|
+
await this._controlProcess({
|
|
2144
|
+
type: "resize",
|
|
2145
|
+
process_id: this._id,
|
|
2146
|
+
...size
|
|
2147
|
+
});
|
|
2148
|
+
}
|
|
2149
|
+
async kill() {
|
|
2150
|
+
if (!this._exit) await this._controlProcess({
|
|
2151
|
+
type: "kill",
|
|
2152
|
+
process_id: this._id
|
|
2153
|
+
});
|
|
2154
|
+
}
|
|
2155
|
+
async disconnect() {
|
|
2156
|
+
this._manual = true;
|
|
2157
|
+
this._socket?.close();
|
|
2158
|
+
await this._closed;
|
|
2159
|
+
if (!this._exit) this._fail(/* @__PURE__ */ new Error("Process is disconnected"));
|
|
2160
|
+
}
|
|
2161
|
+
async wait() {
|
|
2162
|
+
if (!this._iteratorTaken) for await (const _output of this.output);
|
|
2163
|
+
await this._delivered;
|
|
2164
|
+
await this._done;
|
|
2165
|
+
if (this._error) throw this._error;
|
|
2166
|
+
return this._result;
|
|
2167
|
+
}
|
|
2168
|
+
/** @internal Feeds `output` to `handler`, waiting for each call to settle. */
|
|
2169
|
+
_deliverTo(handler) {
|
|
2170
|
+
const iterator = this.output[Symbol.asyncIterator]();
|
|
2171
|
+
this._delivered = (async () => {
|
|
2172
|
+
try {
|
|
2173
|
+
for (let next = await iterator.next(); !next.done; next = await iterator.next()) await handler(next.value);
|
|
2174
|
+
} catch (error) {
|
|
2175
|
+
this._fail(error);
|
|
2176
|
+
await iterator.return?.(void 0);
|
|
2177
|
+
if (!this._exit) await this.disconnect();
|
|
2178
|
+
}
|
|
2179
|
+
})();
|
|
2180
|
+
}
|
|
2181
|
+
async *_iterateOutput() {
|
|
2182
|
+
try {
|
|
2183
|
+
while (true) {
|
|
2184
|
+
const output = this._buffer.take(this);
|
|
2185
|
+
if (output) {
|
|
2186
|
+
this._releases.get(output)?.();
|
|
2187
|
+
this._deliveredCursor = output.offset + output.data.length;
|
|
2188
|
+
if (this._collectOutput) this._appendText(output.stream, (output.stream === "stdout" ? this._stdoutDecoder : this._stderrDecoder).decode(output.data, { stream: true }));
|
|
2189
|
+
this._complete();
|
|
2190
|
+
yield output;
|
|
2191
|
+
} else {
|
|
2192
|
+
this._complete();
|
|
2193
|
+
if (this._error) throw this._error;
|
|
2194
|
+
if (this._exit) return;
|
|
2195
|
+
await new Promise((resolve) => {
|
|
2196
|
+
this._wake = resolve;
|
|
2197
|
+
});
|
|
2198
|
+
this._wake = void 0;
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
} finally {
|
|
2202
|
+
if (!this._exit && !this._error) await this.disconnect();
|
|
2203
|
+
this._buffer.discard(this);
|
|
2204
|
+
this._cursor = this._deliveredCursor;
|
|
2205
|
+
this._complete();
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
/** @internal */
|
|
2209
|
+
async _connect(request) {
|
|
2210
|
+
const socket = await this._openConnection();
|
|
2211
|
+
if (this._manual) {
|
|
2212
|
+
socket.close();
|
|
2213
|
+
throw new Error("Process is disconnected");
|
|
2214
|
+
}
|
|
2215
|
+
this._socket = socket;
|
|
2216
|
+
let closed;
|
|
2217
|
+
this._closed = new Promise((resolve) => {
|
|
2218
|
+
closed = resolve;
|
|
2219
|
+
});
|
|
2220
|
+
const expected = request.type === "start" ? "started" : "attached";
|
|
2221
|
+
let settled = false;
|
|
2222
|
+
let resolveReady;
|
|
2223
|
+
let rejectReady;
|
|
2224
|
+
const ready = new Promise((resolve, reject) => {
|
|
2225
|
+
resolveReady = resolve;
|
|
2226
|
+
rejectReady = reject;
|
|
2227
|
+
});
|
|
2228
|
+
socket.addEventListener("message", (message) => {
|
|
2229
|
+
if (this._socket !== socket) return;
|
|
2230
|
+
try {
|
|
2231
|
+
const data = message.data;
|
|
2232
|
+
if ("stream" in data) {
|
|
2233
|
+
this._enqueueOutput(data.data, data.offset, data.stream, () => socket.release(data.cost));
|
|
2234
|
+
return;
|
|
2235
|
+
}
|
|
2236
|
+
const event = data;
|
|
2237
|
+
switch (event.type) {
|
|
2238
|
+
case "started":
|
|
2239
|
+
case "attached":
|
|
2240
|
+
if (event.type !== expected || this._id && this._id !== event.process_id) throw new Error("Unexpected process identity");
|
|
2241
|
+
this._id = event.process_id;
|
|
2242
|
+
settled = true;
|
|
2243
|
+
resolveReady();
|
|
2244
|
+
break;
|
|
2245
|
+
case "exit":
|
|
2246
|
+
this._exit = event;
|
|
2247
|
+
this.status = event.status;
|
|
2248
|
+
this._stdinClosed = true;
|
|
2249
|
+
this._complete();
|
|
2250
|
+
this._wake?.();
|
|
2251
|
+
break;
|
|
2252
|
+
case "error": throw new Error(`${event.error}: ${event.message}`);
|
|
2253
|
+
}
|
|
2254
|
+
} catch (error) {
|
|
2255
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
2256
|
+
if (!settled) rejectReady(failure);
|
|
2257
|
+
this._fail(failure);
|
|
2258
|
+
socket.close();
|
|
2259
|
+
}
|
|
2260
|
+
});
|
|
2261
|
+
socket.addEventListener("error", () => {
|
|
2262
|
+
const error = /* @__PURE__ */ new Error("Process connection failed");
|
|
2263
|
+
if (!settled) rejectReady(error);
|
|
2264
|
+
this._fail(error);
|
|
2265
|
+
});
|
|
2266
|
+
socket.addEventListener("close", () => {
|
|
2267
|
+
if (this._socket === socket) this._socket = void 0;
|
|
2268
|
+
closed();
|
|
2269
|
+
if (!settled) rejectReady(/* @__PURE__ */ new Error("Process connection closed before ready"));
|
|
2270
|
+
if (!this._exit && !this._manual) this._fail(/* @__PURE__ */ new Error("Process connection closed before exit"));
|
|
2271
|
+
}, { once: true });
|
|
2272
|
+
try {
|
|
2273
|
+
socket.sendRequest(request);
|
|
2274
|
+
} catch (error) {
|
|
2275
|
+
rejectReady(error instanceof Error ? error : new Error(String(error)));
|
|
2276
|
+
this._fail(error);
|
|
2277
|
+
socket.close();
|
|
2278
|
+
}
|
|
2279
|
+
await ready;
|
|
2280
|
+
}
|
|
2281
|
+
_openSocket() {
|
|
2282
|
+
if (this.status !== "running") throw new Error("Process has exited");
|
|
2283
|
+
if (!this.connected) throw new Error("Process is disconnected");
|
|
2284
|
+
return this._socket;
|
|
2285
|
+
}
|
|
2286
|
+
_fail(error) {
|
|
2287
|
+
this._error ??= error instanceof Error ? error : new Error(String(error));
|
|
2288
|
+
this._resolveDone();
|
|
2289
|
+
this._wake?.();
|
|
2290
|
+
}
|
|
2291
|
+
_complete() {
|
|
2292
|
+
if (!this._exit || this._buffer.has(this) || this._result) return;
|
|
2293
|
+
this._flushDecoders();
|
|
2294
|
+
this._result = {
|
|
2295
|
+
status: this._exit.status,
|
|
2296
|
+
exitCode: this._exit.exit_code ?? void 0,
|
|
2297
|
+
exitReason: this._exit.exit_reason ?? void 0,
|
|
2298
|
+
stdout: this.stdout,
|
|
2299
|
+
stderr: this.stderr
|
|
2300
|
+
};
|
|
2301
|
+
this._resolveDone();
|
|
2302
|
+
}
|
|
2303
|
+
/** `release` returns the output's flow-control credit once it is consumed. */
|
|
2304
|
+
_enqueueOutput(payload, offset, stream, release) {
|
|
2305
|
+
const end = offset + payload.byteLength;
|
|
2306
|
+
if (end <= this._cursor) {
|
|
2307
|
+
release();
|
|
2308
|
+
return;
|
|
2309
|
+
}
|
|
2310
|
+
if (offset > this._cursor) throw new Error(`Process output gap: expected offset ${this._cursor}, received ${offset}`);
|
|
2311
|
+
const skip = this._cursor - offset;
|
|
2312
|
+
const output = {
|
|
2313
|
+
stream,
|
|
2314
|
+
offset: this._cursor,
|
|
2315
|
+
data: payload.slice(skip)
|
|
2316
|
+
};
|
|
2317
|
+
this._buffer.push(this, output);
|
|
2318
|
+
this._releases.set(output, release);
|
|
2319
|
+
this._cursor = end;
|
|
2320
|
+
this._wake?.();
|
|
2321
|
+
}
|
|
2322
|
+
_appendText(stream, data) {
|
|
2323
|
+
if (stream === "stdout") this.stdout += data;
|
|
2324
|
+
else this.stderr += data;
|
|
2325
|
+
}
|
|
2326
|
+
_flushDecoders() {
|
|
2327
|
+
if (!this._collectOutput) return;
|
|
2328
|
+
this._appendText("stdout", this._stdoutDecoder.decode());
|
|
2329
|
+
this._appendText("stderr", this._stderrDecoder.decode());
|
|
2330
|
+
}
|
|
2331
|
+
};
|
|
2332
|
+
//#endregion
|
|
2333
|
+
//#region src/sandbox-files.ts
|
|
2334
|
+
const DOWNLOAD_CHUNK_BYTES = 512 * 1024;
|
|
2335
|
+
const UPLOAD_COMMAND = `set -eu
|
|
2336
|
+
mkdir -p "$ARCHIL_FILE_PARENT"
|
|
2337
|
+
trap 'rm -f "$ARCHIL_FILE_TEMP"' EXIT HUP INT TERM
|
|
2338
|
+
: > "$ARCHIL_FILE_TEMP"
|
|
2339
|
+
cat > "$ARCHIL_FILE_TEMP"
|
|
2340
|
+
chmod "$ARCHIL_FILE_MODE" "$ARCHIL_FILE_TEMP"
|
|
2341
|
+
mv -f "$ARCHIL_FILE_TEMP" "$ARCHIL_FILE_TARGET"
|
|
2342
|
+
trap - EXIT HUP INT TERM`;
|
|
2343
|
+
const DOWNLOAD_COMMAND = `set -eu
|
|
2344
|
+
trap 'rm -f "$ARCHIL_FILE_TEMP"' EXIT HUP INT TERM
|
|
2345
|
+
exec 3< "$ARCHIL_FILE_PATH"
|
|
2346
|
+
while IFS= read -r count; do
|
|
2347
|
+
dd bs="$count" count=1 <&3 > "$ARCHIL_FILE_TEMP" 2>/dev/null
|
|
2348
|
+
size=$(wc -c < "$ARCHIL_FILE_TEMP")
|
|
2349
|
+
printf '%s\n' "$size"
|
|
2350
|
+
cat "$ARCHIL_FILE_TEMP"
|
|
2351
|
+
[ "$size" -eq "$count" ] || break
|
|
2352
|
+
done`;
|
|
2353
|
+
var ProcessOutputReader = class {
|
|
2354
|
+
_buffer = /* @__PURE__ */ new Uint8Array();
|
|
2355
|
+
_cursor = 0;
|
|
2356
|
+
_stderrDecoder = new TextDecoder();
|
|
2357
|
+
_stderr = "";
|
|
2358
|
+
_process;
|
|
2359
|
+
_output;
|
|
2360
|
+
attach(process) {
|
|
2361
|
+
this._process = process;
|
|
2362
|
+
this._output = process.output[Symbol.asyncIterator]();
|
|
2363
|
+
}
|
|
2364
|
+
async readLine() {
|
|
2365
|
+
while (true) {
|
|
2366
|
+
const newline = this._buffer.indexOf(10);
|
|
2367
|
+
if (newline >= 0) {
|
|
2368
|
+
const line = this._buffer.slice(0, newline);
|
|
2369
|
+
this._buffer = this._buffer.slice(newline + 1);
|
|
2370
|
+
return line;
|
|
2371
|
+
}
|
|
2372
|
+
this._buffer = concat(this._buffer, await this._nextChunk());
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
async read(size) {
|
|
2376
|
+
while (this._buffer.length < size) this._buffer = concat(this._buffer, await this._nextChunk());
|
|
2377
|
+
const data = this._buffer.slice(0, size);
|
|
2378
|
+
this._buffer = this._buffer.slice(size);
|
|
2379
|
+
return data;
|
|
2380
|
+
}
|
|
2381
|
+
async wait() {
|
|
2382
|
+
while (!(await this._output.next()).done);
|
|
2383
|
+
assertSuccessful(await this._process.wait(), this._stderr + this._stderrDecoder.decode());
|
|
2384
|
+
}
|
|
2385
|
+
async _nextChunk() {
|
|
2386
|
+
while (true) {
|
|
2387
|
+
const next = await this._output.next();
|
|
2388
|
+
if (next.done) {
|
|
2389
|
+
assertSuccessful(await this._process.wait(), this._stderr + this._stderrDecoder.decode());
|
|
2390
|
+
throw new Error("Sandbox process exited before file transfer completed");
|
|
2391
|
+
}
|
|
2392
|
+
const output = next.value;
|
|
2393
|
+
if (output.offset !== this._cursor) throw new Error(`Sandbox process output gap: expected offset ${this._cursor}, received ${output.offset}`);
|
|
2394
|
+
this._cursor += output.data.length;
|
|
2395
|
+
if (output.stream === "stdout") return output.data;
|
|
2396
|
+
this._stderr += this._stderrDecoder.decode(output.data, { stream: true });
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
};
|
|
2400
|
+
var SandboxFiles = class {
|
|
2401
|
+
_sandbox;
|
|
2402
|
+
/** @internal */
|
|
2403
|
+
constructor(sandbox) {
|
|
2404
|
+
this._sandbox = sandbox;
|
|
2405
|
+
}
|
|
2406
|
+
async uploadFile(source, remotePath, options = {}) {
|
|
2407
|
+
const { path, parent } = remoteFilePath(remotePath);
|
|
2408
|
+
const mode = options.mode ?? 420;
|
|
2409
|
+
if (!Number.isInteger(mode) || mode < 0 || mode > 4095) throw new RangeError("mode must be between 0 and 0o7777");
|
|
2410
|
+
let process;
|
|
2411
|
+
try {
|
|
2412
|
+
process = await this._sandbox.run(UPLOAD_COMMAND, { env: {
|
|
2413
|
+
ARCHIL_FILE_PARENT: parent,
|
|
2414
|
+
ARCHIL_FILE_TARGET: path,
|
|
2415
|
+
ARCHIL_FILE_TEMP: `${parent}/.archil-upload-${transferId()}`,
|
|
2416
|
+
ARCHIL_FILE_MODE: mode.toString(8)
|
|
2417
|
+
} });
|
|
2418
|
+
for await (const chunk of fileChunks(source)) await process.sendInput(chunk);
|
|
2419
|
+
await process.closeStdin();
|
|
2420
|
+
assertSuccessful(await process.wait());
|
|
2421
|
+
} catch (error) {
|
|
2422
|
+
if (process) await abort(process);
|
|
2423
|
+
if (error instanceof RangeError || error instanceof TypeError) throw error;
|
|
2424
|
+
throw new SandboxFileTransferError("upload", path, toError(error));
|
|
2425
|
+
} finally {
|
|
2426
|
+
await process?.disconnect();
|
|
2427
|
+
}
|
|
2428
|
+
}
|
|
2429
|
+
async downloadFile(remotePath, write) {
|
|
2430
|
+
const { path } = remoteFilePath(remotePath);
|
|
2431
|
+
const reader = new ProcessOutputReader();
|
|
2432
|
+
let process;
|
|
2433
|
+
try {
|
|
2434
|
+
process = await this._sandbox.run(DOWNLOAD_COMMAND, {
|
|
2435
|
+
env: {
|
|
2436
|
+
ARCHIL_FILE_PATH: path,
|
|
2437
|
+
ARCHIL_FILE_TEMP: `/tmp/.archil-download-${transferId()}`
|
|
2438
|
+
},
|
|
2439
|
+
collectOutput: false
|
|
2440
|
+
});
|
|
2441
|
+
reader.attach(process);
|
|
2442
|
+
while (true) {
|
|
2443
|
+
await process.sendInput(`${DOWNLOAD_CHUNK_BYTES}\n`);
|
|
2444
|
+
const sizeText = new TextDecoder().decode(await reader.readLine()).trim();
|
|
2445
|
+
const size = Number(sizeText);
|
|
2446
|
+
if (!Number.isSafeInteger(size) || size < 0 || size > DOWNLOAD_CHUNK_BYTES) throw new Error(`Sandbox returned an invalid chunk size: ${JSON.stringify(sizeText)}`);
|
|
2447
|
+
if (size === 0) break;
|
|
2448
|
+
await write(await reader.read(size));
|
|
2449
|
+
if (size < DOWNLOAD_CHUNK_BYTES) break;
|
|
2450
|
+
}
|
|
2451
|
+
await reader.wait();
|
|
2452
|
+
} catch (error) {
|
|
2453
|
+
if (process) await abort(process);
|
|
2454
|
+
if (error instanceof RangeError || error instanceof TypeError) throw error;
|
|
2455
|
+
throw new SandboxFileTransferError("download", path, toError(error));
|
|
2456
|
+
} finally {
|
|
2457
|
+
await process?.disconnect();
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
};
|
|
2461
|
+
async function* fileChunks(source) {
|
|
2462
|
+
if (source instanceof Uint8Array) {
|
|
2463
|
+
yield source;
|
|
2464
|
+
return;
|
|
2465
|
+
}
|
|
2466
|
+
if (source instanceof ArrayBuffer) {
|
|
2467
|
+
yield new Uint8Array(source);
|
|
2468
|
+
return;
|
|
2469
|
+
}
|
|
2470
|
+
if (source instanceof Blob) {
|
|
2471
|
+
yield* readableChunks(source.stream());
|
|
2472
|
+
return;
|
|
2473
|
+
}
|
|
2474
|
+
if (Symbol.asyncIterator in source) {
|
|
2475
|
+
for await (const chunk of source) yield new Uint8Array(chunk);
|
|
2476
|
+
return;
|
|
2477
|
+
}
|
|
2478
|
+
yield* readableChunks(source);
|
|
2479
|
+
}
|
|
2480
|
+
async function* readableChunks(source) {
|
|
2481
|
+
const reader = source.getReader();
|
|
2482
|
+
try {
|
|
2483
|
+
while (true) {
|
|
2484
|
+
const { done, value } = await reader.read();
|
|
2485
|
+
if (done) return;
|
|
2486
|
+
yield value;
|
|
2487
|
+
}
|
|
2488
|
+
} finally {
|
|
2489
|
+
reader.releaseLock();
|
|
2490
|
+
}
|
|
2491
|
+
}
|
|
2492
|
+
function remoteFilePath(path) {
|
|
2493
|
+
if (path.includes("\0")) throw new TypeError("remote path cannot contain NUL");
|
|
2494
|
+
if (!path.startsWith("/") || path.endsWith("/")) throw new TypeError("remote path must be an absolute file path");
|
|
2495
|
+
return {
|
|
2496
|
+
path,
|
|
2497
|
+
parent: path.slice(0, path.lastIndexOf("/")) || "/"
|
|
2498
|
+
};
|
|
2499
|
+
}
|
|
2500
|
+
function assertSuccessful(result, stderr = result.stderr) {
|
|
2501
|
+
if (result.status === "completed" && result.exitCode === 0) return;
|
|
2502
|
+
throw new Error(stderr.trim() || result.exitReason || `exit code ${String(result.exitCode)}`);
|
|
2503
|
+
}
|
|
2504
|
+
async function abort(process) {
|
|
2505
|
+
try {
|
|
2506
|
+
await process.kill();
|
|
2507
|
+
} catch {}
|
|
2508
|
+
}
|
|
2509
|
+
function transferId() {
|
|
2510
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
2511
|
+
}
|
|
2512
|
+
function concat(left, right) {
|
|
2513
|
+
const result = new Uint8Array(left.byteLength + right.byteLength);
|
|
2514
|
+
result.set(left);
|
|
2515
|
+
result.set(right, left.byteLength);
|
|
2516
|
+
return result;
|
|
2517
|
+
}
|
|
2518
|
+
function toError(error) {
|
|
2519
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
2520
|
+
}
|
|
2521
|
+
//#endregion
|
|
2522
|
+
//#region src/sandbox.ts
|
|
2523
|
+
/** @internal */
|
|
2524
|
+
function sandboxMountWire(mount) {
|
|
2525
|
+
const entry = {
|
|
2526
|
+
disk_id: typeof mount.disk === "string" ? mount.disk : mount.disk.id,
|
|
2527
|
+
read_only: mount.readOnly ?? false,
|
|
2528
|
+
conditional: mount.conditional ?? false
|
|
2529
|
+
};
|
|
2530
|
+
if (mount.path !== void 0) entry.path = mount.path;
|
|
2531
|
+
if (mount.subdirectory !== void 0) entry.subdirectory = mount.subdirectory;
|
|
2532
|
+
if (mount.queueMs !== void 0) entry.queue_ms = mount.queueMs;
|
|
2533
|
+
return entry;
|
|
2534
|
+
}
|
|
2535
|
+
function sandboxMountFromWire(mount) {
|
|
2536
|
+
const out = {
|
|
2537
|
+
diskId: mount.disk_id,
|
|
2538
|
+
path: mount.path,
|
|
2539
|
+
readOnly: mount.read_only ?? false,
|
|
2540
|
+
conditional: mount.conditional ?? false
|
|
2541
|
+
};
|
|
2542
|
+
if (mount.subdirectory !== void 0) out.subdirectory = mount.subdirectory;
|
|
2543
|
+
if (mount.queue_ms !== void 0) out.queueMs = mount.queue_ms;
|
|
2544
|
+
return out;
|
|
2545
|
+
}
|
|
2546
|
+
function portTokenFromWire(data) {
|
|
2547
|
+
return {
|
|
2548
|
+
id: data.id,
|
|
2549
|
+
port: data.port,
|
|
2550
|
+
createdAt: new Date(data.created_at),
|
|
2551
|
+
expiresAt: data.expires_at ? new Date(data.expires_at) : void 0
|
|
2552
|
+
};
|
|
2553
|
+
}
|
|
2554
|
+
const POLL_INTERVAL_MS = 500;
|
|
2555
|
+
function sleep() {
|
|
2556
|
+
return new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
|
|
2557
|
+
}
|
|
2558
|
+
var Sandbox = class Sandbox {
|
|
2559
|
+
id;
|
|
2560
|
+
name;
|
|
2561
|
+
labels;
|
|
2562
|
+
status;
|
|
2563
|
+
vcpuCount;
|
|
2564
|
+
memSizeMiB;
|
|
2565
|
+
baseImage;
|
|
2566
|
+
imageDigest;
|
|
2567
|
+
platform;
|
|
2568
|
+
maxTtlSeconds;
|
|
2569
|
+
idleTtlSeconds;
|
|
2570
|
+
onTimeout;
|
|
2571
|
+
maxConcurrentExecs;
|
|
2572
|
+
endpoints;
|
|
2573
|
+
mounts;
|
|
2574
|
+
createdAt;
|
|
2575
|
+
runningAt;
|
|
2576
|
+
finishedAt;
|
|
2577
|
+
lastActiveAt;
|
|
2578
|
+
exitReason;
|
|
2579
|
+
checkpoint;
|
|
2580
|
+
/** @deprecated Use run() and attach(). Removed in the next version. */
|
|
2581
|
+
processes;
|
|
2582
|
+
files;
|
|
2583
|
+
/** The sandbox's Linux desktop, for sandboxes created with `desktop: true`. */
|
|
2584
|
+
desktop;
|
|
2585
|
+
/** @internal */
|
|
2586
|
+
_client;
|
|
2587
|
+
_processConnection;
|
|
2588
|
+
_processOutput = new ProcessOutputBuffer();
|
|
2589
|
+
/** @internal */
|
|
2590
|
+
constructor(data, client) {
|
|
2591
|
+
this._client = client;
|
|
2592
|
+
this._apply(data);
|
|
2593
|
+
this._processConnection = new ProcessConnection(() => this._connectionEndpoint());
|
|
2594
|
+
this.processes = new SandboxProcesses(this, () => this._processConnection.disconnect());
|
|
2595
|
+
this.files = new SandboxFiles(this);
|
|
2596
|
+
this.desktop = new require_sandbox_desktop.SandboxDesktop(this);
|
|
2597
|
+
}
|
|
2598
|
+
/** @internal Overwrite this sandbox's fields in place from a fresh wire snapshot. */
|
|
2599
|
+
_apply(data) {
|
|
2600
|
+
this.id = data.sandbox_id;
|
|
2601
|
+
this.name = data.name;
|
|
2602
|
+
this.labels = { ...data.labels };
|
|
2603
|
+
this.status = data.status;
|
|
2604
|
+
this.vcpuCount = data.vcpu_count;
|
|
2605
|
+
this.memSizeMiB = data.mem_size_mib;
|
|
2606
|
+
this.baseImage = data.base_image;
|
|
2607
|
+
this.imageDigest = data.image_digest ?? "";
|
|
2608
|
+
this.platform = data.platform;
|
|
2609
|
+
this.maxTtlSeconds = data.max_ttl_seconds;
|
|
2610
|
+
this.idleTtlSeconds = data.idle_ttl_seconds ?? 0;
|
|
2611
|
+
this.onTimeout = data.on_timeout ?? "pause";
|
|
2612
|
+
this.maxConcurrentExecs = data.max_concurrent_execs;
|
|
2613
|
+
this.endpoints = data.endpoints?.map((endpoint) => ({ ...endpoint }));
|
|
2614
|
+
this.mounts = (data.mounts ?? []).map(sandboxMountFromWire);
|
|
2615
|
+
this.createdAt = new Date(data.created_at);
|
|
2616
|
+
this.runningAt = data.running_at ? new Date(data.running_at) : void 0;
|
|
2617
|
+
this.finishedAt = data.finished_at ? new Date(data.finished_at) : void 0;
|
|
2618
|
+
this.lastActiveAt = new Date(data.last_active_at);
|
|
2619
|
+
this.exitReason = data.exit_reason;
|
|
2620
|
+
this.checkpoint = data.checkpoint;
|
|
2621
|
+
return this;
|
|
2622
|
+
}
|
|
2623
|
+
toJSON() {
|
|
2624
|
+
return {
|
|
2625
|
+
id: this.id,
|
|
2626
|
+
name: this.name,
|
|
2627
|
+
labels: { ...this.labels },
|
|
2628
|
+
status: this.status,
|
|
2629
|
+
vcpuCount: this.vcpuCount,
|
|
2630
|
+
memSizeMiB: this.memSizeMiB,
|
|
2631
|
+
baseImage: this.baseImage,
|
|
2632
|
+
imageDigest: this.imageDigest,
|
|
2633
|
+
platform: this.platform,
|
|
2634
|
+
maxTtlSeconds: this.maxTtlSeconds,
|
|
2635
|
+
idleTtlSeconds: this.idleTtlSeconds,
|
|
2636
|
+
onTimeout: this.onTimeout,
|
|
2637
|
+
maxConcurrentExecs: this.maxConcurrentExecs,
|
|
2638
|
+
endpoints: this.endpoints?.map((endpoint) => ({ ...endpoint })),
|
|
2639
|
+
mounts: this.mounts.map((mount) => ({ ...mount })),
|
|
2640
|
+
createdAt: this.createdAt,
|
|
2641
|
+
runningAt: this.runningAt,
|
|
2642
|
+
finishedAt: this.finishedAt,
|
|
2643
|
+
lastActiveAt: this.lastActiveAt,
|
|
2644
|
+
exitReason: this.exitReason,
|
|
2645
|
+
checkpoint: this.checkpoint
|
|
2646
|
+
};
|
|
2647
|
+
}
|
|
2648
|
+
/** Start a process and return its handle without waiting for exit. */
|
|
2649
|
+
async run(command, options = {}) {
|
|
2650
|
+
const process = new SandboxProcess("", 0, options.collectOutput ?? true, this._processOutput, () => this._processConnection.open(), (request) => this._control(request));
|
|
2651
|
+
const terminal = typeof options.terminal === "object" ? {
|
|
2652
|
+
cols: options.terminal.cols ?? 80,
|
|
2653
|
+
rows: options.terminal.rows ?? 24
|
|
2654
|
+
} : options.terminal;
|
|
2655
|
+
await process._connect({
|
|
2656
|
+
type: "start",
|
|
2657
|
+
command,
|
|
2658
|
+
cwd: options.cwd,
|
|
2659
|
+
terminal,
|
|
2660
|
+
env: options.env ?? {},
|
|
2661
|
+
timeout_seconds: options.timeoutSeconds
|
|
2662
|
+
});
|
|
2663
|
+
if (options.onOutput) process._deliverTo(options.onOutput);
|
|
2664
|
+
return process;
|
|
2665
|
+
}
|
|
2666
|
+
/** Reattach to a process, optionally resuming output from a cursor. */
|
|
2667
|
+
async attach(processId, options = {}) {
|
|
2668
|
+
const offset = options.offset ?? 0;
|
|
2669
|
+
const process = new SandboxProcess(processId, offset, options.collectOutput ?? true, this._processOutput, () => this._processConnection.open(), (request) => this._control(request));
|
|
2670
|
+
await process._connect({
|
|
2671
|
+
type: "attach",
|
|
2672
|
+
process_id: processId,
|
|
2673
|
+
offset,
|
|
2674
|
+
...options.shared ? { shared: true } : {}
|
|
2675
|
+
});
|
|
2676
|
+
if (options.onOutput) process._deliverTo(options.onOutput);
|
|
2677
|
+
return process;
|
|
2678
|
+
}
|
|
2679
|
+
async _connectionEndpoint() {
|
|
2680
|
+
const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/connections", { params: { path: { sid: this.id } } }), "transient"));
|
|
2681
|
+
return {
|
|
2682
|
+
url: data.endpoint,
|
|
2683
|
+
token: data.token
|
|
2684
|
+
};
|
|
2685
|
+
}
|
|
2686
|
+
async _control(request) {
|
|
2687
|
+
const socket = await this._processConnection.open();
|
|
2688
|
+
const expected = request.type === "kill" ? "killed" : "resized";
|
|
2689
|
+
await new Promise((resolve, reject) => {
|
|
2690
|
+
socket.addEventListener("message", (message) => {
|
|
2691
|
+
try {
|
|
2692
|
+
const event = message.data;
|
|
2693
|
+
if (event.type === "error") reject(/* @__PURE__ */ new Error(`${event.error}: ${event.message}`));
|
|
2694
|
+
else if (event.type !== expected) reject(/* @__PURE__ */ new Error(`Expected ${expected}, received ${event.type}`));
|
|
2695
|
+
else resolve();
|
|
2696
|
+
} catch (error) {
|
|
2697
|
+
reject(error);
|
|
2698
|
+
} finally {
|
|
2699
|
+
socket.close();
|
|
2700
|
+
}
|
|
2701
|
+
}, { once: true });
|
|
2702
|
+
socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} request failed`)));
|
|
2703
|
+
socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error(`Process ${request.type} connection closed before confirmation`)));
|
|
2704
|
+
try {
|
|
2705
|
+
socket.sendRequest(request);
|
|
2706
|
+
} catch (error) {
|
|
2707
|
+
reject(error);
|
|
2708
|
+
socket.finish();
|
|
2709
|
+
}
|
|
2710
|
+
});
|
|
2711
|
+
}
|
|
2712
|
+
/** Run a process and wait for it to exit. */
|
|
2713
|
+
async exec(command, options = {}) {
|
|
2714
|
+
return (await this.run(command, options)).wait();
|
|
2715
|
+
}
|
|
2716
|
+
/** Re-fetch this sandbox. */
|
|
2717
|
+
async refresh() {
|
|
2718
|
+
const data = await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }), "transient"));
|
|
2719
|
+
return this._apply(data);
|
|
2720
|
+
}
|
|
2721
|
+
/** Start this sandbox. */
|
|
2722
|
+
async start(options = {}) {
|
|
2723
|
+
const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/start", {
|
|
2724
|
+
params: {
|
|
2725
|
+
path: { sid: this.id },
|
|
2726
|
+
query: { wait: options.wait ?? true }
|
|
2727
|
+
},
|
|
2728
|
+
...options.mounts !== void 0 && { body: { mounts: options.mounts.map(sandboxMountWire) } }
|
|
2729
|
+
}), options.mounts === void 0 ? "transient" : "connect"));
|
|
2730
|
+
this._apply(data);
|
|
2731
|
+
return options.wait === false ? this : waitForSandboxStart(this);
|
|
2732
|
+
}
|
|
2733
|
+
/** Stop this sandbox. */
|
|
2734
|
+
async stop(options = {}) {
|
|
2735
|
+
const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/stop", { params: { path: { sid: this.id } } }), "transient"));
|
|
2736
|
+
this._apply(data);
|
|
2737
|
+
return options.wait === false ? this : waitWhileSandboxStatus(this, "stopping");
|
|
2738
|
+
}
|
|
2739
|
+
/** Pause this sandbox, preserving its CPU and memory state. */
|
|
2740
|
+
async pause(options = {}) {
|
|
2741
|
+
const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }), "transient"));
|
|
2742
|
+
this._apply(data);
|
|
2743
|
+
if (options.wait === false) return this;
|
|
2744
|
+
await waitWhileSandboxStatus(this, "pausing");
|
|
2745
|
+
if (this.status !== "paused") throw new SandboxPauseError(this);
|
|
2746
|
+
return this;
|
|
2747
|
+
}
|
|
2748
|
+
/** Resume this sandbox from its preserved CPU and memory state. */
|
|
2749
|
+
async resume(options = {}) {
|
|
2750
|
+
const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/resume", { params: {
|
|
2751
|
+
path: { sid: this.id },
|
|
2752
|
+
query: { wait: options.wait ?? true }
|
|
2753
|
+
} }), "transient"));
|
|
2754
|
+
this._apply(data);
|
|
2755
|
+
return options.wait === false ? this : waitForSandboxStart(this);
|
|
2756
|
+
}
|
|
2757
|
+
/**
|
|
2758
|
+
* Create an isolated writable branch from this sandbox's current state.
|
|
2759
|
+
* A running sandbox is paused for the snapshot and resumed once the fork is
|
|
2760
|
+
* accepted; a paused or stopped sandbox is left as it is. The fork names the
|
|
2761
|
+
* checkpoint the pause returned, so it does not depend on the source still
|
|
2762
|
+
* being paused when the request lands. Resuming the source is best effort:
|
|
2763
|
+
* the child is returned even if the source could not be resumed, so check
|
|
2764
|
+
* the source's status afterwards if that matters.
|
|
2765
|
+
*/
|
|
2766
|
+
async fork(options = {}) {
|
|
2767
|
+
const paused = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/pause", { params: { path: { sid: this.id } } }), "transient"));
|
|
2768
|
+
this._apply(paused);
|
|
2769
|
+
const resumeAfterFork = this.status === "pausing";
|
|
2770
|
+
const checkpoint = this.checkpoint;
|
|
2771
|
+
const wait = resumeAfterFork ? false : options.wait ?? true;
|
|
2772
|
+
const body = {
|
|
2773
|
+
name: options.name,
|
|
2774
|
+
checkpoint,
|
|
2775
|
+
labels: options.labels
|
|
2776
|
+
};
|
|
2777
|
+
const fork = await waitWhileSandboxStatus(this, "pausing").then(() => unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/fork", {
|
|
2778
|
+
params: {
|
|
2779
|
+
path: { sid: this.id },
|
|
2780
|
+
query: { wait }
|
|
2781
|
+
},
|
|
2782
|
+
body
|
|
2783
|
+
}), "connect"))).then((data) => new Sandbox(data, this._client)).finally(() => resumeAfterFork ? this.resume({ wait: false }).catch(() => void 0) : void 0);
|
|
2784
|
+
if (options.wait === false) return fork;
|
|
2785
|
+
await waitForSandboxStart(fork);
|
|
2786
|
+
if (resumeAfterFork) await waitForSandboxStart(this).catch(() => void 0);
|
|
2787
|
+
return fork;
|
|
2788
|
+
}
|
|
2789
|
+
/** Expose a TCP port publicly (1–65535), returning its hostname. */
|
|
2790
|
+
async exposePort(port) {
|
|
2791
|
+
const client = this._client;
|
|
2792
|
+
return (await unwrap(retryApiRequest(() => client.PUT("/api/sandboxes/{sid}/ports/{port}", { params: { path: {
|
|
2793
|
+
sid: this.id,
|
|
2794
|
+
port
|
|
2795
|
+
} } }), "transient"))).hostname;
|
|
2796
|
+
}
|
|
2797
|
+
/** List explicitly exposed public ports. Service-published ports are in `endpoints`. */
|
|
2798
|
+
async listPorts() {
|
|
2799
|
+
const client = this._client;
|
|
2800
|
+
return (await unwrap(retryApiRequest(() => client.GET("/api/sandboxes/{sid}/ports", { params: { path: { sid: this.id } } }), "transient"))).ports;
|
|
2801
|
+
}
|
|
2802
|
+
/** Remove explicit public exposure. A service publishing the same port remains reachable. */
|
|
2803
|
+
async unexposePort(port) {
|
|
2804
|
+
const client = this._client;
|
|
2805
|
+
await unwrapEmpty(retryApiRequest(() => client.DELETE("/api/sandboxes/{sid}/ports/{port}", { params: { path: {
|
|
2806
|
+
sid: this.id,
|
|
2807
|
+
port
|
|
2808
|
+
} } }), "transient"));
|
|
2809
|
+
}
|
|
2810
|
+
/** Authorize HTTP access to one port without making it public. */
|
|
2811
|
+
async createPortToken(port, options = {}) {
|
|
2812
|
+
const data = await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes/{sid}/port-tokens", {
|
|
2813
|
+
params: { path: { sid: this.id } },
|
|
2814
|
+
body: {
|
|
2815
|
+
port,
|
|
2816
|
+
ttl: options.ttl
|
|
2817
|
+
}
|
|
2818
|
+
}), "connect"));
|
|
2819
|
+
return {
|
|
2820
|
+
...portTokenFromWire(data),
|
|
2821
|
+
hostname: data.hostname,
|
|
2822
|
+
token: data.token
|
|
2823
|
+
};
|
|
2824
|
+
}
|
|
2825
|
+
/** Get token metadata. Expired and revoked tokens return not found. */
|
|
2826
|
+
async getPortToken(tokenId) {
|
|
2827
|
+
return portTokenFromWire(await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}/port-tokens/{token_id}", { params: { path: {
|
|
2828
|
+
sid: this.id,
|
|
2829
|
+
token_id: tokenId
|
|
2830
|
+
} } }), "transient")));
|
|
2831
|
+
}
|
|
2832
|
+
/** List token metadata across pages. `limit` caps the total number returned. */
|
|
2833
|
+
async listPortTokens(options = {}) {
|
|
2834
|
+
const tokens = [];
|
|
2835
|
+
let cursor = options.cursor;
|
|
2836
|
+
for (;;) {
|
|
2837
|
+
const remaining = options.limit === void 0 ? void 0 : options.limit - tokens.length;
|
|
2838
|
+
if (remaining !== void 0 && remaining <= 0) return tokens;
|
|
2839
|
+
const page = await this.listPortTokensPage({
|
|
2840
|
+
limit: remaining === void 0 ? 100 : Math.min(remaining, 100),
|
|
2841
|
+
cursor
|
|
2842
|
+
});
|
|
2843
|
+
tokens.push(...page.tokens);
|
|
2844
|
+
if (!page.nextCursor) return tokens;
|
|
2845
|
+
cursor = page.nextCursor;
|
|
2846
|
+
}
|
|
2847
|
+
}
|
|
2848
|
+
/** Fetch one page of token metadata; pass `nextCursor` back as `cursor`. */
|
|
2849
|
+
async listPortTokensPage(options = {}) {
|
|
2850
|
+
const { data, nextCursor } = await unwrapPage(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}/port-tokens", { params: {
|
|
2851
|
+
path: { sid: this.id },
|
|
2852
|
+
query: {
|
|
2853
|
+
limit: options.limit ?? 100,
|
|
2854
|
+
cursor: options.cursor
|
|
2855
|
+
}
|
|
2856
|
+
} }), "transient"));
|
|
2857
|
+
return {
|
|
2858
|
+
tokens: data.tokens.map(portTokenFromWire),
|
|
2859
|
+
nextCursor
|
|
2860
|
+
};
|
|
2861
|
+
}
|
|
2862
|
+
/** Revoke a token for new connections. Existing connections remain open. */
|
|
2863
|
+
async deletePortToken(token) {
|
|
2864
|
+
const tokenId = typeof token === "string" ? token : token.id;
|
|
2865
|
+
await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/sandboxes/{sid}/port-tokens/{token_id}", { params: { path: {
|
|
2866
|
+
sid: this.id,
|
|
2867
|
+
token_id: tokenId
|
|
2868
|
+
} } }), "transient"));
|
|
2869
|
+
}
|
|
2870
|
+
/** Get this running sandbox's effective network policy. */
|
|
2871
|
+
async getNetwork() {
|
|
2872
|
+
const client = this._client;
|
|
2873
|
+
return unwrap(retryApiRequest(() => client.GET("/api/sandboxes/{sid}/network", { params: { path: { sid: this.id } } }), "transient"));
|
|
2874
|
+
}
|
|
2875
|
+
/** Replace this running sandbox's complete network policy and return the effective policy. */
|
|
2876
|
+
async updateNetwork(network) {
|
|
2877
|
+
const client = this._client;
|
|
2878
|
+
return unwrap(retryApiRequest(() => client.PUT("/api/sandboxes/{sid}/network", {
|
|
2879
|
+
params: { path: { sid: this.id } },
|
|
2880
|
+
body: network
|
|
2881
|
+
}), "transient"));
|
|
2882
|
+
}
|
|
2883
|
+
/** Update either or both TTLs in seconds. Omitted settings remain unchanged. */
|
|
2884
|
+
async setTimeout(timeout) {
|
|
2885
|
+
const options = typeof timeout === "number" ? { timeoutSeconds: timeout } : timeout;
|
|
2886
|
+
const client = this._client;
|
|
2887
|
+
const data = await unwrap(retryApiRequest(() => client.POST("/api/sandboxes/{sid}/timeout", {
|
|
2888
|
+
params: { path: { sid: this.id } },
|
|
2889
|
+
body: {
|
|
2890
|
+
timeout: options.timeoutSeconds,
|
|
2891
|
+
idle_ttl_seconds: options.idleTtlSeconds
|
|
2892
|
+
}
|
|
2893
|
+
}), "transient"));
|
|
2894
|
+
return this._apply(data);
|
|
2895
|
+
}
|
|
2896
|
+
/** Delete this sandbox and its backing disk. */
|
|
2897
|
+
async delete() {
|
|
2898
|
+
await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/sandboxes/{sid}", { params: { path: { sid: this.id } } }), "transient"));
|
|
2899
|
+
}
|
|
2900
|
+
};
|
|
2901
|
+
/** @internal Continue waiting if the server returned before startup completed. */
|
|
2902
|
+
async function waitForSandboxStart(sandbox) {
|
|
2903
|
+
return waitWhileSandboxStatus(sandbox, "pending");
|
|
2904
|
+
}
|
|
2905
|
+
async function waitWhileSandboxStatus(sandbox, status) {
|
|
2906
|
+
while (sandbox.status === status) {
|
|
2907
|
+
await sleep();
|
|
2908
|
+
await sandbox.refresh();
|
|
2909
|
+
}
|
|
2910
|
+
return sandbox;
|
|
2911
|
+
}
|
|
2912
|
+
//#endregion
|
|
2913
|
+
//#region src/sandboxes.ts
|
|
2914
|
+
/** Server-side maximum page size for `GET /api/sandboxes`. */
|
|
2915
|
+
const SANDBOX_PAGE_LIMIT = 100;
|
|
2916
|
+
function matchesListFilters(sandbox, options) {
|
|
2917
|
+
return Object.entries(options.labels ?? {}).every(([key, value]) => sandbox.labels?.[key] === value) && (options.name === void 0 || sandbox.name === options.name) && sandbox.name.startsWith(options.namePrefix ?? "");
|
|
2918
|
+
}
|
|
2919
|
+
var Sandboxes = class {
|
|
2920
|
+
/** @internal */
|
|
2921
|
+
_client;
|
|
2922
|
+
/** @internal */
|
|
2923
|
+
constructor(client) {
|
|
2924
|
+
this._client = client;
|
|
2925
|
+
}
|
|
2926
|
+
/**
|
|
2927
|
+
* List the account's sandboxes, oldest first, keeping those that match every
|
|
2928
|
+
* filter given. Follows the server's pages until none remain.
|
|
2929
|
+
*/
|
|
2930
|
+
async list(options = {}) {
|
|
2931
|
+
const filesystem = typeof options.disk === "string" ? options.disk : options.disk?.id;
|
|
2932
|
+
const labels = Object.entries(options.labels ?? {}).map(([key, value]) => `${key}=${value}`);
|
|
2933
|
+
const client = this._client;
|
|
2934
|
+
const sandboxes = [];
|
|
2935
|
+
let cursor;
|
|
2936
|
+
for (;;) {
|
|
2937
|
+
const { data, nextCursor } = await unwrapPage(retryApiRequest(() => client.GET("/api/sandboxes", { params: { query: {
|
|
2938
|
+
filesystem,
|
|
2939
|
+
label: labels.length > 0 ? labels : void 0,
|
|
2940
|
+
name: options.name,
|
|
2941
|
+
name_prefix: options.namePrefix,
|
|
2942
|
+
limit: SANDBOX_PAGE_LIMIT,
|
|
2943
|
+
cursor
|
|
2944
|
+
} } }), "transient"));
|
|
2945
|
+
for (const sandbox of data?.sandboxes ?? []) if (matchesListFilters(sandbox, options)) sandboxes.push(new Sandbox(sandbox, this._client));
|
|
2946
|
+
if (!nextCursor || nextCursor === cursor) return sandboxes;
|
|
2947
|
+
cursor = nextCursor;
|
|
2948
|
+
}
|
|
2949
|
+
}
|
|
2950
|
+
async get(id) {
|
|
2951
|
+
return new Sandbox(await unwrap(retryApiRequest(() => this._client.GET("/api/sandboxes/{sid}", { params: { path: { sid: id } } }), "transient")), this._client);
|
|
2952
|
+
}
|
|
2953
|
+
async create(request = {}, options = {}) {
|
|
2954
|
+
if (request.desktop) request = {
|
|
2955
|
+
...request.imageId === void 0 && { baseImage: "ghcr.io/archil-data/sandbox-desktop:latest" },
|
|
2956
|
+
vcpuCount: 2,
|
|
2957
|
+
memSizeMiB: require_sandbox_desktop.DESKTOP_MEMORY_MIB,
|
|
2958
|
+
idleTtlSeconds: 0,
|
|
2959
|
+
maxTtlSeconds: require_sandbox_desktop.DESKTOP_MAX_TTL_SECONDS,
|
|
2960
|
+
...Object.fromEntries(Object.entries(request).filter(([, value]) => value !== void 0))
|
|
2961
|
+
};
|
|
2962
|
+
const body = {
|
|
2963
|
+
name: request.name,
|
|
2964
|
+
vcpu_count: request.vcpuCount,
|
|
2965
|
+
mem_size_mib: request.memSizeMiB,
|
|
2966
|
+
base_image: request.baseImage,
|
|
2967
|
+
image_id: request.imageId,
|
|
2968
|
+
env: request.env,
|
|
2969
|
+
max_ttl_seconds: request.maxTtlSeconds,
|
|
2970
|
+
idle_ttl_seconds: request.idleTtlSeconds,
|
|
2971
|
+
on_timeout: request.onTimeout,
|
|
2972
|
+
max_concurrent_execs: request.maxConcurrentExecs,
|
|
2973
|
+
network: request.network,
|
|
2974
|
+
ports: request.ports,
|
|
2975
|
+
...request.mounts !== void 0 && { mounts: request.mounts.map(sandboxMountWire) },
|
|
2976
|
+
labels: request.labels
|
|
2977
|
+
};
|
|
2978
|
+
const sandbox = new Sandbox(await unwrap(retryApiRequest(() => this._client.POST("/api/sandboxes", {
|
|
2979
|
+
params: { query: { wait: options.wait ?? true } },
|
|
2980
|
+
body
|
|
2981
|
+
}), "connect")), this._client);
|
|
2982
|
+
return options.wait === false ? sandbox : waitForSandboxStart(sandbox);
|
|
2983
|
+
}
|
|
2984
|
+
};
|
|
2985
|
+
//#endregion
|
|
2986
|
+
//#region src/tokens.ts
|
|
2987
|
+
var Tokens = class {
|
|
2988
|
+
/** @internal */
|
|
2989
|
+
_client;
|
|
2990
|
+
/** @internal */
|
|
2991
|
+
constructor(client) {
|
|
2992
|
+
this._client = client;
|
|
2993
|
+
}
|
|
2994
|
+
async list(opts) {
|
|
2995
|
+
return (await unwrap(retryApiRequest(() => this._client.GET("/api/tokens", { params: { query: {
|
|
2996
|
+
limit: opts?.limit,
|
|
2997
|
+
cursor: opts?.cursor
|
|
2998
|
+
} } }), "transient"))).tokens ?? [];
|
|
2999
|
+
}
|
|
3000
|
+
async create(req) {
|
|
3001
|
+
return await unwrap(retryApiRequest(() => this._client.POST("/api/tokens", { body: req }), "connect"));
|
|
3002
|
+
}
|
|
3003
|
+
async delete(id) {
|
|
3004
|
+
await unwrapEmpty(retryApiRequest(() => this._client.DELETE("/api/tokens/{tokenId}", { params: { path: { tokenId: id } } }), "connect"));
|
|
3005
|
+
}
|
|
3006
|
+
};
|
|
3007
|
+
//#endregion
|
|
3008
|
+
//#region src/workspace.ts
|
|
3009
|
+
function isExecMountSpec$1(m) {
|
|
3010
|
+
return typeof m === "object" && m !== null && "disk" in m;
|
|
3011
|
+
}
|
|
3012
|
+
/** Keep groups up to the one holding the `maxResults`-th match, and end that
|
|
3013
|
+
* group after up to `after` more lines, which become context so the groups
|
|
3014
|
+
* hold exactly the kept matches. With multiline, a run of matching lines is
|
|
3015
|
+
* one match. Mirrors the controlplane's truncation of a single disk's groups. */
|
|
3016
|
+
function truncateGroups(groups, maxResults, after, multiline) {
|
|
3017
|
+
let seen = 0;
|
|
3018
|
+
for (let i = 0; i < groups.length; i++) {
|
|
3019
|
+
const lines = groups[i].lines;
|
|
3020
|
+
for (let j = 0; j < lines.length; j++) {
|
|
3021
|
+
if (lines[j].match && !(multiline && j > 0 && lines[j - 1].match)) seen++;
|
|
3022
|
+
if (seen === maxResults && !(multiline && j + 1 < lines.length && lines[j + 1].match)) {
|
|
3023
|
+
const kept = lines.slice(0, Math.min(j + 1 + after, lines.length)).map((l, k) => k > j ? {
|
|
3024
|
+
...l,
|
|
3025
|
+
match: false
|
|
3026
|
+
} : l);
|
|
3027
|
+
return [...groups.slice(0, i), {
|
|
3028
|
+
...groups[i],
|
|
3029
|
+
lines: kept
|
|
3030
|
+
}];
|
|
3031
|
+
}
|
|
3032
|
+
}
|
|
3033
|
+
}
|
|
3034
|
+
return groups;
|
|
3035
|
+
}
|
|
3036
|
+
/**
|
|
3037
|
+
* A key-routed filesystem spanning several Archil disks. Each disk is mounted
|
|
3038
|
+
* under a name and addressed as the first segment of a key (`<name>/...`);
|
|
3039
|
+
* `getObject`, `putObject`, `deleteObject`, `listObjects`, and `grep` route to
|
|
3040
|
+
* the right disk by that segment (and `listObjects` / `grep` fan out across all
|
|
3041
|
+
* of them when the key/prefix doesn't name one). Implements the same
|
|
3042
|
+
* {@link FileSystem} surface as a single {@link Disk}, so it works anywhere a
|
|
3043
|
+
* disk does. Mounts can be changed at runtime with {@link addDisk} /
|
|
3044
|
+
* {@link removeDisk}.
|
|
3045
|
+
*/
|
|
3046
|
+
var Workspace = class {
|
|
3047
|
+
client;
|
|
3048
|
+
mounts = /* @__PURE__ */ new Map();
|
|
3049
|
+
/** @internal Use `archil.workspace({ ... })`. */
|
|
3050
|
+
constructor(client, mounts) {
|
|
3051
|
+
this.client = client;
|
|
3052
|
+
for (const [name, value] of Object.entries(mounts)) this.addDisk(name, value);
|
|
3053
|
+
if (this.mounts.size === 0) throw new Error("workspace() needs at least one disk");
|
|
3054
|
+
}
|
|
3055
|
+
/** Mount (or replace) a disk at `name`; its objects are addressed as
|
|
3056
|
+
* `<name>/...`. Accepts a `Disk` or a mount spec (read-only / subdirectory /
|
|
3057
|
+
* conditional / delegation checkouts); a bare disk-id string is rejected —
|
|
3058
|
+
* fetch the disk first. */
|
|
3059
|
+
addDisk(name, disk) {
|
|
3060
|
+
const rel = name.replace(/^\/+|\/+$/g, "");
|
|
3061
|
+
if (!rel) throw new Error("workspace mount name must be non-empty");
|
|
3062
|
+
if (rel.includes("/")) throw new Error(`workspace mount name '${name}' must not contain '/'`);
|
|
3063
|
+
if (rel === "." || rel === "..") throw new Error(`workspace mount name '${name}' is reserved ('.' and '..' are path navigation, not disk names)`);
|
|
3064
|
+
let d;
|
|
3065
|
+
let readOnly = false;
|
|
3066
|
+
let subdirectory;
|
|
3067
|
+
let conditional = false;
|
|
3068
|
+
let queueMs;
|
|
3069
|
+
let checkoutPaths;
|
|
3070
|
+
if (isExecMountSpec$1(disk)) {
|
|
3071
|
+
d = disk.disk;
|
|
3072
|
+
readOnly = disk.readOnly ?? false;
|
|
3073
|
+
subdirectory = disk.subdirectory;
|
|
3074
|
+
conditional = disk.conditional ?? false;
|
|
3075
|
+
queueMs = disk.queueMs;
|
|
3076
|
+
checkoutPaths = disk.checkoutPaths;
|
|
3077
|
+
} else d = disk;
|
|
3078
|
+
if (typeof d === "string") throw new Error("workspace needs Disk objects, not disk-id strings; fetch with archil.getDisk(id) first");
|
|
3079
|
+
this.mounts.set(rel, {
|
|
3080
|
+
disk: d,
|
|
3081
|
+
readOnly,
|
|
3082
|
+
subdirectory,
|
|
3083
|
+
conditional,
|
|
3084
|
+
queueMs,
|
|
3085
|
+
checkoutPaths
|
|
3086
|
+
});
|
|
3087
|
+
return this;
|
|
3088
|
+
}
|
|
3089
|
+
/** Unmount the disk at `name`. Returns whether a disk was removed. Refuses to
|
|
3090
|
+
* remove the last disk — a workspace must always have at least one (the same
|
|
3091
|
+
* invariant the constructor enforces), else fan-out/exec would have nothing to
|
|
3092
|
+
* route to. */
|
|
3093
|
+
removeDisk(name) {
|
|
3094
|
+
const rel = name.replace(/^\/+|\/+$/g, "");
|
|
3095
|
+
if (this.mounts.has(rel) && this.mounts.size === 1) throw new Error("cannot remove the last disk from a workspace; a workspace must keep at least one");
|
|
3096
|
+
return this.mounts.delete(rel);
|
|
3097
|
+
}
|
|
3098
|
+
/** The names of the currently-mounted disks. */
|
|
3099
|
+
diskNames() {
|
|
3100
|
+
return [...this.mounts.keys()];
|
|
3101
|
+
}
|
|
3102
|
+
unknownDisk(name) {
|
|
3103
|
+
return /* @__PURE__ */ new Error(`No disk named '${name}'. Address objects by disk: ${this.diskNames().map((n) => `${n}/…`).join(", ")}`);
|
|
3104
|
+
}
|
|
3105
|
+
/** Resolve a workspace key (`<name>/...`) to the disk and the disk-relative key. */
|
|
3106
|
+
route(key) {
|
|
3107
|
+
const segs = require_paths.toSegments(key);
|
|
3108
|
+
if (segs.length === 0) throw new Error("that key is the workspace root, not an object; name a disk, e.g. data/file.txt");
|
|
3109
|
+
const entry = this.mounts.get(segs[0]);
|
|
3110
|
+
if (!entry) throw this.unknownDisk(segs[0]);
|
|
3111
|
+
return {
|
|
3112
|
+
entry,
|
|
3113
|
+
diskKey: this.diskKey(entry, segs.slice(1).join("/"))
|
|
3114
|
+
};
|
|
3115
|
+
}
|
|
3116
|
+
/** Mounts touched by a key prefix; an empty prefix fans out to all of them. */
|
|
3117
|
+
covered(prefix) {
|
|
3118
|
+
const segs = require_paths.toSegments(prefix);
|
|
3119
|
+
if (segs.length === 0) return [...this.mounts.entries()].map(([name, entry]) => ({
|
|
3120
|
+
name,
|
|
3121
|
+
entry,
|
|
3122
|
+
rel: this.diskKey(entry, "")
|
|
3123
|
+
}));
|
|
3124
|
+
const entry = this.mounts.get(segs[0]);
|
|
3125
|
+
if (!entry) throw this.unknownDisk(segs[0]);
|
|
3126
|
+
return [{
|
|
3127
|
+
name: segs[0],
|
|
3128
|
+
entry,
|
|
3129
|
+
rel: this.diskKey(entry, segs.slice(1).join("/"))
|
|
3130
|
+
}];
|
|
3131
|
+
}
|
|
3132
|
+
/** Route grep globs written against the workspace root to the mounts they
|
|
3133
|
+
* can match. A glob that starts with a mount's name goes to that mount without
|
|
3134
|
+
* the name. One with no `/`, or that starts with `**` + `/` with or without a
|
|
3135
|
+
* leading `/`, goes to every mount as written, and also applies to a mount it
|
|
3136
|
+
* names exactly, like `!cache` or `**` + `/logs/**`. Mount names are matched
|
|
3137
|
+
* literally, so `!l*` doesn't skip a `logs` mount. Leaves out a mount whose
|
|
3138
|
+
* directory an exclude names, or that no include reaches, and throws for any
|
|
3139
|
+
* other glob with a `/`. */
|
|
3140
|
+
rootGlobs(globs) {
|
|
3141
|
+
const routed = new Map([...this.mounts.keys()].map((name) => [name, []]));
|
|
3142
|
+
const excluded = /* @__PURE__ */ new Set();
|
|
3143
|
+
for (const glob of globs) {
|
|
3144
|
+
const exclude = glob.startsWith("!");
|
|
3145
|
+
let body = exclude ? glob.slice(1) : glob;
|
|
3146
|
+
const dirOnly = body.endsWith("/");
|
|
3147
|
+
if (dirOnly) body = body.slice(0, -1);
|
|
3148
|
+
const anchored = body.startsWith("/");
|
|
3149
|
+
if (anchored) body = body.slice(1);
|
|
3150
|
+
const everywhere = !anchored && !body.includes("/") || body === "**" || body.startsWith("**/");
|
|
3151
|
+
if (everywhere) for (const mountGlobs of routed.values()) mountGlobs.push(glob);
|
|
3152
|
+
const path = everywhere && body.startsWith("**/") ? body.slice(3) : body;
|
|
3153
|
+
const slash = path.indexOf("/");
|
|
3154
|
+
const name = slash < 0 ? path : path.slice(0, slash);
|
|
3155
|
+
const rest = slash < 0 ? "" : path.slice(slash + 1);
|
|
3156
|
+
const mountGlobs = routed.get(name);
|
|
3157
|
+
if (!mountGlobs) {
|
|
3158
|
+
if (everywhere) continue;
|
|
3159
|
+
throw new Error(`At the workspace root, a glob with a '/' must start with a mount name (${this.diskNames().map((n) => `${n}/`).join(", ")}) or '**/'; got '${glob}'. To search below one mount, set directory to it.`);
|
|
3160
|
+
}
|
|
3161
|
+
if (rest === "") {
|
|
3162
|
+
if (exclude) excluded.add(name);
|
|
3163
|
+
else excluded.delete(name);
|
|
3164
|
+
continue;
|
|
3165
|
+
}
|
|
3166
|
+
mountGlobs.push(`${exclude ? "!" : ""}${rest.includes("/") ? rest : `/${rest}`}${dirOnly ? "/" : ""}`);
|
|
3167
|
+
}
|
|
3168
|
+
const hasInclude = globs.some((glob) => !glob.startsWith("!"));
|
|
3169
|
+
for (const [name, mountGlobs] of routed) if (excluded.has(name) || hasInclude && mountGlobs.every((glob) => glob.startsWith("!"))) routed.delete(name);
|
|
3170
|
+
return routed;
|
|
3171
|
+
}
|
|
3172
|
+
/** Map a workspace-relative key to the disk's key, applying the mount's subdirectory. */
|
|
3173
|
+
diskKey(entry, rel) {
|
|
3174
|
+
const trimmed = rel.replace(/^\/+/, "");
|
|
3175
|
+
const sub = (entry.subdirectory ?? "").replace(/^\/+|\/+$/g, "");
|
|
3176
|
+
if (!sub) return trimmed;
|
|
3177
|
+
return trimmed ? `${sub}/${trimmed}` : sub;
|
|
3178
|
+
}
|
|
3179
|
+
/** Map a disk key back to its workspace key (`<name>/...`), stripping the mount subdirectory. */
|
|
3180
|
+
abs(name, entry, diskKey) {
|
|
3181
|
+
const sub = (entry.subdirectory ?? "").replace(/^\/+|\/+$/g, "");
|
|
3182
|
+
let rel = diskKey;
|
|
3183
|
+
if (sub && diskKey.startsWith(sub + "/")) rel = diskKey.slice(sub.length + 1);
|
|
3184
|
+
else if (sub && diskKey === sub) rel = "";
|
|
3185
|
+
rel = rel.replace(/^\/+|\/+$/g, "");
|
|
3186
|
+
return rel ? `${name}/${rel}` : name;
|
|
3187
|
+
}
|
|
3188
|
+
async getObject(key) {
|
|
3189
|
+
const { entry, diskKey } = this.route(key);
|
|
3190
|
+
return entry.disk.getObject(diskKey);
|
|
3191
|
+
}
|
|
3192
|
+
async putObject(key, body, options) {
|
|
3193
|
+
const { entry, diskKey } = this.route(key);
|
|
3194
|
+
if (entry.readOnly) throw new Error(`${key} is on a read-only disk and cannot be written.`);
|
|
3195
|
+
return entry.disk.putObject(diskKey, body, options);
|
|
3196
|
+
}
|
|
3197
|
+
async deleteObject(key) {
|
|
3198
|
+
const { entry, diskKey } = this.route(key);
|
|
3199
|
+
if (entry.readOnly) throw new Error(`${key} is on a read-only disk and cannot be deleted.`);
|
|
3200
|
+
await entry.disk.deleteObject(diskKey);
|
|
3201
|
+
}
|
|
3202
|
+
async listObjects(prefix, opts = {}) {
|
|
3203
|
+
if (require_paths.toSegments(prefix ?? "").length === 0 && !opts.recursive) return {
|
|
3204
|
+
objects: [],
|
|
3205
|
+
commonPrefixes: this.diskNames().map((n) => `${n}/`).sort(),
|
|
3206
|
+
isTruncated: false,
|
|
3207
|
+
keyCount: 0
|
|
3208
|
+
};
|
|
3209
|
+
const covered = this.covered(prefix ?? "");
|
|
3210
|
+
const listings = await Promise.allSettled(covered.map(({ entry, rel }) => {
|
|
3211
|
+
const p = rel ? rel.endsWith("/") ? rel : `${rel}/` : void 0;
|
|
3212
|
+
return entry.disk.listObjects(p, { recursive: opts.recursive });
|
|
3213
|
+
}));
|
|
3214
|
+
const objects = [];
|
|
3215
|
+
const commonPrefixes = [];
|
|
3216
|
+
let isTruncated = false;
|
|
3217
|
+
let keyCount = 0;
|
|
3218
|
+
covered.forEach(({ name, entry }, i) => {
|
|
3219
|
+
const settled = listings[i];
|
|
3220
|
+
if (settled.status === "rejected") {
|
|
3221
|
+
isTruncated = true;
|
|
3222
|
+
return;
|
|
3223
|
+
}
|
|
3224
|
+
const listing = settled.value;
|
|
3225
|
+
for (const cp of listing.commonPrefixes) commonPrefixes.push(`${this.abs(name, entry, cp.replace(/\/+$/, ""))}/`);
|
|
3226
|
+
for (const obj of listing.objects) objects.push({
|
|
3227
|
+
...obj,
|
|
3228
|
+
key: this.abs(name, entry, obj.key)
|
|
3229
|
+
});
|
|
3230
|
+
isTruncated = isTruncated || listing.isTruncated;
|
|
3231
|
+
keyCount += listing.keyCount;
|
|
3232
|
+
});
|
|
3233
|
+
objects.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
3234
|
+
commonPrefixes.sort();
|
|
3235
|
+
return {
|
|
3236
|
+
objects,
|
|
3237
|
+
commonPrefixes,
|
|
3238
|
+
isTruncated,
|
|
3239
|
+
keyCount
|
|
3240
|
+
};
|
|
3241
|
+
}
|
|
3242
|
+
/**
|
|
3243
|
+
* Grep the disks `directory` covers in parallel and merge their results. At
|
|
3244
|
+
* the workspace root, a glob with a `/` must start with a mount name, like
|
|
3245
|
+
* `data/src/**`, which applies to that mount only, or with `**` + `/`. A glob
|
|
3246
|
+
* with no `/`, like `*.ts`, or one starting with `**` + `/` with or without a
|
|
3247
|
+
* leading `/`, applies inside every mount, and also to a mount it names
|
|
3248
|
+
* exactly, so `!cache` skips the cache mount. Mount names are matched
|
|
3249
|
+
* literally, not as patterns: `!l*` applies inside every mount, but doesn't
|
|
3250
|
+
* skip a mount named `logs`.
|
|
3251
|
+
*/
|
|
3252
|
+
async grep(opts) {
|
|
3253
|
+
const directory = opts.directory ?? "";
|
|
3254
|
+
const rootGlobs = require_paths.toSegments(directory).length === 0 && opts.globs?.length ? this.rootGlobs(opts.globs) : void 0;
|
|
3255
|
+
const covered = this.covered(directory).flatMap((c) => {
|
|
3256
|
+
if (rootGlobs === void 0) return [{
|
|
3257
|
+
...c,
|
|
3258
|
+
globs: opts.globs
|
|
3259
|
+
}];
|
|
3260
|
+
const globs = rootGlobs.get(c.name);
|
|
3261
|
+
return globs === void 0 ? [] : [{
|
|
3262
|
+
...c,
|
|
3263
|
+
globs
|
|
3264
|
+
}];
|
|
3265
|
+
});
|
|
3266
|
+
const results = await Promise.allSettled(covered.map(({ entry, rel, globs }) => entry.disk.grep({
|
|
3267
|
+
...opts,
|
|
3268
|
+
directory: rel,
|
|
3269
|
+
globs
|
|
3270
|
+
})));
|
|
3271
|
+
for (const settled of results) if (settled.status === "rejected" && settled.reason instanceof ArchilApiError && settled.reason.status === 400) throw settled.reason;
|
|
3272
|
+
const matches = [];
|
|
3273
|
+
const groups = [];
|
|
3274
|
+
let filesScanned = 0;
|
|
3275
|
+
let containersDispatched = 0;
|
|
3276
|
+
let computeSecondsUsed = 0;
|
|
3277
|
+
let durationMs = 0;
|
|
3278
|
+
let listingMs = 0;
|
|
3279
|
+
let grepMs = 0;
|
|
3280
|
+
const reasons = /* @__PURE__ */ new Set();
|
|
3281
|
+
covered.forEach(({ name, entry }, i) => {
|
|
3282
|
+
const settled = results[i];
|
|
3283
|
+
if (settled.status === "rejected") {
|
|
3284
|
+
reasons.add("list_failed");
|
|
3285
|
+
return;
|
|
3286
|
+
}
|
|
3287
|
+
const r = settled.value;
|
|
3288
|
+
filesScanned += r.filesScanned;
|
|
3289
|
+
containersDispatched += r.containersDispatched ?? 0;
|
|
3290
|
+
computeSecondsUsed += r.computeSecondsUsed ?? 0;
|
|
3291
|
+
durationMs = Math.max(durationMs, r.durationMs ?? 0);
|
|
3292
|
+
listingMs = Math.max(listingMs, r.listingMs ?? 0);
|
|
3293
|
+
grepMs = Math.max(grepMs, r.grepMs ?? 0);
|
|
3294
|
+
reasons.add(r.stoppedReason);
|
|
3295
|
+
for (const m of r.matches) matches.push({
|
|
3296
|
+
...m,
|
|
3297
|
+
file: this.abs(name, entry, m.file)
|
|
3298
|
+
});
|
|
3299
|
+
for (const g of r.groups ?? []) groups.push({
|
|
3300
|
+
...g,
|
|
3301
|
+
file: this.abs(name, entry, g.file)
|
|
3302
|
+
});
|
|
3303
|
+
});
|
|
3304
|
+
const cap = opts.maxResults ?? 1e3;
|
|
3305
|
+
if (matches.length > cap) reasons.add("max_results");
|
|
3306
|
+
const priority = [
|
|
3307
|
+
"list_failed",
|
|
3308
|
+
"incomplete",
|
|
3309
|
+
"deadline",
|
|
3310
|
+
"max_results"
|
|
3311
|
+
];
|
|
3312
|
+
const stoppedReason = [...reasons].every((x) => x === "completed") ? "completed" : priority.find((x) => reasons.has(x)) ?? "completed";
|
|
3313
|
+
const withGroups = (opts.contextBefore ?? 0) > 0 || (opts.contextAfter ?? 0) > 0;
|
|
3314
|
+
return {
|
|
3315
|
+
matches: matches.slice(0, cap),
|
|
3316
|
+
...withGroups && { groups: matches.length > cap ? truncateGroups(groups, cap, opts.contextAfter ?? 0, opts.multiline ?? false) : groups },
|
|
3317
|
+
stoppedReason,
|
|
3318
|
+
filesScanned,
|
|
3319
|
+
containersDispatched,
|
|
3320
|
+
computeSecondsUsed,
|
|
3321
|
+
durationMs,
|
|
3322
|
+
listingMs,
|
|
3323
|
+
grepMs
|
|
3324
|
+
};
|
|
3325
|
+
}
|
|
3326
|
+
exec(command) {
|
|
3327
|
+
const disks = {};
|
|
3328
|
+
for (const [name, entry] of this.mounts) disks[name] = entry.readOnly || entry.subdirectory || entry.conditional || entry.queueMs !== void 0 || entry.checkoutPaths !== void 0 ? {
|
|
3329
|
+
disk: entry.disk,
|
|
3330
|
+
subdirectory: entry.subdirectory,
|
|
3331
|
+
readOnly: entry.readOnly,
|
|
3332
|
+
conditional: entry.conditional,
|
|
3333
|
+
queueMs: entry.queueMs,
|
|
3334
|
+
checkoutPaths: entry.checkoutPaths
|
|
3335
|
+
} : entry.disk;
|
|
3336
|
+
return this.client.exec({
|
|
3337
|
+
disks,
|
|
3338
|
+
command
|
|
3339
|
+
});
|
|
3340
|
+
}
|
|
3341
|
+
};
|
|
3342
|
+
//#endregion
|
|
3343
|
+
//#region src/archil.ts
|
|
3344
|
+
/**
|
|
3345
|
+
* Read an environment variable in a way that is safe in browsers, where the
|
|
3346
|
+
* `process` global does not exist. Returns undefined when there is no process
|
|
3347
|
+
* environment, so the SDK can be bundled and run client-side as long as
|
|
3348
|
+
* credentials are passed explicitly to `new Archil({ ... })`.
|
|
3349
|
+
*/
|
|
3350
|
+
function envVar(name) {
|
|
3351
|
+
return typeof process !== "undefined" && process.env ? process.env[name] : void 0;
|
|
3352
|
+
}
|
|
3353
|
+
function isExecMountSpec(m) {
|
|
3354
|
+
return typeof m === "object" && m !== null && "disk" in m;
|
|
3355
|
+
}
|
|
3356
|
+
function diskIdFromMount(m) {
|
|
3357
|
+
return typeof m === "string" ? m : m.id;
|
|
3358
|
+
}
|
|
3359
|
+
var Archil = class {
|
|
3360
|
+
disks;
|
|
3361
|
+
images;
|
|
3362
|
+
sandboxes;
|
|
3363
|
+
tokens;
|
|
3364
|
+
/** @internal */
|
|
3365
|
+
_client;
|
|
3366
|
+
constructor(opts = {}) {
|
|
3367
|
+
const apiKey = opts.apiKey ?? envVar("ARCHIL_API_KEY");
|
|
3368
|
+
const region = opts.region ?? envVar("ARCHIL_REGION");
|
|
3369
|
+
if (!apiKey) throw new Error("Missing API key: pass apiKey in options or set ARCHIL_API_KEY environment variable");
|
|
3370
|
+
if (!region) throw new Error("Missing region: pass region in options or set ARCHIL_REGION environment variable");
|
|
3371
|
+
const controlBaseUrl = opts.baseUrl ?? resolveBaseUrl(region);
|
|
3372
|
+
const client = createApiClient({
|
|
3373
|
+
apiKey,
|
|
3374
|
+
region,
|
|
3375
|
+
baseUrl: controlBaseUrl,
|
|
3376
|
+
tls: opts.tls
|
|
3377
|
+
});
|
|
3378
|
+
const s3BaseUrl = opts.s3BaseUrl ?? envVar("ARCHIL_S3_BASE_URL") ?? deriveS3BaseUrl(controlBaseUrl);
|
|
3379
|
+
this._client = client;
|
|
3380
|
+
this.disks = new Disks(client, region, s3BaseUrl);
|
|
3381
|
+
this.images = new Images(client);
|
|
3382
|
+
this.sandboxes = new Sandboxes(client);
|
|
3383
|
+
this.tokens = new Tokens(client);
|
|
3384
|
+
}
|
|
3385
|
+
/**
|
|
3386
|
+
* Run a command in a container with multiple disks mounted simultaneously,
|
|
3387
|
+
* each at its own relative path under `/mnt/archil`. Blocks until the
|
|
3388
|
+
* command completes and returns its stdout, stderr, exit code, and timing.
|
|
3389
|
+
*/
|
|
3390
|
+
async exec(opts) {
|
|
3391
|
+
const disks = {};
|
|
3392
|
+
for (const [relPath, mount] of Object.entries(opts.disks)) if (isExecMountSpec(mount)) {
|
|
3393
|
+
const entry = {
|
|
3394
|
+
disk: diskIdFromMount(mount.disk),
|
|
3395
|
+
readOnly: mount.readOnly ?? false,
|
|
3396
|
+
conditional: mount.conditional ?? false
|
|
3397
|
+
};
|
|
3398
|
+
if (mount.subdirectory !== void 0) entry.subdirectory = mount.subdirectory;
|
|
3399
|
+
if (mount.queueMs !== void 0) entry.queueMs = mount.queueMs;
|
|
3400
|
+
if (mount.checkoutPaths !== void 0) entry.checkoutPaths = mount.checkoutPaths;
|
|
3401
|
+
disks[relPath] = entry;
|
|
3402
|
+
} else disks[relPath] = diskIdFromMount(mount);
|
|
3403
|
+
return unwrap(retryApiRequest(() => this._client.POST("/api/exec", { body: {
|
|
3404
|
+
...execVmBody(opts),
|
|
3405
|
+
disks,
|
|
3406
|
+
command: opts.command
|
|
3407
|
+
} }), "connect"));
|
|
3408
|
+
}
|
|
3409
|
+
/**
|
|
3410
|
+
* Build an agent filesystem toolset spanning several disks at once. `mounts`
|
|
3411
|
+
* maps a relative path to a disk (or `ExecMountSpec`), exactly like
|
|
3412
|
+
* {@link exec}; each disk appears under `/mnt/archil/<path>`. Hand the result
|
|
3413
|
+
* to a framework adapter (`createDiskTools(workspace)`) to get tools that route
|
|
3414
|
+
* file operations by path and fan `grep`/`list_files` out across the disks.
|
|
3415
|
+
*/
|
|
3416
|
+
workspace(mounts) {
|
|
3417
|
+
return new Workspace(this, mounts);
|
|
3418
|
+
}
|
|
3419
|
+
};
|
|
3420
|
+
//#endregion
|
|
3421
|
+
//#region src/index.ts
|
|
3422
|
+
let _options;
|
|
3423
|
+
let _instance;
|
|
3424
|
+
function configure(options) {
|
|
3425
|
+
_options = options;
|
|
3426
|
+
_instance = void 0;
|
|
3427
|
+
}
|
|
3428
|
+
function archil() {
|
|
3429
|
+
if (!_instance) _instance = new Archil(_options);
|
|
3430
|
+
return _instance;
|
|
3431
|
+
}
|
|
3432
|
+
function createDisk(req) {
|
|
3433
|
+
return archil().disks.create(req);
|
|
3434
|
+
}
|
|
3435
|
+
function listDisks(opts) {
|
|
3436
|
+
return archil().disks.list(opts);
|
|
3437
|
+
}
|
|
3438
|
+
function getDisk(id) {
|
|
3439
|
+
return archil().disks.get(id);
|
|
3440
|
+
}
|
|
3441
|
+
function createSandbox(req = {}, opts = {}) {
|
|
3442
|
+
return archil().sandboxes.create(req, opts);
|
|
3443
|
+
}
|
|
3444
|
+
function listSandboxes(opts) {
|
|
3445
|
+
return archil().sandboxes.list(opts);
|
|
3446
|
+
}
|
|
3447
|
+
function getSandbox(id) {
|
|
3448
|
+
return archil().sandboxes.get(id);
|
|
3449
|
+
}
|
|
3450
|
+
function listApiKeys(opts) {
|
|
3451
|
+
return archil().tokens.list(opts);
|
|
3452
|
+
}
|
|
3453
|
+
function createApiKey(req) {
|
|
3454
|
+
return archil().tokens.create(req);
|
|
3455
|
+
}
|
|
3456
|
+
function deleteApiKey(id) {
|
|
3457
|
+
return archil().tokens.delete(id);
|
|
3458
|
+
}
|
|
3459
|
+
/**
|
|
3460
|
+
* Run a command in a container with multiple disks mounted simultaneously,
|
|
3461
|
+
* each at its own relative path under `/mnt/archil`. Blocks until the
|
|
3462
|
+
* command completes and returns its stdout, stderr, exit code, and timing.
|
|
3463
|
+
*/
|
|
3464
|
+
function exec(opts) {
|
|
3465
|
+
return archil().exec(opts);
|
|
3466
|
+
}
|
|
3467
|
+
/**
|
|
3468
|
+
* Build an agent filesystem toolset spanning several disks, using the
|
|
3469
|
+
* module-level client. See {@link Archil.workspace}.
|
|
3470
|
+
*/
|
|
3471
|
+
function workspace(mounts) {
|
|
3472
|
+
return archil().workspace(mounts);
|
|
3473
|
+
}
|
|
3474
|
+
//#endregion
|
|
3475
|
+
exports.Archil = Archil;
|
|
3476
|
+
exports.ArchilApiError = ArchilApiError;
|
|
3477
|
+
exports.ArchilError = ArchilError;
|
|
3478
|
+
exports.ArchilS3Error = ArchilS3Error;
|
|
3479
|
+
exports.DESKTOP_IMAGE = require_sandbox_desktop.DESKTOP_IMAGE;
|
|
3480
|
+
exports.DESKTOP_MAX_TTL_SECONDS = require_sandbox_desktop.DESKTOP_MAX_TTL_SECONDS;
|
|
3481
|
+
exports.DESKTOP_MEMORY_MIB = require_sandbox_desktop.DESKTOP_MEMORY_MIB;
|
|
3482
|
+
exports.DESKTOP_PORT = require_sandbox_desktop.DESKTOP_PORT;
|
|
3483
|
+
exports.DESKTOP_VCPUS = require_sandbox_desktop.DESKTOP_VCPUS;
|
|
3484
|
+
exports.DesktopNotInstalledError = require_sandbox_desktop.DesktopNotInstalledError;
|
|
3485
|
+
exports.Disk = Disk;
|
|
3486
|
+
exports.DiskMultipart = DiskMultipart;
|
|
3487
|
+
exports.Disks = Disks;
|
|
3488
|
+
exports.ImageBuildError = ImageBuildError;
|
|
3489
|
+
exports.Images = Images;
|
|
3490
|
+
exports.Sandbox = Sandbox;
|
|
3491
|
+
exports.SandboxDesktop = require_sandbox_desktop.SandboxDesktop;
|
|
3492
|
+
exports.SandboxFileTransferError = SandboxFileTransferError;
|
|
3493
|
+
exports.SandboxFiles = SandboxFiles;
|
|
3494
|
+
exports.SandboxPauseError = SandboxPauseError;
|
|
3495
|
+
exports.SandboxProcess = SandboxProcess;
|
|
3496
|
+
exports.SandboxProcesses = SandboxProcesses;
|
|
3497
|
+
exports.Sandboxes = Sandboxes;
|
|
3498
|
+
exports.Tokens = Tokens;
|
|
3499
|
+
exports.USER_AGENT = USER_AGENT;
|
|
3500
|
+
exports.VERSION = VERSION;
|
|
3501
|
+
exports.Workspace = Workspace;
|
|
3502
|
+
exports.configure = configure;
|
|
3503
|
+
exports.createApiKey = createApiKey;
|
|
3504
|
+
exports.createDisk = createDisk;
|
|
3505
|
+
exports.createSandbox = createSandbox;
|
|
3506
|
+
exports.deleteApiKey = deleteApiKey;
|
|
3507
|
+
exports.desktopViewerPath = require_sandbox_desktop.desktopViewerPath;
|
|
3508
|
+
exports.effectiveUploadPartSize = effectiveUploadPartSize;
|
|
3509
|
+
exports.exec = exec;
|
|
3510
|
+
exports.getDisk = getDisk;
|
|
3511
|
+
exports.getSandbox = getSandbox;
|
|
3512
|
+
exports.listApiKeys = listApiKeys;
|
|
3513
|
+
exports.listDisks = listDisks;
|
|
3514
|
+
exports.listSandboxes = listSandboxes;
|
|
3515
|
+
exports.workspace = workspace;
|