@insforge/instabox-sdk 0.9.0 → 0.10.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/index.js CHANGED
@@ -2521,6 +2521,8 @@ function toInfo(m) {
2521
2521
  if (m.snapshot?.id) info.snapshotId = m.snapshot.id;
2522
2522
  if (m.archiveAt) info.archiveAt = new Date(m.archiveAt);
2523
2523
  if (m.autoSuspendAfterSeconds) info.autoSuspendMs = m.autoSuspendAfterSeconds * 1e3;
2524
+ if (m.spec.gpuType && m.spec.gpus) info.gpu = { type: m.spec.gpuType, count: m.spec.gpus };
2525
+ if (m.queue) info.queue = m.queue;
2524
2526
  return info;
2525
2527
  }
2526
2528
  function timeoutRemoved(what, use) {
@@ -2548,6 +2550,9 @@ function toSeconds(ms, field) {
2548
2550
  }
2549
2551
  return s;
2550
2552
  }
2553
+ function queueBody(q2) {
2554
+ return q2 === true ? {} : { maxWaitSeconds: toSeconds(q2.maxWaitMs, "queue.maxWaitMs") };
2555
+ }
2551
2556
  function wholeCount(field, n) {
2552
2557
  if (!Number.isInteger(n) || n < 1) {
2553
2558
  throw new InstaboxError(`${field} must be a whole number from 1; got ${n}`, { code: "bad_request" });
@@ -2594,8 +2599,10 @@ var Sandbox = class _Sandbox {
2594
2599
  const body = { name: opts.name ?? `sbx-${randomSuffix()}` };
2595
2600
  if (opts.archiveMs !== void 0) body.archiveSeconds = toSeconds(opts.archiveMs, "archiveMs");
2596
2601
  if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
2597
- const template = typeof a === "string" ? a : await defaultTemplate(http);
2598
- Object.assign(body, await resolveSource(http, template));
2602
+ if (opts.queue !== void 0) body.queue = queueBody(opts.queue);
2603
+ if (typeof a === "string") Object.assign(body, await resolveSource(http, a));
2604
+ else if (!opts.gpu) Object.assign(body, await resolveSource(http, await defaultTemplate(http)));
2605
+ if (opts.gpu) body.gpu = opts.gpu;
2599
2606
  if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
2600
2607
  if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
2601
2608
  if (opts.diskGiB !== void 0) body.persistentDiskGiB = opts.diskGiB;
@@ -2604,15 +2611,16 @@ var Sandbox = class _Sandbox {
2604
2611
  if (opts.vault === false) body.vault = false;
2605
2612
  const op = await createMachine(http, body);
2606
2613
  const done = await http.waitForOperation(op);
2607
- const machine = await getMachine(http, done.machineId);
2614
+ const machine = await untilPlaced(http, await getMachine(http, done.machineId));
2608
2615
  return new _Sandbox(http, machine, opts);
2609
2616
  }
2610
2617
  /** Attaches to an existing sandbox. Resumes it if it is paused or stopped, unless `resume: false`. */
2611
2618
  static async connect(sandboxId, opts = {}) {
2619
+ const start = startBody(opts.queue);
2612
2620
  const http = new HttpClient(opts);
2613
2621
  const sbx = new _Sandbox(http, await getMachine(http, sandboxId), opts);
2614
2622
  await sbx.settle(false);
2615
- if (opts.resume !== false) await sbx.wake();
2623
+ if (opts.resume !== false) await sbx.wake(start);
2616
2624
  return sbx;
2617
2625
  }
2618
2626
  /** Lists your sandboxes (all pages), optionally only those matching `metadata`. */
@@ -2650,6 +2658,31 @@ var Sandbox = class _Sandbox {
2650
2658
  static async usage(opts = {}) {
2651
2659
  return new HttpClient(opts).request("GET", "/v1/usage");
2652
2660
  }
2661
+ /**
2662
+ * The templates a create may name. Every version of a template is listed; `latest` marks the one a
2663
+ * create gets. GPU templates have `gpu` and list their GPU types in `gpuTypes`.
2664
+ */
2665
+ static async listTemplates(opts = {}) {
2666
+ return (await new HttpClient(opts).request("GET", "/v1/templates")).templates;
2667
+ }
2668
+ /**
2669
+ * A page of your GPU queue entries, newest first: live ones (`queued`, `dispatched`) with their place
2670
+ * in line, and ended ones with their `reason`. Requires machines:read.
2671
+ */
2672
+ static async listGpuQueue(opts = {}) {
2673
+ return new HttpClient(opts).request("GET", "/v1/gpu-queue", {
2674
+ query: { state: opts.state, limit: opts.limit, cursor: opts.cursor }
2675
+ });
2676
+ }
2677
+ /**
2678
+ * Stops a GPU queue entry's wait (`getInfo().queue.id`). A `create` entry's sandbox is deleted; a
2679
+ * `start` entry's stays stopped with its disks. Cancel this way, never with `kill()`, which deletes
2680
+ * a stopped sandbox's disks. Returns the entry, `cancelled`, or still `dispatched` with `cancelling`
2681
+ * when the sandbox was already starting. Requires machines:write.
2682
+ */
2683
+ static async cancelGpuQueue(entryId, opts = {}) {
2684
+ return new HttpClient(opts).request("DELETE", `/v1/gpu-queue/${enc4(entryId)}`);
2685
+ }
2653
2686
  /** Lists the caller's private snapshots. Requires images:read. */
2654
2687
  static async listSnapshots(opts = {}) {
2655
2688
  const result = await new HttpClient(opts).request("GET", "/v1/snapshots");
@@ -2768,15 +2801,23 @@ var Sandbox = class _Sandbox {
2768
2801
  async pause() {
2769
2802
  await this.mutate("POST", "suspend");
2770
2803
  }
2771
- /** Resumes a paused sandbox from its snapshot, or starts a stopped one. */
2772
- async resume() {
2804
+ /** Resumes a paused sandbox from its snapshot, or starts a stopped one (waiting for a GPU with `queue`). */
2805
+ async resume(opts = {}) {
2806
+ const start = startBody(opts.queue);
2773
2807
  await this.settle();
2774
- await this.wake();
2808
+ await this.wake(start);
2775
2809
  }
2776
- /** Resumes or starts based on the cached state; callers make sure the cache is fresh. */
2777
- async wake() {
2778
- if (this.machine.state === "suspended") await this.mutate("POST", "resume");
2779
- else if (this.machine.state === "stopped") await this.mutate("POST", "start");
2810
+ /**
2811
+ * Resumes or starts based on the cached state; callers make sure the cache is fresh. A sandbox
2812
+ * already waiting for a GPU is waited for: starting it again would not move it up the line.
2813
+ */
2814
+ async wake(start) {
2815
+ if (this.machine.queue) this.machine = await untilPlaced(this.http, this.machine);
2816
+ else if (this.machine.state === "suspended") await this.mutate("POST", "resume");
2817
+ else if (this.machine.state === "stopped") {
2818
+ await this.mutate("POST", "start", start);
2819
+ this.machine = await untilPlaced(this.http, this.machine);
2820
+ }
2780
2821
  }
2781
2822
  /** Stops the sandbox (guest shutdown; processes end, `/data` is kept). */
2782
2823
  async stop() {
@@ -2849,8 +2890,9 @@ var Sandbox = class _Sandbox {
2849
2890
  this.machine = await getMachine(this.http, this.sandboxId);
2850
2891
  }
2851
2892
  }
2852
- async mutate(method, action) {
2853
- const op = await this.http.request(method, `/v1/machines/${enc4(this.sandboxId)}/${action}`);
2893
+ async mutate(method, action, body) {
2894
+ const path = `/v1/machines/${enc4(this.sandboxId)}/${action}`;
2895
+ const op = await this.http.request(method, path, body ? { body } : {});
2854
2896
  await this.http.waitForOperation(op);
2855
2897
  this.machine = await getMachine(this.http, this.sandboxId);
2856
2898
  }
@@ -2858,6 +2900,66 @@ var Sandbox = class _Sandbox {
2858
2900
  async function getMachine(http, id) {
2859
2901
  return http.request("GET", `/v1/machines/${enc4(id)}`);
2860
2902
  }
2903
+ function startBody(queue) {
2904
+ return queue === void 0 ? void 0 : { queue: queueBody(queue) };
2905
+ }
2906
+ async function untilPlaced(http, m) {
2907
+ let last = m.queue;
2908
+ if (!last) return m;
2909
+ let orgId = m.orgId;
2910
+ let delay = http.pollIntervalMs;
2911
+ let waited;
2912
+ for (; ; ) {
2913
+ if (m.queue) last = m.queue;
2914
+ else if (m.state === "running") return m;
2915
+ else if (m.state !== "starting" && m.state !== "creating") throw await queueEnded(http, last, m, orgId);
2916
+ if (m.operationId && m.operationId !== waited) {
2917
+ waited = m.operationId;
2918
+ const op = await http.request("GET", `/v1/operations/${enc4(m.operationId)}`);
2919
+ await http.waitForOperation(op);
2920
+ } else {
2921
+ const deadline = Date.parse(last.expiresAt) + http.operationTimeoutMs;
2922
+ if (Date.now() + delay > deadline) {
2923
+ throw new InstaboxTimeoutError(
2924
+ `${m.id} was still waiting for a ${last.gpuType ?? ""} GPU ${http.operationTimeoutMs} ms past its queue entry's expiry (${last.expiresAt}); cancel it with Sandbox.cancelGpuQueue('${last.id}')`,
2925
+ { code: "operation_timeout" }
2926
+ );
2927
+ }
2928
+ await sleep(delay);
2929
+ delay = Math.min(Math.round(delay * 1.5), Math.max(5e3, http.pollIntervalMs));
2930
+ }
2931
+ try {
2932
+ m = await getMachine(http, m.id);
2933
+ } catch (err) {
2934
+ if (err instanceof InstaboxError && err.status === 404) throw await queueEnded(http, last, void 0, orgId);
2935
+ throw err;
2936
+ }
2937
+ orgId = m.orgId ?? orgId;
2938
+ }
2939
+ }
2940
+ var QUEUE_ENDS = {
2941
+ expired: "no GPU freed up within the wait",
2942
+ cancelled: "the request was cancelled",
2943
+ failed: "the start failed"
2944
+ };
2945
+ async function queueEnded(http, q2, m, orgId) {
2946
+ let entry;
2947
+ try {
2948
+ let cursor;
2949
+ for (let i = 0; i < 3 && !entry; i++) {
2950
+ const page = await http.request("GET", "/v1/gpu-queue", { query: { orgId, limit: 200, cursor } });
2951
+ entry = page.entries.find((e) => e.id === q2.id);
2952
+ cursor = page.nextCursor;
2953
+ if (!cursor) break;
2954
+ }
2955
+ } catch (err) {
2956
+ if (!(err instanceof InstaboxError)) throw err;
2957
+ }
2958
+ const what = QUEUE_ENDS[entry?.state ?? ""] ?? "the request ended";
2959
+ const left = !m || q2.kind === "create" ? "it was deleted" : `it is ${m.state} with its disks`;
2960
+ const code = entry?.reason || (entry ? `queue_${entry.state}` : "queue_ended");
2961
+ return new InstaboxError(`sandbox stopped waiting for a ${q2.gpuType ?? ""} GPU: ${what}; ${left}`, { code });
2962
+ }
2861
2963
  async function getMetrics(http, id, opts) {
2862
2964
  const out = await http.request("GET", `/v1/machines/${enc4(id)}/metrics`, {
2863
2965
  query: { since: opts.since?.toISOString() }