-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsandboxes.ts
More file actions
456 lines (430 loc) · 14.8 KB
/
Copy pathsandboxes.ts
File metadata and controls
456 lines (430 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
import { OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_HEADERS } from "@/config/constants.js";
import { Leap0Error } from "@/core/errors.js";
import { normalize } from "@/core/normalize.js";
import {
createSnapshotParamsSchema,
createPresignedUrlParamsSchema,
createSandboxRuntimeParamsSchema,
listSandboxesParamsSchema,
objectStorageMountSchema,
objectStorageMountSummarySchema,
objectStorageMountUpdateSchema,
listSandboxesResponseSchema,
presignedUrlSchema,
sandboxDataSchema,
toObjectStorageMountsWire,
toObjectStorageMountUpdateWire,
toNetworkPolicyWire,
} from "@/models/sandbox.js";
import { snapshotDataSchema } from "@/models/snapshot.js";
import type {
CreatePresignedUrlParams,
CreateSandboxParams,
CreateSnapshotParams,
ListSandboxesParams,
ListSandboxesResponse,
ObjectStorageMount,
ObjectStorageMountSummary,
ObjectStorageMountUpdate,
PresignedUrl,
RequestOptions,
SandboxData,
SandboxRef,
SnapshotData,
} from "@/models/index.js";
import { Leap0Transport, jsonBody } from "@/core/transport.js";
import {
ensureLeadingSlash,
sandboxBaseUrl,
sandboxIdOf,
websocketUrlFromHttp,
} from "@/core/utils.js";
import { withErrorPrefix } from "@/services/shared.js";
function injectOtelEnv(
envVars: Record<string, string> | undefined,
enabled: boolean,
): Record<string, string> | undefined {
if (!enabled) {
return envVars;
}
const env: Record<string, string | undefined> =
typeof process !== "undefined" && process.env ? process.env : {};
const endpoint = env[OTEL_EXPORTER_OTLP_ENDPOINT]?.trim();
if (!endpoint) {
throw new Leap0Error(
`otelExport=true requires ${OTEL_EXPORTER_OTLP_ENDPOINT} in the local environment`,
);
}
const merged: Record<string, string> = {
[OTEL_EXPORTER_OTLP_ENDPOINT]: endpoint,
};
const headers = env[OTEL_EXPORTER_OTLP_HEADERS]?.trim();
if (headers) {
merged[OTEL_EXPORTER_OTLP_HEADERS] = headers;
}
if (envVars) {
Object.assign(merged, envVars);
}
return merged;
}
type SandboxFactory<T> = (data: SandboxData) => T;
/**
* Creates, fetches, pauses, and deletes sandboxes.
*
* @throws {Leap0Error} If request validation, API calls, or response validation fail.
*/
export class SandboxesClient<T = SandboxData> {
private readonly sandboxFactory?: SandboxFactory<T>;
constructor(transport: Leap0Transport);
constructor(transport: Leap0Transport, sandboxFactory: SandboxFactory<T>);
constructor(
private readonly transport: Leap0Transport,
sandboxFactory?: SandboxFactory<T>,
) {
this.sandboxFactory = sandboxFactory;
}
private wrap(data: SandboxData): T {
return (this.sandboxFactory ? this.sandboxFactory(data) : data) as T;
}
/**
* Creates a sandbox from a template and resource config.
*
* @param params Sandbox creation parameters.
* @param options Optional request settings such as timeout and query params.
* @returns The created sandbox resource.
* @throws {Leap0Error} If params are invalid, local OTEL env is missing, or sandbox creation fails.
*
* @example
* ```ts
* const sandbox = await client.sandboxes.create({
* templateName: "base",
* timeout: 1800,
* });
* ```
*/
async create(params: CreateSandboxParams = {}, options: RequestOptions = {}): Promise<T> {
const parsedParams = createSandboxRuntimeParamsSchema.safeParse(params);
if (!parsedParams.success) {
throw new Leap0Error(parsedParams.error.issues[0]?.message ?? "Invalid sandbox parameters");
}
const normalizedParams = parsedParams.data;
const effectiveOtelExport = normalizedParams.otelExport ?? Boolean(normalizedParams.telemetry);
const payload = {
template_name: normalizedParams.templateName,
vcpu: normalizedParams.vcpu,
memory: normalizedParams.memory,
timeout: normalizedParams.timeout,
auto_pause: normalizedParams.autoPause ?? false,
env_vars: injectOtelEnv(normalizedParams.envVars, effectiveOtelExport),
network_policy: toNetworkPolicyWire(normalizedParams.networkPolicy),
mounts: toObjectStorageMountsWire(normalizedParams.mounts),
};
return withErrorPrefix("Failed to create sandbox: ", async () => {
const data = await this.transport.requestJson<unknown>(
"/v1/sandbox",
{ method: "POST", body: jsonBody(payload) },
options,
);
return this.wrap(normalize(sandboxDataSchema, data));
});
}
/**
* Lists sandboxes for the authenticated organization.
*
* @param params Optional filter, sort, and pagination parameters.
* @param options Optional request settings such as timeout and headers.
* @returns Paginated sandbox summaries.
*/
async list(
params: ListSandboxesParams = {},
options: RequestOptions = {},
): Promise<ListSandboxesResponse> {
return withErrorPrefix("Failed to list sandboxes: ", async () => {
const parsed = listSandboxesParamsSchema.parse(params);
const data = await this.transport.requestJson<unknown>(
"/v1/sandboxes",
{ method: "GET" },
{
...options,
query: {
...options.query,
state: parsed.state,
sort: parsed.sort,
"order-by": parsed.orderBy,
page: parsed.page,
"page-size": parsed.pageSize,
},
},
);
return normalize(listSandboxesResponseSchema, data);
});
}
/**
* Pauses a running sandbox.
*
* @param sandbox Sandbox ID or sandbox-like object.
* @param options Optional request settings such as timeout and query params.
* @returns The updated sandbox resource.
*/
async pause(sandbox: SandboxRef, options: RequestOptions = {}): Promise<T> {
return withErrorPrefix("Failed to pause sandbox: ", async () => {
const data = await this.transport.requestJson<unknown>(
`/v1/sandbox/${sandboxIdOf(sandbox)}/pause`,
{ method: "POST" },
options,
);
return this.wrap(normalize(sandboxDataSchema, data));
});
}
/**
* Creates a snapshot from a running sandbox.
*
* @param sandbox Sandbox ID or sandbox-like object.
* @param params Optional snapshot naming parameters.
* @param options Optional request settings such as timeout and query params.
* @returns The created snapshot resource.
*/
async createSnapshot(
sandbox: SandboxRef,
params: CreateSnapshotParams = {},
options: RequestOptions = {},
): Promise<SnapshotData> {
const parsedParams = createSnapshotParamsSchema.safeParse(params);
if (!parsedParams.success) {
throw new Leap0Error(parsedParams.error.issues[0]?.message ?? "Invalid snapshot parameters");
}
return withErrorPrefix("Failed to create snapshot: ", async () => {
const parsed = parsedParams.data;
const data = await this.transport.requestJson<unknown>(
`/v1/sandbox/${sandboxIdOf(sandbox)}/snapshot/create`,
{
method: "POST",
body: jsonBody({
name: parsed.name,
kill_sandbox_after: parsed.killSandboxAfter,
}),
},
options,
);
return normalize(snapshotDataSchema, data);
});
}
/**
* Fetches a sandbox by ID.
*
* @param sandbox Sandbox ID or sandbox-like object.
* @param options Optional request settings such as timeout and query params.
* @returns The current sandbox resource.
*/
async get(sandbox: SandboxRef, options: RequestOptions = {}): Promise<T> {
return withErrorPrefix("Failed to get sandbox: ", async () => {
const data = await this.transport.requestJson<unknown>(
`/v1/sandbox/${sandboxIdOf(sandbox)}/`,
{ method: "GET" },
options,
);
return this.wrap(normalize(sandboxDataSchema, data));
});
}
/**
* Deletes a sandbox by ID.
*
* @param sandbox Sandbox ID or sandbox-like object.
* @param options Optional request settings such as timeout and query params.
*/
async delete(sandbox: SandboxRef, options: RequestOptions = {}): Promise<void> {
await withErrorPrefix("Failed to delete sandbox: ", () =>
this.transport.request(`/v1/sandbox/${sandboxIdOf(sandbox)}/`, { method: "DELETE" }, options),
);
}
/**
* Adds an object storage mount to a running sandbox.
*
* @param sandbox Sandbox ID or sandbox-like object.
* @param mount Object storage mount configuration.
* @param options Optional request settings such as timeout and query params.
* @returns The created mount summary.
*/
async addMount(
sandbox: SandboxRef,
mount: ObjectStorageMount,
options: RequestOptions = {},
): Promise<ObjectStorageMountSummary> {
const parsedMount = objectStorageMountSchema.parse(mount);
return withErrorPrefix("Failed to add sandbox mount: ", async () => {
const data = await this.transport.requestJson<unknown>(
`/v1/sandbox/${sandboxIdOf(sandbox)}/mounts`,
{ method: "POST", body: jsonBody(toObjectStorageMountsWire([parsedMount])?.[0]) },
options,
);
return normalize(objectStorageMountSummarySchema, data);
});
}
/**
* Updates an existing object storage mount on a sandbox.
*
* @param sandbox Sandbox ID or sandbox-like object.
* @param mountID Mount identifier.
* @param mount Partial mount update payload.
* @param options Optional request settings such as timeout and query params.
* @returns The updated mount summary.
*/
async updateMount(
sandbox: SandboxRef,
mountID: string,
mount: ObjectStorageMountUpdate,
options: RequestOptions = {},
): Promise<ObjectStorageMountSummary> {
const trimmedMountID = mountID.trim();
if (!trimmedMountID) {
throw new Leap0Error("mountID must be a non-empty string");
}
const parsedMount = objectStorageMountUpdateSchema.parse(mount);
return withErrorPrefix("Failed to update sandbox mount: ", async () => {
const data = await this.transport.requestJson<unknown>(
`/v1/sandbox/${sandboxIdOf(sandbox)}/mounts/${trimmedMountID}`,
{ method: "PATCH", body: jsonBody(toObjectStorageMountUpdateWire(parsedMount)) },
options,
);
return normalize(objectStorageMountSummarySchema, data);
});
}
/**
* Deletes an object storage mount from a sandbox.
*
* @param sandbox Sandbox ID or sandbox-like object.
* @param mountID Mount identifier.
* @param options Optional request settings such as timeout and query params.
*/
async deleteMount(
sandbox: SandboxRef,
mountID: string,
options: RequestOptions = {},
): Promise<void> {
const trimmedMountID = mountID.trim();
if (!trimmedMountID) {
throw new Leap0Error("mountID must be a non-empty string");
}
await withErrorPrefix("Failed to delete sandbox mount: ", () =>
this.transport.request(
`/v1/sandbox/${sandboxIdOf(sandbox)}/mounts/${trimmedMountID}`,
{ method: "DELETE" },
options,
),
);
}
/**
* Fetches the resolved home directory for the sandbox user.
*
* @param sandbox Sandbox ID or sandbox-like object.
* @param options Optional request settings such as timeout and query params.
* @returns The resolved sandbox user home directory.
*/
async getUserHomeDir(sandbox: SandboxRef, options: RequestOptions = {}): Promise<string> {
return withErrorPrefix("Failed to get sandbox user home directory: ", async () => {
const data = await this.transport.requestJson<unknown>(
`/v1/sandbox/${sandboxIdOf(sandbox)}/system/user-home-dir`,
{ method: "GET" },
options,
);
if (
typeof data !== "object" ||
data === null ||
typeof (data as { user_home_dir?: unknown }).user_home_dir !== "string"
) {
throw new Leap0Error("Sandbox user home directory response missing user_home_dir");
}
return (data as { user_home_dir: string }).user_home_dir;
});
}
/**
* Fetches the configured working directory for the sandbox.
*
* @param sandbox Sandbox ID or sandbox-like object.
* @param options Optional request settings such as timeout and query params.
* @returns The configured sandbox workdir.
*/
async getWorkdir(sandbox: SandboxRef, options: RequestOptions = {}): Promise<string> {
return withErrorPrefix("Failed to get sandbox workdir: ", async () => {
const data = await this.transport.requestJson<unknown>(
`/v1/sandbox/${sandboxIdOf(sandbox)}/system/workdir`,
{ method: "GET" },
options,
);
if (
typeof data !== "object" ||
data === null ||
typeof (data as { workdir?: unknown }).workdir !== "string"
) {
throw new Leap0Error("Sandbox workdir response missing workdir");
}
return (data as { workdir: string }).workdir;
});
}
/**
* Creates a temporary public URL for a specific sandbox port.
*/
async createPresignedUrl(
sandbox: SandboxRef,
params: CreatePresignedUrlParams,
options: RequestOptions = {},
): Promise<PresignedUrl> {
const parsed = createPresignedUrlParamsSchema.parse(params);
return withErrorPrefix("Failed to create presigned URL: ", async () => {
const data = await this.transport.requestJson<unknown>(
`/v1/sandbox/${sandboxIdOf(sandbox)}/presigned-url`,
{
method: "POST",
body: jsonBody({
port: parsed.port,
expires_in: parsed.expiresIn,
}),
},
options,
);
return normalize(presignedUrlSchema, data);
});
}
/**
* Deletes a previously issued presigned URL.
*/
async deletePresignedUrl(
sandbox: SandboxRef,
id: string,
options: RequestOptions = {},
): Promise<void> {
const trimmedID = id.trim();
if (!trimmedID) {
throw new Leap0Error("id must be a non-empty string");
}
await withErrorPrefix("Failed to delete presigned URL: ", () =>
this.transport.request(
`/v1/sandbox/${sandboxIdOf(sandbox)}/presigned-url/${trimmedID}`,
{ method: "DELETE" },
options,
),
);
}
/**
* Builds the public invoke URL for a sandbox.
*
* @param sandbox Sandbox ID or sandbox-like object.
* @param path Route path to append to the sandbox base URL.
* @param port Optional forwarded port.
* @returns The public HTTPS URL for the sandbox.
*/
invokeUrl(sandbox: SandboxRef, path = "/", port?: number): string {
return `${sandboxBaseUrl(sandboxIdOf(sandbox), this.transport.sandboxDomain, port)}${ensureLeadingSlash(path)}`;
}
/**
* Builds the public websocket URL for a sandbox.
*
* @param sandbox Sandbox ID or sandbox-like object.
* @param path Route path to append to the sandbox base URL.
* @param port Optional forwarded port.
* @returns The public websocket URL for the sandbox.
*/
websocketUrl(sandbox: SandboxRef, path = "/", port?: number): string {
return websocketUrlFromHttp(this.invokeUrl(sandbox, path, port));
}
}