@sistemo/sdk 0.1.2 → 0.1.3
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 +6 -2
- package/dist/index.d.ts +25 -3
- package/dist/index.js +99 -22
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -49,7 +49,8 @@ Or pass them explicitly: `Sandbox.create({ apiKey: "sk_live_…", baseUrl: "http
|
|
|
49
49
|
|
|
50
50
|
```ts
|
|
51
51
|
const sb = await Sandbox.create({ vcpus: 1, memoryMb: 1024, stack: "base" });
|
|
52
|
-
const res = await sb.run("echo hi && uname -a"); // -> { exitCode, stdout, stderr, truncated } (default 120s, max 24h)
|
|
52
|
+
const res = await sb.run("echo hi && uname -a"); // -> { exitCode, stdout, stderr, truncated, requestId } (default 120s, max 24h)
|
|
53
|
+
await sb.run("node app.js", 120, { env: { FOO: "bar" }, cwd: "/tmp" });
|
|
53
54
|
await sb.close(); // destroy
|
|
54
55
|
```
|
|
55
56
|
|
|
@@ -69,7 +70,7 @@ try {
|
|
|
69
70
|
// quota refusal does once you free the resource it names.
|
|
70
71
|
if (e instanceof QuotaExceededError) { console.log(e.detail); }
|
|
71
72
|
else if (e instanceof AuthError) { /* 401/403 — key invalid or read-only */ }
|
|
72
|
-
else if (e instanceof APIError) { console.log(e.status, e.detail, e.code); }
|
|
73
|
+
else if (e instanceof APIError) { console.log(e.status, e.detail, e.code, e.requestId); }
|
|
73
74
|
}
|
|
74
75
|
```
|
|
75
76
|
|
|
@@ -77,6 +78,9 @@ try {
|
|
|
77
78
|
dimension bound and how much is in use, and `GET /v1/quotas` reports every limit
|
|
78
79
|
alongside current usage.
|
|
79
80
|
|
|
81
|
+
Every request sends `X-Request-Id`. Quote `e.requestId` when you contact support.
|
|
82
|
+
On `429`, the client honours `Retry-After` (capped at 60 s) from version 0.1.3.
|
|
83
|
+
|
|
80
84
|
Apache-2.0.
|
|
81
85
|
|
|
82
86
|
## Long-running commands
|
package/dist/index.d.ts
CHANGED
|
@@ -24,13 +24,20 @@ export declare class APIError extends SistemoError {
|
|
|
24
24
|
* that away would leave it unaddressable.
|
|
25
25
|
*/
|
|
26
26
|
readonly body: Record<string, unknown>;
|
|
27
|
-
|
|
27
|
+
/** Seconds from `Retry-After`, capped at 60. */
|
|
28
|
+
readonly retryAfter?: number;
|
|
29
|
+
private readonly explicitRequestId?;
|
|
30
|
+
constructor(status: number, detail: string, code?: string, body?: Record<string, unknown>, extra?: {
|
|
31
|
+
retryAfter?: number;
|
|
32
|
+
requestId?: string;
|
|
33
|
+
});
|
|
34
|
+
get requestId(): string | undefined;
|
|
28
35
|
}
|
|
29
36
|
/** 401/403 — key missing, invalid, revoked, or a read-only key on a mutation. */
|
|
30
37
|
export declare class AuthError extends APIError {
|
|
31
38
|
}
|
|
32
39
|
/**
|
|
33
|
-
* 403 `quota_exceeded` — an account limit
|
|
40
|
+
* 403 `quota_exceeded` — this request would exceed an account limit.
|
|
34
41
|
*
|
|
35
42
|
* Deliberately NOT an `AuthError`, even though both arrive as 403. They need
|
|
36
43
|
* opposite handling, and conflating them sends callers to the wrong place:
|
|
@@ -87,6 +94,13 @@ export declare class AsyncExecUnsupportedError extends APIError {
|
|
|
87
94
|
export declare class ExecStartUnconfirmed extends APIError {
|
|
88
95
|
get execId(): string;
|
|
89
96
|
}
|
|
97
|
+
/** Seconds from a Retry-After header (delta-seconds or HTTP-date), capped at 60. */
|
|
98
|
+
export declare function parseRetryAfter(value: string | null | undefined): number | undefined;
|
|
99
|
+
/** Milliseconds to wait before the next attempt. Tests pass `rand` so they do not sleep. */
|
|
100
|
+
export declare function retryDelayMs(attempt: number, backoffMs: number, maxBackoffMs: number, err?: {
|
|
101
|
+
status: number;
|
|
102
|
+
retryAfter?: number;
|
|
103
|
+
}, rand?: () => number): number;
|
|
90
104
|
export interface ClientOptions {
|
|
91
105
|
apiKey?: string;
|
|
92
106
|
baseUrl?: string;
|
|
@@ -109,6 +123,7 @@ export interface RequestOptions {
|
|
|
109
123
|
/** Low-level API client. Most users want {@link Sandbox} instead. */
|
|
110
124
|
export declare class Client {
|
|
111
125
|
readonly baseUrl: string;
|
|
126
|
+
lastRequestId?: string;
|
|
112
127
|
private readonly apiKey;
|
|
113
128
|
private readonly timeoutMs;
|
|
114
129
|
private readonly maxRetries;
|
|
@@ -154,6 +169,7 @@ export interface ExecResult {
|
|
|
154
169
|
stdout: string;
|
|
155
170
|
stderr: string;
|
|
156
171
|
truncated?: boolean;
|
|
172
|
+
requestId?: string;
|
|
157
173
|
}
|
|
158
174
|
export interface SandboxOptions extends ClientOptions {
|
|
159
175
|
client?: Client;
|
|
@@ -183,7 +199,10 @@ export declare class Sandbox {
|
|
|
183
199
|
* This is start + wait on a guest job (`POST /execs`). Default timeout 120s,
|
|
184
200
|
* ceiling 24 hours. A proxy never holds the connection for the whole command.
|
|
185
201
|
*/
|
|
186
|
-
run(script: string, timeoutSec?: number
|
|
202
|
+
run(script: string, timeoutSec?: number, opts?: {
|
|
203
|
+
env?: Record<string, string>;
|
|
204
|
+
cwd?: string;
|
|
205
|
+
}): Promise<ExecResult>;
|
|
187
206
|
/**
|
|
188
207
|
* Start a command and return a handle without waiting.
|
|
189
208
|
*
|
|
@@ -199,6 +218,8 @@ export declare class Sandbox {
|
|
|
199
218
|
*/
|
|
200
219
|
start(script: string, timeoutSec?: number, opts?: {
|
|
201
220
|
execId?: string;
|
|
221
|
+
env?: Record<string, string>;
|
|
222
|
+
cwd?: string;
|
|
202
223
|
}): Promise<Job>;
|
|
203
224
|
/** Re-attach to a job by id — after a crash, or after an unconfirmed start. */
|
|
204
225
|
job(execId: string): Promise<Job>;
|
|
@@ -238,6 +259,7 @@ export declare class Job {
|
|
|
238
259
|
id: string;
|
|
239
260
|
machineId: string;
|
|
240
261
|
state: string;
|
|
262
|
+
requestId?: string;
|
|
241
263
|
/**
|
|
242
264
|
* ⚠ `null` until known, and null FOREVER when `state` is `"lost"`. Never
|
|
243
265
|
* coerce this to 0 — a zero here reads as "the command succeeded".
|
package/dist/index.js
CHANGED
|
@@ -15,7 +15,7 @@ const DEFAULT_BASE_URL = "https://api.sistemo.io";
|
|
|
15
15
|
// User-Agent is required: the production WAF (Cloudflare) blocks generic
|
|
16
16
|
// library UAs with a 403. Browsers ignore attempts to set User-Agent and send
|
|
17
17
|
// their own (which the WAF allows), so this is a no-op there.
|
|
18
|
-
const USER_AGENT = "@sistemo/sdk/0.1.
|
|
18
|
+
const USER_AGENT = "@sistemo/sdk/0.1.3";
|
|
19
19
|
const RETRY_STATUSES = new Set([408, 429, 500, 502, 503, 504]);
|
|
20
20
|
export class SistemoError extends Error {
|
|
21
21
|
}
|
|
@@ -31,20 +31,31 @@ export class APIError extends SistemoError {
|
|
|
31
31
|
* that away would leave it unaddressable.
|
|
32
32
|
*/
|
|
33
33
|
body;
|
|
34
|
-
|
|
34
|
+
/** Seconds from `Retry-After`, capped at 60. */
|
|
35
|
+
retryAfter;
|
|
36
|
+
explicitRequestId;
|
|
37
|
+
constructor(status, detail, code, body, extra) {
|
|
35
38
|
super(`[${status}] ${detail}${code ? ` (${code})` : ""}`);
|
|
36
39
|
this.name = "APIError";
|
|
37
40
|
this.status = status;
|
|
38
41
|
this.detail = detail;
|
|
39
42
|
this.code = code;
|
|
40
43
|
this.body = body ?? {};
|
|
44
|
+
this.retryAfter = extra?.retryAfter;
|
|
45
|
+
this.explicitRequestId = extra?.requestId;
|
|
46
|
+
}
|
|
47
|
+
get requestId() {
|
|
48
|
+
if (this.explicitRequestId)
|
|
49
|
+
return this.explicitRequestId;
|
|
50
|
+
const v = this.body.request_id;
|
|
51
|
+
return typeof v === "string" ? v : undefined;
|
|
41
52
|
}
|
|
42
53
|
}
|
|
43
54
|
/** 401/403 — key missing, invalid, revoked, or a read-only key on a mutation. */
|
|
44
55
|
export class AuthError extends APIError {
|
|
45
56
|
}
|
|
46
57
|
/**
|
|
47
|
-
* 403 `quota_exceeded` — an account limit
|
|
58
|
+
* 403 `quota_exceeded` — this request would exceed an account limit.
|
|
48
59
|
*
|
|
49
60
|
* Deliberately NOT an `AuthError`, even though both arrive as 403. They need
|
|
50
61
|
* opposite handling, and conflating them sends callers to the wrong place:
|
|
@@ -103,26 +114,26 @@ export class ExecStartUnconfirmed extends APIError {
|
|
|
103
114
|
return String(this.body.exec_id ?? "");
|
|
104
115
|
}
|
|
105
116
|
}
|
|
106
|
-
function apiError(status, detail, code, body) {
|
|
117
|
+
function apiError(status, detail, code, body, extra) {
|
|
107
118
|
// 403 is two different things, told apart by `code` — never by the status.
|
|
108
119
|
if (status === 403 && code === "quota_exceeded")
|
|
109
|
-
return new QuotaExceededError(status, detail, code, body);
|
|
120
|
+
return new QuotaExceededError(status, detail, code, body, extra);
|
|
110
121
|
if (status === 401 || status === 403)
|
|
111
|
-
return new AuthError(status, detail, code, body);
|
|
122
|
+
return new AuthError(status, detail, code, body, extra);
|
|
112
123
|
if (status === 404)
|
|
113
|
-
return new NotFoundError(status, detail, code, body);
|
|
124
|
+
return new NotFoundError(status, detail, code, body, extra);
|
|
114
125
|
if (status === 410)
|
|
115
|
-
return new GoneError(status, detail, code, body);
|
|
126
|
+
return new GoneError(status, detail, code, body, extra);
|
|
116
127
|
if (status === 429)
|
|
117
|
-
return new RateLimitError(status, detail, code, body);
|
|
128
|
+
return new RateLimitError(status, detail, code, body, extra);
|
|
118
129
|
if (status === 501)
|
|
119
|
-
return new AsyncExecUnsupportedError(status, detail, code, body);
|
|
130
|
+
return new AsyncExecUnsupportedError(status, detail, code, body, extra);
|
|
120
131
|
// ⚠ Only a 503 that NAMES an exec is the unconfirmed-start case. A plain 503
|
|
121
132
|
// (no host available, say) is an ordinary retryable error and must not be
|
|
122
133
|
// dressed up as a command that might be running.
|
|
123
134
|
if (status === 503 && body && body.exec_id)
|
|
124
|
-
return new ExecStartUnconfirmed(status, detail, code, body);
|
|
125
|
-
return new APIError(status, detail, code, body);
|
|
135
|
+
return new ExecStartUnconfirmed(status, detail, code, body, extra);
|
|
136
|
+
return new APIError(status, detail, code, body, extra);
|
|
126
137
|
}
|
|
127
138
|
function newIdempotencyKey() {
|
|
128
139
|
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
@@ -133,9 +144,44 @@ function newIdempotencyKey() {
|
|
|
133
144
|
function sleep(ms) {
|
|
134
145
|
return new Promise((r) => setTimeout(r, ms));
|
|
135
146
|
}
|
|
147
|
+
const RETRY_AFTER_CAP_SEC = 60;
|
|
148
|
+
/** Seconds from a Retry-After header (delta-seconds or HTTP-date), capped at 60. */
|
|
149
|
+
export function parseRetryAfter(value) {
|
|
150
|
+
if (value == null || value === "")
|
|
151
|
+
return undefined;
|
|
152
|
+
const text = String(value).trim();
|
|
153
|
+
if (/^-?\d+$/.test(text)) {
|
|
154
|
+
const secs = Number(text);
|
|
155
|
+
if (!Number.isFinite(secs) || secs < 0)
|
|
156
|
+
return undefined;
|
|
157
|
+
return Math.min(secs, RETRY_AFTER_CAP_SEC);
|
|
158
|
+
}
|
|
159
|
+
const ms = Date.parse(text);
|
|
160
|
+
if (Number.isNaN(ms))
|
|
161
|
+
return undefined;
|
|
162
|
+
const delay = (ms - Date.now()) / 1000;
|
|
163
|
+
if (delay < 0)
|
|
164
|
+
return 0;
|
|
165
|
+
return Math.min(delay, RETRY_AFTER_CAP_SEC);
|
|
166
|
+
}
|
|
167
|
+
/** Milliseconds to wait before the next attempt. Tests pass `rand` so they do not sleep. */
|
|
168
|
+
export function retryDelayMs(attempt, backoffMs, maxBackoffMs, err, rand = Math.random) {
|
|
169
|
+
const base = Math.min(maxBackoffMs, backoffMs * 2 ** attempt);
|
|
170
|
+
let delay = base * (0.5 + rand());
|
|
171
|
+
if (err?.status === 429) {
|
|
172
|
+
if (err.retryAfter == null) {
|
|
173
|
+
delay = Math.max(delay, base);
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
delay = Math.min(Math.max(delay, err.retryAfter * 1000), RETRY_AFTER_CAP_SEC * 1000);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return delay;
|
|
180
|
+
}
|
|
136
181
|
/** Low-level API client. Most users want {@link Sandbox} instead. */
|
|
137
182
|
export class Client {
|
|
138
183
|
baseUrl;
|
|
184
|
+
lastRequestId;
|
|
139
185
|
apiKey;
|
|
140
186
|
timeoutMs;
|
|
141
187
|
maxRetries;
|
|
@@ -159,9 +205,23 @@ export class Client {
|
|
|
159
205
|
const retries = opts.maxRetries ?? this.maxRetries;
|
|
160
206
|
const methodU = method.toUpperCase();
|
|
161
207
|
let lastErr;
|
|
208
|
+
const headers = { ...(opts.headers ?? {}) };
|
|
209
|
+
let reqId;
|
|
210
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
211
|
+
if (k.toLowerCase() === "x-request-id" && v) {
|
|
212
|
+
reqId = v;
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (!reqId) {
|
|
217
|
+
reqId = newIdempotencyKey();
|
|
218
|
+
headers["X-Request-Id"] = reqId;
|
|
219
|
+
}
|
|
220
|
+
this.lastRequestId = reqId;
|
|
221
|
+
const next = { ...opts, headers };
|
|
162
222
|
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
163
223
|
try {
|
|
164
|
-
return await this.once(methodU, path, body,
|
|
224
|
+
return await this.once(methodU, path, body, next);
|
|
165
225
|
}
|
|
166
226
|
catch (e) {
|
|
167
227
|
lastErr = e;
|
|
@@ -222,7 +282,13 @@ export class Client {
|
|
|
222
282
|
catch {
|
|
223
283
|
/* non-JSON error body */
|
|
224
284
|
}
|
|
225
|
-
|
|
285
|
+
const retryAfter = parseRetryAfter(res.headers.get("Retry-After"));
|
|
286
|
+
let requestId;
|
|
287
|
+
if (body && typeof body.request_id === "string")
|
|
288
|
+
requestId = body.request_id;
|
|
289
|
+
if (!requestId)
|
|
290
|
+
requestId = res.headers.get("X-Request-Id") ?? this.lastRequestId;
|
|
291
|
+
throw apiError(res.status, detail, code, body, { retryAfter, requestId: requestId ?? undefined });
|
|
226
292
|
}
|
|
227
293
|
return (text ? JSON.parse(text) : {});
|
|
228
294
|
}
|
|
@@ -235,11 +301,7 @@ export class Client {
|
|
|
235
301
|
return Boolean(idempotencyKey);
|
|
236
302
|
}
|
|
237
303
|
async backoff(attempt, err) {
|
|
238
|
-
|
|
239
|
-
let delay = base * (0.5 + Math.random());
|
|
240
|
-
if (err?.status === 429)
|
|
241
|
-
delay = Math.max(delay, base);
|
|
242
|
-
await sleep(delay);
|
|
304
|
+
await sleep(retryDelayMs(attempt, this.retryBackoffMs, this.retryMaxBackoffMs, err));
|
|
243
305
|
}
|
|
244
306
|
// --- volumes (incl. detachable root volumes) ---------------------------
|
|
245
307
|
/** List the account's volumes (root and data). */
|
|
@@ -303,11 +365,11 @@ export class Sandbox {
|
|
|
303
365
|
* This is start + wait on a guest job (`POST /execs`). Default timeout 120s,
|
|
304
366
|
* ceiling 24 hours. A proxy never holds the connection for the whole command.
|
|
305
367
|
*/
|
|
306
|
-
async run(script, timeoutSec = 120) {
|
|
368
|
+
async run(script, timeoutSec = 120, opts = {}) {
|
|
307
369
|
const execId = newIdempotencyKey();
|
|
308
370
|
let job;
|
|
309
371
|
try {
|
|
310
|
-
job = await this.start(script, timeoutSec, { execId });
|
|
372
|
+
job = await this.start(script, timeoutSec, { execId, ...opts });
|
|
311
373
|
}
|
|
312
374
|
catch (e) {
|
|
313
375
|
if (e instanceof ExecStartUnconfirmed) {
|
|
@@ -324,6 +386,7 @@ export class Sandbox {
|
|
|
324
386
|
stdout: dec.decode(await job.output("stdout")),
|
|
325
387
|
stderr: dec.decode(await job.output("stderr")),
|
|
326
388
|
truncated: job.truncated,
|
|
389
|
+
requestId: job.requestId,
|
|
327
390
|
};
|
|
328
391
|
}
|
|
329
392
|
/**
|
|
@@ -341,12 +404,24 @@ export class Sandbox {
|
|
|
341
404
|
*/
|
|
342
405
|
async start(script, timeoutSec = 120, opts = {}) {
|
|
343
406
|
const execId = opts.execId ?? newIdempotencyKey();
|
|
407
|
+
const body = { exec_id: execId, script, timeout_sec: timeoutSec };
|
|
408
|
+
if (opts.env && Object.keys(opts.env).length)
|
|
409
|
+
body.env = opts.env;
|
|
410
|
+
if (opts.cwd)
|
|
411
|
+
body.cwd = opts.cwd;
|
|
344
412
|
try {
|
|
345
|
-
const rec = await this.client.request("POST", `/v1/machines/${this.id}/execs`,
|
|
413
|
+
const rec = await this.client.request("POST", `/v1/machines/${this.id}/execs`, body);
|
|
346
414
|
return new Job(this.client, this.id, rec);
|
|
347
415
|
}
|
|
348
416
|
catch (e) {
|
|
349
417
|
if (e instanceof APIError && e.status === 409) {
|
|
418
|
+
if (e.code === "too_many_execs" ||
|
|
419
|
+
e.code === "machine_process_limit" ||
|
|
420
|
+
e.code === "machine_disk_full" ||
|
|
421
|
+
e.code === "machine_out_of_memory" ||
|
|
422
|
+
e.code === "machine_not_running") {
|
|
423
|
+
throw e;
|
|
424
|
+
}
|
|
350
425
|
try {
|
|
351
426
|
const rec = await this.client.request("GET", `/v1/machines/${this.id}/execs/${execId}`);
|
|
352
427
|
return new Job(this.client, this.id, rec);
|
|
@@ -399,6 +474,7 @@ export class Job {
|
|
|
399
474
|
id = "";
|
|
400
475
|
machineId = "";
|
|
401
476
|
state = "";
|
|
477
|
+
requestId;
|
|
402
478
|
/**
|
|
403
479
|
* ⚠ `null` until known, and null FOREVER when `state` is `"lost"`. Never
|
|
404
480
|
* coerce this to 0 — a zero here reads as "the command succeeded".
|
|
@@ -412,6 +488,7 @@ export class Job {
|
|
|
412
488
|
constructor(client, sandboxId, rec) {
|
|
413
489
|
this.client = client;
|
|
414
490
|
this.sandboxId = sandboxId;
|
|
491
|
+
this.requestId = client.lastRequestId;
|
|
415
492
|
this.apply(rec);
|
|
416
493
|
}
|
|
417
494
|
apply(rec) {
|