@sandboxrouter/sdk 0.18.0 → 0.20.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/dist/assistant.d.ts +172 -0
- package/dist/assistant.js +307 -0
- package/dist/bench.d.ts +10 -0
- package/dist/bench.js +17 -7
- package/dist/browser.d.ts +164 -0
- package/dist/browser.js +350 -0
- package/dist/catalog.js +11 -2
- package/dist/cli.js +2 -2
- package/dist/client.d.ts +106 -0
- package/dist/client.js +78 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/leaderboard.d.ts +5 -1
- package/dist/leaderboard.js +7 -0
- package/dist/move.d.ts +5 -0
- package/dist/move.js +4 -3
- package/dist/price-index.d.ts +51 -0
- package/dist/price-index.js +70 -0
- package/dist/providers/runcloud.js +11 -3
- package/dist/providers/vercel.d.ts +6 -0
- package/dist/providers/vercel.js +18 -2
- package/dist/published.js +588 -115
- package/dist/recommend.d.ts +3 -1
- package/dist/recommend.js +4 -0
- package/dist/results.js +136 -1
- package/dist/router.d.ts +22 -0
- package/dist/router.js +28 -0
- package/dist/save.d.ts +120 -0
- package/dist/save.js +276 -0
- package/dist/steady.d.ts +92 -0
- package/dist/steady.js +164 -0
- package/dist/task.d.ts +2 -0
- package/dist/task.js +2 -2
- package/dist/types.d.ts +2 -0
- package/package.json +4 -4
package/dist/recommend.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** A job the benchmarks measure. "start" is only starting a sandbox and running one command. */
|
|
2
|
-
export type RecJob = "start" | "short" | "long" | "python" | "download" | "agent" | "repo";
|
|
2
|
+
export type RecJob = "start" | "short" | "long" | "python" | "download" | "agent" | "repo" | "assistant" | "browser";
|
|
3
3
|
/** What to rank by: lowest cost, shortest time, or both together ("value"). */
|
|
4
4
|
export type RecPriority = "cost" | "speed" | "value";
|
|
5
5
|
type BenchmarkSize = {
|
|
@@ -35,6 +35,8 @@ export interface PublishedJob {
|
|
|
35
35
|
minimumSeconds?: number;
|
|
36
36
|
/** Fee per sandbox started. */
|
|
37
37
|
perSandboxUsd?: number;
|
|
38
|
+
/** Something about how this number was measured that a reader should know. */
|
|
39
|
+
note?: string;
|
|
38
40
|
measuredAt: string;
|
|
39
41
|
}
|
|
40
42
|
export interface PublishedLoadRow {
|
package/dist/recommend.js
CHANGED
|
@@ -9,6 +9,8 @@ const LOAD_JOB = {
|
|
|
9
9
|
download: "start",
|
|
10
10
|
agent: "agents",
|
|
11
11
|
repo: "start",
|
|
12
|
+
assistant: "start",
|
|
13
|
+
browser: "start",
|
|
12
14
|
};
|
|
13
15
|
const mid = (xs) => {
|
|
14
16
|
const s = [...xs].sort((a, b) => a - b);
|
|
@@ -51,6 +53,8 @@ export function recommend(data, opts = {}) {
|
|
|
51
53
|
notes.push(`$${j.perSandboxUsd} per sandbox started`);
|
|
52
54
|
if (j.limited)
|
|
53
55
|
notes.push(`${j.limited} reported limit refusals`);
|
|
56
|
+
if (j.note)
|
|
57
|
+
notes.push(j.note);
|
|
54
58
|
raw.push({
|
|
55
59
|
provider: id,
|
|
56
60
|
name: j.name,
|
package/dist/results.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { steadySummary } from "./steady.js";
|
|
3
|
+
import { assistantSummary } from "./assistant.js";
|
|
4
|
+
import { browserSummary } from "./browser.js";
|
|
2
5
|
import { join, relative } from "node:path";
|
|
3
6
|
import { benchmarksPublishable, CATALOG } from "./catalog.js";
|
|
4
7
|
import { CHECK_STEPS } from "./check.js";
|
|
@@ -121,7 +124,7 @@ export function validateResult(j, now = Date.now()) {
|
|
|
121
124
|
out.push(`${r?.provider}: failures must be between 0 and runs`);
|
|
122
125
|
if (r?.limited !== undefined && !isNum(r.limited, 0, r?.failures ?? 0))
|
|
123
126
|
out.push(`${r?.provider}: limited must be between 0 and failures`);
|
|
124
|
-
for (const k of ["medianCreateMs", "medianExecMs", "medianReadyMs", "medianTaskReadyMs"]) {
|
|
127
|
+
for (const k of ["medianCreateMs", "medianExecMs", "medianReadyMs", "medianKillMs", "medianTaskReadyMs"]) {
|
|
125
128
|
if (r?.[k] !== undefined && !isNum(r[k], 1, MAX_MS))
|
|
126
129
|
out.push(`${r?.provider}: ${k} must be between 1 ms and 15 min`);
|
|
127
130
|
}
|
|
@@ -420,6 +423,138 @@ export function validateResult(j, now = Date.now()) {
|
|
|
420
423
|
out.push(`${r.provider}: errors must not be shared (they can hold account details)`);
|
|
421
424
|
}
|
|
422
425
|
}
|
|
426
|
+
else if (j.tool === "sandboxrouter-steady") {
|
|
427
|
+
add(checkDate(j.date, now));
|
|
428
|
+
add(checkLabel(j.label));
|
|
429
|
+
add(checkBy(j.by));
|
|
430
|
+
if (typeof j.task !== "string" || !j.task)
|
|
431
|
+
out.push("task must be the sample version, e.g. \"steady-v1\"");
|
|
432
|
+
if (!isSize(j.spec))
|
|
433
|
+
out.push("spec must record the requested size");
|
|
434
|
+
if (!Number.isInteger(j.samples) || !isNum(j.samples, 30, 1000))
|
|
435
|
+
out.push("samples must be at least 30");
|
|
436
|
+
if (!isNum(j.intervalSeconds, 5, 600))
|
|
437
|
+
out.push("intervalSeconds must be between 5 s and 10 min");
|
|
438
|
+
if (!Array.isArray(j.rows) || !j.rows.length)
|
|
439
|
+
out.push("rows is empty");
|
|
440
|
+
for (const r of Array.isArray(j.rows) ? j.rows : []) {
|
|
441
|
+
provider(r?.provider, "row provider");
|
|
442
|
+
if (noBench(r?.provider))
|
|
443
|
+
out.push(`${r.provider}: ${NO_BENCH}`);
|
|
444
|
+
if (!isSize(r?.size))
|
|
445
|
+
out.push(`${r?.provider}: invalid sandbox size`);
|
|
446
|
+
const ms = Array.isArray(r?.sampleMs) ? r.sampleMs : undefined;
|
|
447
|
+
if (!ms || ms.some((v) => !isNum(v, 1, MAX_MS))) {
|
|
448
|
+
out.push(`${r?.provider}: sampleMs must list each sample's time, between 1 ms and 15 min`);
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
if (!isCount(r.failures, j.samples) || ms.length + r.failures !== j.samples)
|
|
452
|
+
out.push(`${r.provider}: samples timed plus failures must equal the samples asked for`);
|
|
453
|
+
const want = steadySummary(ms);
|
|
454
|
+
for (const k of ["medianMs", "p95Ms", "maxMs"]) {
|
|
455
|
+
if (r[k] !== want[k])
|
|
456
|
+
out.push(`${r.provider}: ${k} does not match sampleMs`);
|
|
457
|
+
}
|
|
458
|
+
if (r.hourlyUsd !== undefined && !isNum(r.hourlyUsd, 0, 1000))
|
|
459
|
+
out.push(`${r.provider}: hourlyUsd is out of range`);
|
|
460
|
+
if ("error" in r || "lastError" in r)
|
|
461
|
+
out.push(`${r.provider}: errors must not be shared (they can hold account details)`);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
else if (j.tool === "sandboxrouter-assistant") {
|
|
465
|
+
add(checkDate(j.date, now));
|
|
466
|
+
add(checkLabel(j.label));
|
|
467
|
+
add(checkBy(j.by));
|
|
468
|
+
if (typeof j.task !== "string" || !j.task)
|
|
469
|
+
out.push("task must be the session version, e.g. \"assistant-v1\"");
|
|
470
|
+
if (!isSize(j.spec))
|
|
471
|
+
out.push("spec must record the requested size");
|
|
472
|
+
if (!Number.isInteger(j.runs) || !isNum(j.runs, 3, 100))
|
|
473
|
+
out.push("runs must be at least 3 sessions");
|
|
474
|
+
if (!Number.isInteger(j.calls) || !isNum(j.calls, 10, 1000))
|
|
475
|
+
out.push("calls must be at least 10");
|
|
476
|
+
if (!isNum(j.idleSeconds, 30, 3600))
|
|
477
|
+
out.push("idleSeconds must be between 30 s and an hour");
|
|
478
|
+
if (!isNum(j.uploadBytes, 1, 1e10) || !isNum(j.downloadBytes, 1, 1e10))
|
|
479
|
+
out.push("uploadBytes and downloadBytes must record the file sizes");
|
|
480
|
+
if (!Array.isArray(j.rows) || !j.rows.length)
|
|
481
|
+
out.push("rows is empty");
|
|
482
|
+
for (const r of Array.isArray(j.rows) ? j.rows : []) {
|
|
483
|
+
provider(r?.provider, "row provider");
|
|
484
|
+
if (noBench(r?.provider))
|
|
485
|
+
out.push(`${r.provider}: ${NO_BENCH}`);
|
|
486
|
+
if (!isSize(r?.size))
|
|
487
|
+
out.push(`${r?.provider}: invalid sandbox size`);
|
|
488
|
+
const sessions = Array.isArray(r?.sessions) ? r.sessions : undefined;
|
|
489
|
+
const times = ["createMs", "firstMs", "uploadMs", "analyseMs", "downloadMs", "idleMs", "sessionMs"];
|
|
490
|
+
const whole = (s) => times.every((k) => isNum(s?.[k], 1, MAX_MS)) && Array.isArray(s.callMs) && s.callMs.length === j.calls && s.callMs.every((v) => isNum(v, 1, MAX_MS)) &&
|
|
491
|
+
(s.cpuMs === undefined || isNum(s.cpuMs, 0, MAX_MS * 1024)) && (s.maxCoreMs === undefined || isNum(s.maxCoreMs, 0, MAX_MS));
|
|
492
|
+
if (!sessions || !sessions.every(whole)) {
|
|
493
|
+
out.push(`${r?.provider}: every session must list its times (1 ms to 15 min) and one time per call`);
|
|
494
|
+
continue;
|
|
495
|
+
}
|
|
496
|
+
if (!isCount(r.failures, j.runs) || sessions.length + r.failures !== j.runs)
|
|
497
|
+
out.push(`${r.provider}: sessions plus failures must equal the sessions asked for`);
|
|
498
|
+
const want = assistantSummary(sessions);
|
|
499
|
+
for (const k of ["firstAnswerMs", "uploadMs", "analyseMs", "downloadMs", "callMs", "callP95Ms", "idleMs"]) {
|
|
500
|
+
if (r[k] !== want[k])
|
|
501
|
+
out.push(`${r.provider}: ${k} does not match the sessions`);
|
|
502
|
+
}
|
|
503
|
+
if (r.sessionUsd !== undefined && !isNum(r.sessionUsd, 0, 1000))
|
|
504
|
+
out.push(`${r.provider}: sessionUsd is out of range`);
|
|
505
|
+
if (r.hourlyUsd !== undefined && !isNum(r.hourlyUsd, 0, 1000))
|
|
506
|
+
out.push(`${r.provider}: hourlyUsd is out of range`);
|
|
507
|
+
if ("error" in r || "lastError" in r)
|
|
508
|
+
out.push(`${r.provider}: errors must not be shared (they can hold account details)`);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
else if (j.tool === "sandboxrouter-browser") {
|
|
512
|
+
add(checkDate(j.date, now));
|
|
513
|
+
add(checkLabel(j.label));
|
|
514
|
+
add(checkBy(j.by));
|
|
515
|
+
if (typeof j.task !== "string" || !j.task)
|
|
516
|
+
out.push("task must be the browser task's version, e.g. \"browser-v1\"");
|
|
517
|
+
if (!isSize(j.spec))
|
|
518
|
+
out.push("spec must record the requested size");
|
|
519
|
+
if (!Number.isInteger(j.runs) || !isNum(j.runs, 3, 100))
|
|
520
|
+
out.push("runs must be at least 3 sessions");
|
|
521
|
+
if (!Number.isInteger(j.pages) || !isNum(j.pages, 1, 100) || !Number.isInteger(j.reloads) || !isNum(j.reloads, 1, 100))
|
|
522
|
+
out.push("pages and reloads must record how many pages were loaded");
|
|
523
|
+
if (!Array.isArray(j.rows) || !j.rows.length)
|
|
524
|
+
out.push("rows is empty");
|
|
525
|
+
for (const r of Array.isArray(j.rows) ? j.rows : []) {
|
|
526
|
+
provider(r?.provider, "row provider");
|
|
527
|
+
if (noBench(r?.provider))
|
|
528
|
+
out.push(`${r.provider}: ${NO_BENCH}`);
|
|
529
|
+
if (!isSize(r?.size))
|
|
530
|
+
out.push(`${r?.provider}: invalid sandbox size`);
|
|
531
|
+
const sessions = Array.isArray(r?.sessions) ? r.sessions : undefined;
|
|
532
|
+
const times = ["createMs", "setupMs", "launchMs", "workMs", "screenshotMs", "taskMs"];
|
|
533
|
+
const list = (v, n) => Array.isArray(v) && v.length === n && v.every((x) => isNum(x, 1, MAX_MS));
|
|
534
|
+
const whole = (s) => times.every((k) => isNum(s?.[k], 1, MAX_MS)) && list(s.pageMs, j.pages) && list(s.reloadMs, j.reloads) && isNum(s.screenshotBytes, 1, 1e9) &&
|
|
535
|
+
(s.cpuMs === undefined || isNum(s.cpuMs, 0, MAX_MS * 1024)) && (s.maxCoreMs === undefined || isNum(s.maxCoreMs, 0, MAX_MS));
|
|
536
|
+
if (!sessions || !sessions.every(whole)) {
|
|
537
|
+
out.push(`${r?.provider}: every session must list its times (1 ms to 15 min), one per page and one per reload`);
|
|
538
|
+
continue;
|
|
539
|
+
}
|
|
540
|
+
if (!isCount(r.failures, j.runs) || sessions.length + r.failures !== j.runs)
|
|
541
|
+
out.push(`${r.provider}: sessions plus failures must equal the sessions asked for`);
|
|
542
|
+
const stopped = r.failedAt === undefined ? 0 : ["create", "setup", "browse"].reduce((n, k) => n + (r.failedAt[k] ?? 0), 0);
|
|
543
|
+
if (r.failedAt !== undefined && (typeof r.failedAt !== "object" || Object.keys(r.failedAt).some((k) => !["create", "setup", "browse"].includes(k)) || stopped !== r.failures)) {
|
|
544
|
+
out.push(`${r.provider}: failedAt must count the failures by step (create, setup, browse)`);
|
|
545
|
+
}
|
|
546
|
+
const want = browserSummary(sessions);
|
|
547
|
+
for (const k of ["readyMs", "launchMs", "pageMs", "reloadMs", "workMs", "screenshotMs", "taskMs"]) {
|
|
548
|
+
if (r[k] !== want[k])
|
|
549
|
+
out.push(`${r.provider}: ${k} does not match the sessions`);
|
|
550
|
+
}
|
|
551
|
+
for (const k of ["sessionUsd", "taskUsd", "hourlyUsd"])
|
|
552
|
+
if (r[k] !== undefined && !isNum(r[k], 0, 1000))
|
|
553
|
+
out.push(`${r.provider}: ${k} is out of range`);
|
|
554
|
+
if ("error" in r || "lastError" in r)
|
|
555
|
+
out.push(`${r.provider}: errors must not be shared (they can hold account details)`);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
423
558
|
else {
|
|
424
559
|
out.push(`unknown tool "${String(j.tool)}": expected a benchmark report, saved check, cost run or hosted ledger check`);
|
|
425
560
|
}
|
package/dist/router.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { type ProviderInfo } from "./catalog.js";
|
|
|
2
2
|
import { type ComputerRoute, RoutedComputer, type ComputerOs, type ComputerProvider, type ComputerProviderId, type ComputerSpec } from "./computers.js";
|
|
3
3
|
import { Ledger } from "./ledger.js";
|
|
4
4
|
import { type CopyOptions, type CopyResult, type FileBox, type MoveOptions } from "./move.js";
|
|
5
|
+
import { type Keeper, type KeepOptions, type RecoverOptions, type RestoreOptions, type RestoreResult, type Saved, type SaveOptions, type SaveStore } from "./save.js";
|
|
5
6
|
import { type Attempt, type ExecOptions, type ExecResult, type Provider, type ProviderId, type ProviderSandbox, type RouteOptions, type SandboxProcess, type SandboxSpec, type StartOptions } from "./types.js";
|
|
6
7
|
/** vCPUs and memory a sandbox gets. */
|
|
7
8
|
export interface Size {
|
|
@@ -245,6 +246,27 @@ export declare class Router {
|
|
|
245
246
|
move(from: FileBox, opts?: MoveOptions): Promise<RoutedSandbox & {
|
|
246
247
|
moved: CopyResult;
|
|
247
248
|
}>;
|
|
249
|
+
/**
|
|
250
|
+
* Save a sandbox's folder to your own storage (`folderStore(dir)`, or anything with put/get/delete),
|
|
251
|
+
* so the work outlives the sandbox. Files only. Saving under the same name replaces the last save.
|
|
252
|
+
*
|
|
253
|
+
* const store = folderStore("./saves");
|
|
254
|
+
* await router.save(sbx, store, { name: "job-42", exclude: ["node_modules"] });
|
|
255
|
+
*/
|
|
256
|
+
save(box: FileBox, store: SaveStore, opts?: SaveOptions): Promise<Saved>;
|
|
257
|
+
/** Save a sandbox's folder every `everySeconds` (default 300) while it works. Call `stop()` when the job ends. */
|
|
258
|
+
keepSaved(box: FileBox, store: SaveStore, opts?: KeepOptions): Keeper;
|
|
259
|
+
/** Put a saved folder into a sandbox you already have. */
|
|
260
|
+
restore(box: FileBox, store: SaveStore, name: string, opts?: RestoreOptions): Promise<RestoreResult>;
|
|
261
|
+
/**
|
|
262
|
+
* Start a new sandbox with a saved folder in it, for when the sandbox doing the work is gone. Other
|
|
263
|
+
* providers are tried first and the one the save came from last, unless `provider` names where to go.
|
|
264
|
+
*
|
|
265
|
+
* sbx = await router.recover(store, "job-42");
|
|
266
|
+
*/
|
|
267
|
+
recover(store: SaveStore, name: string, opts?: RecoverOptions): Promise<RoutedSandbox & {
|
|
268
|
+
restored: RestoreResult;
|
|
269
|
+
}>;
|
|
248
270
|
/** Reattach to a sandbox by its routed id (`provider:nativeId`). */
|
|
249
271
|
get(id: string): Promise<RoutedSandbox>;
|
|
250
272
|
}
|
package/dist/router.js
CHANGED
|
@@ -6,6 +6,7 @@ import { PUBLISHED } from "./published.js";
|
|
|
6
6
|
import { Ledger, defaultLedgerFile } from "./ledger.js";
|
|
7
7
|
import { DEFAULT_EXEC_TIMEOUT_S, LIMIT_ERROR, SETUP_ERRORS, errorStatus, timeoutError, withDeadline } from "./util.js";
|
|
8
8
|
import { copyFiles, moveSandbox } from "./move.js";
|
|
9
|
+
import { keepSaved, recoverSandbox, restoreFiles, saveFiles } from "./save.js";
|
|
9
10
|
import { BILLED_VS_LIST } from "./billing.js";
|
|
10
11
|
import { FAILING, VERIFIED } from "./verified.js";
|
|
11
12
|
import { isPort, validate, validateStart } from "./validate.js";
|
|
@@ -493,6 +494,33 @@ export class Router {
|
|
|
493
494
|
move(from, opts = {}) {
|
|
494
495
|
return moveSandbox({ candidates: async (spec, route) => this.plan(spec, route), create: (spec, route) => this.create(spec, route) }, from, opts);
|
|
495
496
|
}
|
|
497
|
+
/**
|
|
498
|
+
* Save a sandbox's folder to your own storage (`folderStore(dir)`, or anything with put/get/delete),
|
|
499
|
+
* so the work outlives the sandbox. Files only. Saving under the same name replaces the last save.
|
|
500
|
+
*
|
|
501
|
+
* const store = folderStore("./saves");
|
|
502
|
+
* await router.save(sbx, store, { name: "job-42", exclude: ["node_modules"] });
|
|
503
|
+
*/
|
|
504
|
+
save(box, store, opts = {}) {
|
|
505
|
+
return saveFiles(box, store, opts);
|
|
506
|
+
}
|
|
507
|
+
/** Save a sandbox's folder every `everySeconds` (default 300) while it works. Call `stop()` when the job ends. */
|
|
508
|
+
keepSaved(box, store, opts = {}) {
|
|
509
|
+
return keepSaved(box, store, opts);
|
|
510
|
+
}
|
|
511
|
+
/** Put a saved folder into a sandbox you already have. */
|
|
512
|
+
restore(box, store, name, opts = {}) {
|
|
513
|
+
return restoreFiles(box, store, name, opts);
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Start a new sandbox with a saved folder in it, for when the sandbox doing the work is gone. Other
|
|
517
|
+
* providers are tried first and the one the save came from last, unless `provider` names where to go.
|
|
518
|
+
*
|
|
519
|
+
* sbx = await router.recover(store, "job-42");
|
|
520
|
+
*/
|
|
521
|
+
recover(store, name, opts = {}) {
|
|
522
|
+
return recoverSandbox({ candidates: async (spec, route) => this.plan(spec, route), create: (spec, route) => this.create(spec, route) }, store, name, opts);
|
|
523
|
+
}
|
|
496
524
|
/** Reattach to a sandbox by its routed id (`provider:nativeId`). */
|
|
497
525
|
async get(id) {
|
|
498
526
|
const { provider, nativeId } = parseId(id);
|
package/dist/save.d.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { type FileBox, type Mover } from "./move.js";
|
|
2
|
+
import { type RouteOptions, type SandboxSpec } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Where saved folders are kept: your own storage. Two keys are written per name, a small JSON record
|
|
5
|
+
* and the packed folder. `folderStore` keeps them on this machine's disk; anything with these three
|
|
6
|
+
* calls works (S3, R2, a database).
|
|
7
|
+
*/
|
|
8
|
+
export interface SaveStore {
|
|
9
|
+
put(key: string, data: Uint8Array): Promise<void>;
|
|
10
|
+
/** Undefined when there is nothing under the key. */
|
|
11
|
+
get(key: string): Promise<Uint8Array | undefined>;
|
|
12
|
+
delete(key: string): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
/** A `SaveStore` that is a folder on this machine. */
|
|
15
|
+
export declare function folderStore(dir: string): SaveStore;
|
|
16
|
+
export interface SaveOptions {
|
|
17
|
+
/** What this save is called. Saving under the same name again replaces it. Default: the sandbox's id. */
|
|
18
|
+
name?: string;
|
|
19
|
+
/** Folder to save. Default: the folder the sandbox's commands run in. */
|
|
20
|
+
path?: string;
|
|
21
|
+
/** Names or patterns to leave out, as `tar --exclude` reads them, e.g. `["node_modules", ".venv"]`. */
|
|
22
|
+
exclude?: string[];
|
|
23
|
+
/** Refuse when the packed folder is bigger than this (default 200 MB). It passes through this process's memory. */
|
|
24
|
+
maxBytes?: number;
|
|
25
|
+
/** Seconds the pack command may take (default 600). */
|
|
26
|
+
timeoutSeconds?: number;
|
|
27
|
+
/** Bytes read per file transfer (default 4 MB). */
|
|
28
|
+
chunkBytes?: number;
|
|
29
|
+
}
|
|
30
|
+
/** The record of one save. */
|
|
31
|
+
export interface Saved {
|
|
32
|
+
name: string;
|
|
33
|
+
/** When it was taken (ISO). */
|
|
34
|
+
at: string;
|
|
35
|
+
/** The provider the sandbox was on. */
|
|
36
|
+
provider: string;
|
|
37
|
+
/** The sandbox's id. */
|
|
38
|
+
sandbox: string;
|
|
39
|
+
/** The folder that was saved. */
|
|
40
|
+
folder: string;
|
|
41
|
+
/** True when it was the sandbox's own working folder (no `path` given). */
|
|
42
|
+
whole: boolean;
|
|
43
|
+
/** Size of the packed (gzip) folder. */
|
|
44
|
+
bytes: number;
|
|
45
|
+
/** The sandbox's size, so a recovered one can match it. */
|
|
46
|
+
size?: {
|
|
47
|
+
vcpu: number;
|
|
48
|
+
memoryGb: number;
|
|
49
|
+
};
|
|
50
|
+
/** The store key holding the packed folder. */
|
|
51
|
+
blob: string;
|
|
52
|
+
}
|
|
53
|
+
export interface RestoreOptions {
|
|
54
|
+
/** Folder to unpack into. Default: the saved folder's path, or the sandbox's own working folder when that was what was saved. */
|
|
55
|
+
to?: string;
|
|
56
|
+
/** Seconds the unpack command may take (default 600). */
|
|
57
|
+
timeoutSeconds?: number;
|
|
58
|
+
/** Bytes sent per file transfer (default 4 MB). */
|
|
59
|
+
chunkBytes?: number;
|
|
60
|
+
}
|
|
61
|
+
export interface RestoreResult {
|
|
62
|
+
name: string;
|
|
63
|
+
/** When the save that was put back was taken (ISO). */
|
|
64
|
+
at: string;
|
|
65
|
+
/** The folder written. */
|
|
66
|
+
to: string;
|
|
67
|
+
bytes: number;
|
|
68
|
+
ms: number;
|
|
69
|
+
}
|
|
70
|
+
export interface RecoverOptions extends RestoreOptions, RouteOptions {
|
|
71
|
+
/** The new sandbox's spec. Its size defaults to the saved sandbox's. */
|
|
72
|
+
spec?: SandboxSpec;
|
|
73
|
+
}
|
|
74
|
+
export interface KeepOptions extends SaveOptions {
|
|
75
|
+
/** Seconds between saves, counted from the end of one to the start of the next (default 300, at least 30). */
|
|
76
|
+
everySeconds?: number;
|
|
77
|
+
onSave?: (saved: Saved) => void;
|
|
78
|
+
/** A save that failed. Saving carries on at the next interval. */
|
|
79
|
+
onError?: (error: unknown) => void;
|
|
80
|
+
}
|
|
81
|
+
/** A running `keepSaved`. */
|
|
82
|
+
export interface Keeper {
|
|
83
|
+
/** The newest save, if one has finished. */
|
|
84
|
+
readonly last: Saved | undefined;
|
|
85
|
+
/** Save now, outside the interval. */
|
|
86
|
+
saveNow(): Promise<Saved>;
|
|
87
|
+
/** Stop saving. Waits for a save in flight; pass `{ save: true }` to take one last save first. */
|
|
88
|
+
stop(opts?: {
|
|
89
|
+
save?: boolean;
|
|
90
|
+
}): Promise<void>;
|
|
91
|
+
}
|
|
92
|
+
export declare const DEFAULT_SAVE_MAX_BYTES: number;
|
|
93
|
+
export declare const DEFAULT_SAVE_EVERY_S = 300;
|
|
94
|
+
export declare const MIN_SAVE_EVERY_S = 30;
|
|
95
|
+
/** The record of the newest save under a name, or undefined. */
|
|
96
|
+
export declare function findSaved(store: SaveStore, name: string): Promise<Saved | undefined>;
|
|
97
|
+
/**
|
|
98
|
+
* Save a sandbox's folder to your own storage, so the work outlives the sandbox: packed with tar in
|
|
99
|
+
* the sandbox, read out in pieces, written to the store. Files, their modes and symlinks are saved;
|
|
100
|
+
* running processes, memory and env vars are not. A new save under the same name replaces the old
|
|
101
|
+
* one only once it is complete, so a save cut short (the sandbox died halfway) leaves the last good
|
|
102
|
+
* one in place. A file being written at that moment may be saved half-written.
|
|
103
|
+
*/
|
|
104
|
+
export declare function saveFiles(box: FileBox, store: SaveStore, opts?: SaveOptions): Promise<Saved>;
|
|
105
|
+
/** Put a saved folder into a sandbox you already have, on any provider. */
|
|
106
|
+
export declare function restoreFiles(box: FileBox, store: SaveStore, name: string, opts?: RestoreOptions): Promise<RestoreResult>;
|
|
107
|
+
/**
|
|
108
|
+
* Start a new sandbox and put a saved folder into it: what to call when the sandbox that was doing
|
|
109
|
+
* the work is gone. Without a named provider it tries the other providers first and the one the
|
|
110
|
+
* save came from last. The new sandbox gets the saved one's size where a provider sells it.
|
|
111
|
+
*/
|
|
112
|
+
export declare function recoverSandbox<B extends FileBox>(mover: Mover<B>, store: SaveStore, name: string, opts?: RecoverOptions): Promise<B & {
|
|
113
|
+
restored: RestoreResult;
|
|
114
|
+
}>;
|
|
115
|
+
/**
|
|
116
|
+
* Save a sandbox's folder again and again while it works, so a sandbox that dies costs the minutes
|
|
117
|
+
* since the last save and not the whole run. Saves never overlap. One that fails is reported to
|
|
118
|
+
* `onError` and the next is tried at the usual interval.
|
|
119
|
+
*/
|
|
120
|
+
export declare function keepSaved(box: FileBox, store: SaveStore, opts?: KeepOptions): Keeper;
|
package/dist/save.js
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { IMAGE_FILES, mb, workdir } from "./move.js";
|
|
5
|
+
import { RouterError } from "./types.js";
|
|
6
|
+
import { shq } from "./util.js";
|
|
7
|
+
/** A `SaveStore` that is a folder on this machine. */
|
|
8
|
+
export function folderStore(dir) {
|
|
9
|
+
const file = (key) => {
|
|
10
|
+
if (!KEY.test(key))
|
|
11
|
+
throw new RouterError(`bad save key "${key}"`, [], "bad_request");
|
|
12
|
+
return join(dir, key);
|
|
13
|
+
};
|
|
14
|
+
return {
|
|
15
|
+
async put(key, data) {
|
|
16
|
+
await mkdir(dir, { recursive: true });
|
|
17
|
+
// Written beside the file and renamed, so a reader never sees half of it.
|
|
18
|
+
const tmp = `${file(key)}.${randomUUID().slice(0, 8)}.tmp`;
|
|
19
|
+
await writeFile(tmp, data);
|
|
20
|
+
await rename(tmp, file(key));
|
|
21
|
+
},
|
|
22
|
+
async get(key) {
|
|
23
|
+
try {
|
|
24
|
+
return new Uint8Array(await readFile(file(key)));
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (error.code === "ENOENT")
|
|
28
|
+
return undefined;
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
async delete(key) {
|
|
33
|
+
await rm(file(key), { force: true });
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export const DEFAULT_SAVE_MAX_BYTES = 200 * 1024 * 1024;
|
|
38
|
+
export const DEFAULT_SAVE_EVERY_S = 300;
|
|
39
|
+
export const MIN_SAVE_EVERY_S = 30;
|
|
40
|
+
const DEFAULT_CHUNK_BYTES = 4 * 1024 * 1024;
|
|
41
|
+
const DEFAULT_TIMEOUT_S = 600;
|
|
42
|
+
const KEY = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
|
|
43
|
+
const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,119}$/;
|
|
44
|
+
/** A store-safe name: what was given, or the sandbox id with its separators replaced. */
|
|
45
|
+
function saveName(given, box) {
|
|
46
|
+
const name = given ?? box.id.replace(/[^A-Za-z0-9._-]/g, "-").replace(/^[^A-Za-z0-9]+/, "");
|
|
47
|
+
if (!NAME.test(name))
|
|
48
|
+
throw new RouterError(`bad save name "${name}": use letters, digits, ".", "_" and "-" (120 at most)`, [], "bad_request");
|
|
49
|
+
return name;
|
|
50
|
+
}
|
|
51
|
+
const recordKey = (name) => `${name}.json`;
|
|
52
|
+
/** The record of the newest save under a name, or undefined. */
|
|
53
|
+
export async function findSaved(store, name) {
|
|
54
|
+
if (!NAME.test(name))
|
|
55
|
+
throw new RouterError(`bad save name "${name}"`, [], "bad_request");
|
|
56
|
+
const raw = await store.get(recordKey(name));
|
|
57
|
+
if (!raw)
|
|
58
|
+
return undefined;
|
|
59
|
+
try {
|
|
60
|
+
const saved = JSON.parse(new TextDecoder().decode(raw));
|
|
61
|
+
if (typeof saved.blob !== "string" || typeof saved.folder !== "string" || typeof saved.bytes !== "number")
|
|
62
|
+
throw new Error("missing fields");
|
|
63
|
+
return saved;
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
throw new RouterError(`the record of save "${name}" can't be read: ${error.message}`, [], "all_failed");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const absolute = (p, what) => {
|
|
70
|
+
if (!p.startsWith("/"))
|
|
71
|
+
throw new RouterError(`${what} needs an absolute path, got "${p}"`, [], "bad_request");
|
|
72
|
+
if (p.replace(/\/+$/, "") === "")
|
|
73
|
+
throw new RouterError(`${what} won't take the whole filesystem (/): name a folder`, [], "bad_request");
|
|
74
|
+
};
|
|
75
|
+
async function run(box, what, cmd, timeoutSeconds) {
|
|
76
|
+
const r = await box.exec(cmd, { timeoutSeconds });
|
|
77
|
+
if (r.exitCode !== 0) {
|
|
78
|
+
const detail = (r.stderr || r.stdout).trim().split("\n").slice(-3).join(" ");
|
|
79
|
+
throw new RouterError(`${what} failed on ${box.provider} (exit ${r.exitCode})${detail ? `: ${detail}` : ""}`, [], "all_failed");
|
|
80
|
+
}
|
|
81
|
+
return r.stdout;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Save a sandbox's folder to your own storage, so the work outlives the sandbox: packed with tar in
|
|
85
|
+
* the sandbox, read out in pieces, written to the store. Files, their modes and symlinks are saved;
|
|
86
|
+
* running processes, memory and env vars are not. A new save under the same name replaces the old
|
|
87
|
+
* one only once it is complete, so a save cut short (the sandbox died halfway) leaves the last good
|
|
88
|
+
* one in place. A file being written at that moment may be saved half-written.
|
|
89
|
+
*/
|
|
90
|
+
export async function saveFiles(box, store, opts = {}) {
|
|
91
|
+
const name = saveName(opts.name, box);
|
|
92
|
+
const timeoutSeconds = opts.timeoutSeconds ?? DEFAULT_TIMEOUT_S;
|
|
93
|
+
const chunk = Math.max(64 * 1024, Math.floor(opts.chunkBytes ?? DEFAULT_CHUNK_BYTES));
|
|
94
|
+
const maxBytes = opts.maxBytes ?? DEFAULT_SAVE_MAX_BYTES;
|
|
95
|
+
const folder = opts.path ?? (await workdir(box));
|
|
96
|
+
absolute(folder, "save");
|
|
97
|
+
const tmp = `/tmp/sr-save-${randomUUID().slice(0, 8)}`;
|
|
98
|
+
try {
|
|
99
|
+
const excludes = ["sr-save-*", "sr-move-*", ...(opts.exclude ?? [])].map((e) => `--exclude=${shq(e)}`).join(" ");
|
|
100
|
+
// tar exits 1 when a file changed while it was read. On a sandbox with work in progress that is
|
|
101
|
+
// expected and the archive is still whole, so only 2 and above count as failure.
|
|
102
|
+
const packed = await run(box, "packing the folder", [
|
|
103
|
+
`mkdir -p ${shq(tmp)}`,
|
|
104
|
+
`{ tar -czf ${shq(`${tmp}/a.tgz`)} ${excludes} -C ${shq(folder)} . ; rc=$?; [ "$rc" -le 1 ] || exit "$rc"; }`,
|
|
105
|
+
`echo "size=$(wc -c < ${shq(`${tmp}/a.tgz`)} | tr -d ' ')"`,
|
|
106
|
+
].join(" && "), timeoutSeconds);
|
|
107
|
+
const bytes = Number(/size=(\d+)/.exec(packed)?.[1] ?? NaN);
|
|
108
|
+
if (!Number.isFinite(bytes))
|
|
109
|
+
throw new RouterError(`couldn't read the packed size on ${box.provider}`, [], "all_failed");
|
|
110
|
+
if (bytes > maxBytes) {
|
|
111
|
+
throw new RouterError(`the folder packs to ${mb(bytes)}, over the ${mb(maxBytes)} limit: pass path or exclude (e.g. node_modules), or a higher maxBytes`, [], "bad_request");
|
|
112
|
+
}
|
|
113
|
+
const listed = await run(box, "splitting the archive", `cd ${shq(tmp)} && split -b ${chunk} -a 4 a.tgz p. && rm a.tgz && ls p.*`, timeoutSeconds);
|
|
114
|
+
const parts = listed.split("\n").map((l) => l.trim()).filter((l) => /^p\.[a-z]{4}$/.test(l)).sort();
|
|
115
|
+
if (parts.length === 0)
|
|
116
|
+
throw new RouterError(`no archive pieces found on ${box.provider}`, [], "all_failed");
|
|
117
|
+
const data = new Uint8Array(bytes);
|
|
118
|
+
let at = 0;
|
|
119
|
+
for (const part of parts) {
|
|
120
|
+
const piece = await box.readFile(`${tmp}/${part}`);
|
|
121
|
+
if (at + piece.length > bytes)
|
|
122
|
+
throw new RouterError(`the archive read from ${box.provider} is longer than the ${bytes} bytes it packed`, [], "all_failed");
|
|
123
|
+
data.set(piece, at);
|
|
124
|
+
at += piece.length;
|
|
125
|
+
}
|
|
126
|
+
// Catches a piece a provider cut short before a broken archive replaces a good save.
|
|
127
|
+
if (at !== bytes)
|
|
128
|
+
throw new RouterError(`the archive read from ${box.provider} is ${at} bytes, expected ${bytes}`, [], "all_failed");
|
|
129
|
+
const before = await findSaved(store, name).catch(() => undefined);
|
|
130
|
+
const saved = {
|
|
131
|
+
name,
|
|
132
|
+
at: new Date().toISOString(),
|
|
133
|
+
provider: box.provider,
|
|
134
|
+
sandbox: box.id,
|
|
135
|
+
folder,
|
|
136
|
+
whole: opts.path === undefined,
|
|
137
|
+
bytes,
|
|
138
|
+
...(box.size ? { size: { vcpu: box.size.vcpu, memoryGb: box.size.memoryGb } } : {}),
|
|
139
|
+
blob: `${name}.${Date.now().toString(36)}${randomUUID().slice(0, 4)}.tgz`,
|
|
140
|
+
};
|
|
141
|
+
// The packed folder first, the record last: the record only ever points at a complete archive.
|
|
142
|
+
await store.put(saved.blob, data);
|
|
143
|
+
await store.put(recordKey(name), new TextEncoder().encode(JSON.stringify(saved, null, 2) + "\n"));
|
|
144
|
+
if (before && before.blob !== saved.blob)
|
|
145
|
+
await store.delete(before.blob).catch(() => { });
|
|
146
|
+
return saved;
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
await box.exec(`rm -rf ${shq(tmp)}`, { timeoutSeconds: 60 }).catch(() => { });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/** Put a saved folder into a sandbox you already have, on any provider. */
|
|
153
|
+
export async function restoreFiles(box, store, name, opts = {}) {
|
|
154
|
+
const started = Date.now();
|
|
155
|
+
const saved = await findSaved(store, name);
|
|
156
|
+
if (!saved)
|
|
157
|
+
throw new RouterError(`nothing is saved as "${name}"`, [], "bad_request");
|
|
158
|
+
const data = await store.get(saved.blob);
|
|
159
|
+
if (!data)
|
|
160
|
+
throw new RouterError(`save "${name}" has a record but its archive (${saved.blob}) is missing from the store`, [], "all_failed");
|
|
161
|
+
if (data.length !== saved.bytes)
|
|
162
|
+
throw new RouterError(`save "${name}" is ${data.length} bytes in the store, its record says ${saved.bytes}`, [], "all_failed");
|
|
163
|
+
const timeoutSeconds = opts.timeoutSeconds ?? DEFAULT_TIMEOUT_S;
|
|
164
|
+
const chunk = Math.max(64 * 1024, Math.floor(opts.chunkBytes ?? DEFAULT_CHUNK_BYTES));
|
|
165
|
+
// A saved working folder goes into the new sandbox's own working folder, wherever its image puts that.
|
|
166
|
+
// Some images run commands in / (Modal's stock one): there the folder goes back at the path it was saved from.
|
|
167
|
+
const own = saved.whole && opts.to === undefined ? await workdir(box) : undefined;
|
|
168
|
+
const ownFolder = own !== undefined && own.replace(/\/+$/, "") !== "";
|
|
169
|
+
const to = opts.to ?? (ownFolder ? own : saved.folder);
|
|
170
|
+
absolute(to, "restore");
|
|
171
|
+
const tmp = `/tmp/sr-save-${randomUUID().slice(0, 8)}`;
|
|
172
|
+
try {
|
|
173
|
+
await run(box, "preparing the sandbox", `mkdir -p ${shq(tmp)} ${shq(to)}`, timeoutSeconds);
|
|
174
|
+
for (let i = 0, n = 0; i < data.length || n === 0; i += chunk, n++) {
|
|
175
|
+
await box.writeFile(`${tmp}/p.${String(n).padStart(6, "0")}`, data.subarray(i, i + chunk));
|
|
176
|
+
}
|
|
177
|
+
const got = await run(box, "checking the archive", `cat ${shq(tmp)}/p.* | wc -c | tr -d ' '`, timeoutSeconds);
|
|
178
|
+
if (Number(got.trim().split("\n").pop()) !== saved.bytes) {
|
|
179
|
+
throw new RouterError(`the archive arrived as ${got.trim()} bytes on ${box.provider}, expected ${saved.bytes}`, [], "all_failed");
|
|
180
|
+
}
|
|
181
|
+
// As in a move: the sandbox keeps its own image's shell startup files when a whole working folder is put back.
|
|
182
|
+
const keep = ownFolder ? IMAGE_FILES.map(shq).join(" ") : "";
|
|
183
|
+
const hold = keep ? `mkdir -p ${shq(`${tmp}/keep`)} && for f in ${keep}; do if [ -f ${shq(to)}/"$f" ]; then cp -p ${shq(to)}/"$f" ${shq(`${tmp}/keep`)}/; fi; done && ` : "";
|
|
184
|
+
const back = keep ? ` && for f in ${keep}; do if [ -f ${shq(`${tmp}/keep`)}/"$f" ]; then cp -p ${shq(`${tmp}/keep`)}/"$f" ${shq(to)}/; fi; done` : "";
|
|
185
|
+
await run(box, "unpacking the folder", `${hold}cat ${shq(tmp)}/p.* | tar -xzo -f - -C ${shq(to)}${back}`, timeoutSeconds);
|
|
186
|
+
return { name, at: saved.at, to, bytes: saved.bytes, ms: Date.now() - started };
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
await box.exec(`rm -rf ${shq(tmp)}`, { timeoutSeconds: 60 }).catch(() => { });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Start a new sandbox and put a saved folder into it: what to call when the sandbox that was doing
|
|
194
|
+
* the work is gone. Without a named provider it tries the other providers first and the one the
|
|
195
|
+
* save came from last. The new sandbox gets the saved one's size where a provider sells it.
|
|
196
|
+
*/
|
|
197
|
+
export async function recoverSandbox(mover, store, name, opts = {}) {
|
|
198
|
+
const { spec: given = {}, to, timeoutSeconds, chunkBytes, ...route } = opts;
|
|
199
|
+
const saved = await findSaved(store, name);
|
|
200
|
+
if (!saved)
|
|
201
|
+
throw new RouterError(`nothing is saved as "${name}"`, [], "bad_request");
|
|
202
|
+
const usable = async (s) => (await mover.candidates(s, route)).filter((c) => !c.skip).map((c) => c.provider);
|
|
203
|
+
const sized = given.vcpu === undefined && given.memoryGb === undefined && saved.size ? { ...given, vcpu: saved.size.vcpu, memoryGb: saved.size.memoryGb } : undefined;
|
|
204
|
+
let spec = { ...given };
|
|
205
|
+
let list = sized ? await usable(sized) : [];
|
|
206
|
+
if (list.length > 0)
|
|
207
|
+
spec = sized;
|
|
208
|
+
else
|
|
209
|
+
list = await usable(spec);
|
|
210
|
+
if (list.length === 0)
|
|
211
|
+
throw new RouterError(`no provider can take save "${name}"`, [], "no_provider");
|
|
212
|
+
if (route.provider === undefined)
|
|
213
|
+
route.provider = [...list.filter((p) => p !== saved.provider), ...list.filter((p) => p === saved.provider)];
|
|
214
|
+
const next = await mover.create(spec, route);
|
|
215
|
+
try {
|
|
216
|
+
const restored = await restoreFiles(next, store, name, { to, timeoutSeconds, chunkBytes });
|
|
217
|
+
return Object.assign(next, { restored });
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
await next.kill().catch(() => { });
|
|
221
|
+
throw error;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Save a sandbox's folder again and again while it works, so a sandbox that dies costs the minutes
|
|
226
|
+
* since the last save and not the whole run. Saves never overlap. One that fails is reported to
|
|
227
|
+
* `onError` and the next is tried at the usual interval.
|
|
228
|
+
*/
|
|
229
|
+
export function keepSaved(box, store, opts = {}) {
|
|
230
|
+
const { everySeconds = DEFAULT_SAVE_EVERY_S, onSave, onError, ...save } = opts;
|
|
231
|
+
if (!Number.isFinite(everySeconds) || everySeconds < MIN_SAVE_EVERY_S) {
|
|
232
|
+
throw new RouterError(`everySeconds must be at least ${MIN_SAVE_EVERY_S}, got ${everySeconds}`, [], "bad_request");
|
|
233
|
+
}
|
|
234
|
+
// The name is fixed once, so every save replaces the one before it.
|
|
235
|
+
const name = saveName(save.name, box);
|
|
236
|
+
let last;
|
|
237
|
+
let stopped = false;
|
|
238
|
+
let timer;
|
|
239
|
+
let inFlight = Promise.resolve();
|
|
240
|
+
const saveNow = () => {
|
|
241
|
+
const next = inFlight.then(async () => {
|
|
242
|
+
const saved = await saveFiles(box, store, { ...save, name });
|
|
243
|
+
last = saved;
|
|
244
|
+
onSave?.(saved);
|
|
245
|
+
return saved;
|
|
246
|
+
});
|
|
247
|
+
inFlight = next.catch(() => { });
|
|
248
|
+
return next;
|
|
249
|
+
};
|
|
250
|
+
const arm = () => {
|
|
251
|
+
if (stopped)
|
|
252
|
+
return;
|
|
253
|
+
timer = setTimeout(() => {
|
|
254
|
+
saveNow()
|
|
255
|
+
.catch((error) => onError?.(error))
|
|
256
|
+
.finally(arm);
|
|
257
|
+
}, everySeconds * 1000);
|
|
258
|
+
// A pending save never keeps the process alive on its own.
|
|
259
|
+
timer.unref?.();
|
|
260
|
+
};
|
|
261
|
+
arm();
|
|
262
|
+
return {
|
|
263
|
+
get last() {
|
|
264
|
+
return last;
|
|
265
|
+
},
|
|
266
|
+
saveNow,
|
|
267
|
+
async stop(o = {}) {
|
|
268
|
+
stopped = true;
|
|
269
|
+
if (timer)
|
|
270
|
+
clearTimeout(timer);
|
|
271
|
+
if (o.save)
|
|
272
|
+
await saveNow();
|
|
273
|
+
await inFlight;
|
|
274
|
+
},
|
|
275
|
+
};
|
|
276
|
+
}
|