forked from vercel/sandbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-client.ts
More file actions
800 lines (740 loc) · 20.4 KB
/
api-client.ts
File metadata and controls
800 lines (740 loc) · 20.4 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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
import {
BaseClient,
parseOrThrow,
type Parsed,
type RequestParams,
} from "./base-client.js";
import {
CommandFinishedData,
SandboxAndRoutesResponse,
SandboxResponse,
CommandResponse,
CommandFinishedResponse,
EmptyResponse,
LogLine,
LogLineStdout,
LogLineStderr,
SandboxesResponse,
SnapshotsResponse,
ExtendTimeoutResponse,
UpdateNetworkPolicyResponse,
SnapshotResponse,
CreateSnapshotResponse,
type CommandData,
} from "./validators.js";
import { APIError, StreamError } from "./api-error.js";
import { FileWriter } from "./file-writer.js";
import { VERSION } from "../version.js";
import { consumeReadable } from "../utils/consume-readable.js";
import { z } from "zod";
import jsonlines from "jsonlines";
import os from "os";
import { Readable } from "stream";
import { normalizePath } from "../utils/normalizePath.js";
import { getVercelOidcToken } from "@vercel/oidc";
import { NetworkPolicy } from "../network-policy.js";
import {
toAPINetworkPolicy,
fromAPINetworkPolicy,
} from "../utils/network-policy.js";
import { getPrivateParams, WithPrivate } from "../utils/types.js";
import { RUNTIMES } from "../constants.js";
import { setTimeout } from "node:timers/promises";
interface Claims {
owner_id: string;
project_id?: string;
}
function decodeUnverifiedToken(token: string): Claims | null {
if (token.split(".").length !== 3) {
return null;
}
try {
const payload = JSON.parse(
Buffer.from(token.split(".")[1], "base64url").toString("utf8"),
);
if (payload.owner_id) {
return { owner_id: payload.owner_id, project_id: payload.project_id };
}
return null;
} catch {
return null;
}
}
export interface WithFetchOptions {
fetch?: typeof globalThis.fetch;
}
export class APIClient extends BaseClient {
private teamId: string;
private projectId: string | undefined;
private isJwtToken: boolean;
constructor(params: {
baseUrl?: string;
teamId: string;
token: string;
fetch?: typeof globalThis.fetch;
}) {
super({
baseUrl: params.baseUrl ?? "https://vercel.com/api",
token: params.token,
debug: false,
fetch: params.fetch,
});
this.teamId = params.teamId;
this.isJwtToken = false;
const claims = decodeUnverifiedToken(params.token);
if (claims) {
this.isJwtToken = true;
this.projectId = claims.project_id;
this.teamId = claims.owner_id;
}
}
private async ensureValidToken(): Promise<void> {
if (!this.isJwtToken) {
return;
}
try {
// Use getVercelOidcToken to refresh the token with team/project scope
const freshToken = await getVercelOidcToken({
expirationBufferMs: 5 * 60 * 1000, // 5 minutes
team: this.teamId,
project: this.projectId,
});
// Update token if it changed
if (freshToken !== this.token) {
this.token = freshToken;
const claims = decodeUnverifiedToken(freshToken);
if (claims) {
this.teamId = claims.owner_id;
}
}
} catch {
// Ignore refresh errors and continue with current token
}
}
protected async request(path: string, params?: RequestParams) {
await this.ensureValidToken();
return super.request(path, {
...params,
query: { teamId: this.teamId, ...params?.query },
headers: {
"content-type": "application/json",
"user-agent": `vercel/sandbox/${VERSION} (Node.js/${process.version}; ${os.platform()}/${os.arch()})`,
...params?.headers,
},
});
}
async getSandbox(
params: WithPrivate<{ sandboxId: string; signal?: AbortSignal }>,
) {
const privateParams = getPrivateParams(params);
let querystring = new URLSearchParams(privateParams).toString();
querystring = querystring ? `?${querystring}` : "";
return parseOrThrow(
SandboxAndRoutesResponse,
await this.request(`/v1/sandboxes/${params.sandboxId}${querystring}`, {
signal: params.signal,
}),
);
}
async createSandbox(
params: WithPrivate<{
ports?: number[];
projectId: string;
source?:
| {
type: "git";
url: string;
depth?: number;
revision?: string;
username?: string;
password?: string;
}
| { type: "tarball"; url: string }
| { type: "snapshot"; snapshotId: string };
timeout?: number;
resources?: { vcpus: number };
runtime?: RUNTIMES | (string & {});
networkPolicy?: NetworkPolicy;
env?: Record<string, string>;
signal?: AbortSignal;
}>,
) {
const privateParams = getPrivateParams(params);
return parseOrThrow(
SandboxAndRoutesResponse,
await this.request("/v1/sandboxes", {
method: "POST",
body: JSON.stringify({
projectId: params.projectId,
ports: params.ports,
source: params.source,
timeout: params.timeout,
resources: params.resources,
runtime: params.runtime,
networkPolicy: params.networkPolicy
? toAPINetworkPolicy(params.networkPolicy)
: undefined,
env: params.env,
...privateParams,
}),
signal: params.signal,
}),
);
}
async runCommand(params: {
sandboxId: string;
cwd?: string;
command: string;
args: string[];
env: Record<string, string>;
sudo: boolean;
wait: true;
signal?: AbortSignal;
}): Promise<{ command: CommandData; finished: Promise<CommandFinishedData> }>;
async runCommand(params: {
sandboxId: string;
cwd?: string;
command: string;
args: string[];
env: Record<string, string>;
sudo: boolean;
wait?: false;
signal?: AbortSignal;
}): Promise<Parsed<z.infer<typeof CommandResponse>>>;
async runCommand(params: {
sandboxId: string;
cwd?: string;
command: string;
args: string[];
env: Record<string, string>;
sudo: boolean;
wait?: boolean;
signal?: AbortSignal;
}) {
if (params.wait) {
const response = await this.request(
`/v1/sandboxes/${params.sandboxId}/cmd`,
{
method: "POST",
body: JSON.stringify({
command: params.command,
args: params.args,
cwd: params.cwd,
env: params.env,
sudo: params.sudo,
wait: true,
}),
signal: params.signal,
},
);
if (!response.ok) {
await parseOrThrow(z.any(), response);
}
if (response.headers.get("content-type") !== "application/x-ndjson") {
throw new APIError(response, {
message: "Expected a stream of command data",
sandboxId: params.sandboxId,
});
}
if (response.body === null) {
throw new APIError(response, {
message: "No response body",
sandboxId: params.sandboxId,
});
}
const jsonlinesStream = jsonlines.parse();
pipe(response.body, jsonlinesStream, { signal: params.signal }).catch(
(err) => {
console.error("Error piping command stream:", err);
},
);
const iterator = jsonlinesStream[Symbol.asyncIterator]();
const commandChunk = await iterator.next();
if (commandChunk.done) {
throw new StreamError(
"stream_ended_early",
"Stream ended before command data was received",
params.sandboxId,
);
}
const { command } = CommandResponse.parse(commandChunk.value);
const finished = (async () => {
const finishedChunk = await iterator.next();
if (finishedChunk.done) {
throw new StreamError(
"stream_ended_early",
"Stream ended before command finished",
params.sandboxId,
);
}
const { command } = CommandFinishedResponse.parse(finishedChunk.value);
return command;
})();
return { command, finished };
}
return parseOrThrow(
CommandResponse,
await this.request(`/v1/sandboxes/${params.sandboxId}/cmd`, {
method: "POST",
body: JSON.stringify({
command: params.command,
args: params.args,
cwd: params.cwd,
env: params.env,
sudo: params.sudo,
}),
signal: params.signal,
}),
);
}
async getCommand(params: {
sandboxId: string;
cmdId: string;
wait: true;
signal?: AbortSignal;
}): Promise<Parsed<z.infer<typeof CommandFinishedResponse>>>;
async getCommand(params: {
sandboxId: string;
cmdId: string;
wait?: boolean;
signal?: AbortSignal;
}): Promise<Parsed<z.infer<typeof CommandResponse>>>;
async getCommand(params: {
sandboxId: string;
cmdId: string;
wait?: boolean;
signal?: AbortSignal;
}) {
return params.wait
? parseOrThrow(
CommandFinishedResponse,
await this.request(
`/v1/sandboxes/${params.sandboxId}/cmd/${params.cmdId}`,
{ signal: params.signal, query: { wait: "true" } },
),
)
: parseOrThrow(
CommandResponse,
await this.request(
`/v1/sandboxes/${params.sandboxId}/cmd/${params.cmdId}`,
{ signal: params.signal },
),
);
}
async mkDir(params: {
sandboxId: string;
path: string;
cwd?: string;
signal?: AbortSignal;
}) {
return parseOrThrow(
EmptyResponse,
await this.request(`/v1/sandboxes/${params.sandboxId}/fs/mkdir`, {
method: "POST",
body: JSON.stringify({ path: params.path, cwd: params.cwd }),
signal: params.signal,
}),
);
}
getFileWriter(params: {
sandboxId: string;
extractDir: string;
signal?: AbortSignal;
}) {
const writer = new FileWriter();
return {
response: (async () => {
return this.request(`/v1/sandboxes/${params.sandboxId}/fs/write`, {
method: "POST",
headers: {
"content-type": "application/gzip",
"x-cwd": params.extractDir,
},
body: await consumeReadable(writer.readable),
signal: params.signal,
});
})(),
writer,
};
}
async listSandboxes(params: {
/**
* The ID or name of the project to which the sandboxes belong.
* @example "my-project"
*/
projectId: string;
/**
* Maximum number of sandboxes to list from a request.
* @example 10
*/
limit?: number;
/**
* Get sandboxes created after this JavaScript timestamp.
* @example 1540095775941
*/
since?: number | Date;
/**
* Get sandboxes created before this JavaScript timestamp.
* @example 1540095775951
*/
until?: number | Date;
signal?: AbortSignal;
}) {
return parseOrThrow(
SandboxesResponse,
await this.request(`/v1/sandboxes`, {
query: {
project: params.projectId,
limit: params.limit,
since:
typeof params.since === "number"
? params.since
: params.since?.getTime(),
until:
typeof params.until === "number"
? params.until
: params.until?.getTime(),
},
method: "GET",
signal: params.signal,
}),
);
}
async listSnapshots(params: {
/**
* The ID or name of the project to which the snapshots belong.
* @example "my-project"
*/
projectId: string;
/**
* Maximum number of snapshots to list from a request.
* @example 10
*/
limit?: number;
/**
* Get snapshots created after this JavaScript timestamp.
* @example 1540095775941
*/
since?: number | Date;
/**
* Get snapshots created before this JavaScript timestamp.
* @example 1540095775951
*/
until?: number | Date;
signal?: AbortSignal;
}) {
return parseOrThrow(
SnapshotsResponse,
await this.request(`/v1/sandboxes/snapshots`, {
query: {
project: params.projectId,
limit: params.limit,
since:
typeof params.since === "number"
? params.since
: params.since?.getTime(),
until:
typeof params.until === "number"
? params.until
: params.until?.getTime(),
},
method: "GET",
signal: params.signal,
}),
);
}
async writeFiles(params: {
sandboxId: string;
cwd: string;
files: {
path: string;
content: string | Uint8Array;
mode?: number;
}[];
extractDir: string;
signal?: AbortSignal;
}) {
const { writer, response } = this.getFileWriter({
sandboxId: params.sandboxId,
extractDir: params.extractDir,
signal: params.signal,
});
for (const file of params.files) {
await writer.addFile({
name: normalizePath({
filePath: file.path,
extractDir: params.extractDir,
cwd: params.cwd,
}),
content: file.content,
mode: file.mode,
});
}
writer.end();
await parseOrThrow(EmptyResponse, await response);
}
async readFile(params: {
sandboxId: string;
path: string;
cwd?: string;
signal?: AbortSignal;
}): Promise<Readable | null> {
const response = await this.request(
`/v1/sandboxes/${params.sandboxId}/fs/read`,
{
method: "POST",
body: JSON.stringify({ path: params.path, cwd: params.cwd }),
signal: params.signal,
},
);
if (response.status === 404) {
return null;
}
if (response.body === null) {
return null;
}
return Readable.fromWeb(response.body);
}
async killCommand(params: {
sandboxId: string;
commandId: string;
signal: number;
abortSignal?: AbortSignal;
}) {
return parseOrThrow(
CommandResponse,
await this.request(
`/v1/sandboxes/${params.sandboxId}/${params.commandId}/kill`,
{
method: "POST",
body: JSON.stringify({ signal: params.signal }),
signal: params.abortSignal,
},
),
);
}
getLogs(params: {
sandboxId: string;
cmdId: string;
signal?: AbortSignal;
}): AsyncGenerator<
z.infer<typeof LogLineStdout> | z.infer<typeof LogLineStderr>,
void,
void
> &
Disposable & { close(): void } {
const self = this;
const disposer = new AbortController();
const signal = !params.signal
? disposer.signal
: mergeSignals(params.signal, disposer.signal);
const generator = (async function* () {
const url = `/v1/sandboxes/${params.sandboxId}/cmd/${params.cmdId}/logs`;
const response = await self.request(url, {
method: "GET",
signal,
});
if (!response.ok) {
await parseOrThrow(z.any(), response);
}
if (response.headers.get("content-type") !== "application/x-ndjson") {
throw new APIError(response, {
message: "Expected a stream of logs",
sandboxId: params.sandboxId,
});
}
if (response.body === null) {
throw new APIError(response, {
message: "No response body",
sandboxId: params.sandboxId,
});
}
const jsonlinesStream = jsonlines.parse();
pipe(response.body, jsonlinesStream, { signal }).catch((err) => {
console.error("Error piping logs:", err);
});
for await (const chunk of jsonlinesStream) {
const parsed = LogLine.parse(chunk);
if (parsed.stream === "error") {
throw new StreamError(
parsed.data.code,
parsed.data.message,
params.sandboxId,
);
}
yield parsed;
}
})();
return Object.assign(generator, {
[Symbol.dispose]() {
disposer.abort("Disposed");
},
close: () => disposer.abort("Disposed"),
});
}
async stopSandbox(params: {
sandboxId: string;
signal?: AbortSignal;
blocking?: boolean;
}): Promise<Parsed<z.infer<typeof SandboxResponse>>> {
const url = `/v1/sandboxes/${params.sandboxId}/stop`;
const response = await parseOrThrow(
SandboxResponse,
await this.request(url, { method: "POST", signal: params.signal }),
);
if (params.blocking) {
let sandbox = response.json.sandbox;
while (
sandbox.status !== "stopped" &&
sandbox.status !== "failed" &&
sandbox.status !== "aborted"
) {
await setTimeout(500, undefined, { signal: params.signal });
const poll = await this.getSandbox({
sandboxId: params.sandboxId,
signal: params.signal,
});
sandbox = poll.json.sandbox;
response.json.sandbox = sandbox;
}
}
return response;
}
async updateNetworkPolicy(params: {
sandboxId: string;
networkPolicy: NetworkPolicy;
signal?: AbortSignal;
}): Promise<Parsed<z.infer<typeof UpdateNetworkPolicyResponse>>> {
const url = `/v1/sandboxes/${params.sandboxId}/network-policy`;
return parseOrThrow(
UpdateNetworkPolicyResponse,
await this.request(url, {
method: "POST",
body: JSON.stringify(toAPINetworkPolicy(params.networkPolicy)),
signal: params.signal,
}),
);
}
async extendTimeout(params: {
sandboxId: string;
duration: number;
signal?: AbortSignal;
}): Promise<Parsed<z.infer<typeof ExtendTimeoutResponse>>> {
const url = `/v1/sandboxes/${params.sandboxId}/extend-timeout`;
return parseOrThrow(
ExtendTimeoutResponse,
await this.request(url, {
method: "POST",
body: JSON.stringify({ duration: params.duration }),
signal: params.signal,
}),
);
}
async createSnapshot(params: {
sandboxId: string;
expiration?: number;
signal?: AbortSignal;
}): Promise<Parsed<z.infer<typeof CreateSnapshotResponse>>> {
const url = `/v1/sandboxes/${params.sandboxId}/snapshot`;
const body =
params.expiration === undefined
? undefined
: JSON.stringify({ expiration: params.expiration });
return parseOrThrow(
CreateSnapshotResponse,
await this.request(url, {
method: "POST",
body,
signal: params.signal,
}),
);
}
async deleteSnapshot(params: {
snapshotId: string;
signal?: AbortSignal;
}): Promise<Parsed<z.infer<typeof SnapshotResponse>>> {
const url = `/v1/sandboxes/snapshots/${params.snapshotId}`;
return parseOrThrow(
SnapshotResponse,
await this.request(url, { method: "DELETE", signal: params.signal }),
);
}
async getSnapshot(params: {
snapshotId: string;
signal?: AbortSignal;
}): Promise<Parsed<z.infer<typeof SnapshotResponse>>> {
const url = `/v1/sandboxes/snapshots/${params.snapshotId}`;
return parseOrThrow(
SnapshotResponse,
await this.request(url, { signal: params.signal }),
);
}
}
async function pipe(
readable: ReadableStream<Uint8Array>,
output: NodeJS.WritableStream,
options?: { signal?: AbortSignal },
) {
const reader = readable.getReader();
let aborted = false;
const signal = options?.signal;
const onAbort = () => {
aborted = true;
const reason =
signal?.reason ??
new DOMException("The operation was aborted.", "AbortError");
void reader.cancel(reason).catch(() => {
// ignore cancel errors when aborting
});
if ("destroy" in output && typeof output.destroy === "function") {
output.destroy(reason as Error);
return;
}
output.emit("error", reason);
output.end();
};
if (signal) {
if (signal.aborted) {
onAbort();
} else {
signal.addEventListener("abort", onAbort, { once: true });
}
}
try {
while (true) {
const read = await reader.read();
if (read.value) {
output.write(Buffer.from(read.value));
}
if (read.done) {
break;
}
}
} catch (err) {
if (!aborted) {
output.emit("error", err);
}
} finally {
signal?.removeEventListener("abort", onAbort);
if (!aborted) {
output.end();
}
}
}
function mergeSignals(...signals: [AbortSignal, ...AbortSignal[]]) {
const controller = new AbortController();
const onAbort = () => {
controller.abort();
for (const signal of signals) {
signal.removeEventListener("abort", onAbort);
}
};
for (const signal of signals) {
if (signal.aborted) {
controller.abort();
break;
}
signal.addEventListener("abort", onAbort);
}
return controller.signal;
}