@insforge/instabox-sdk 0.8.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,15 @@ 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
+ }
2556
+ function wholeCount(field, n) {
2557
+ if (!Number.isInteger(n) || n < 1) {
2558
+ throw new InstaboxError(`${field} must be a whole number from 1; got ${n}`, { code: "bad_request" });
2559
+ }
2560
+ return n;
2561
+ }
2551
2562
  var METADATA_KEY = /^[A-Za-z0-9_.-]{1,64}$/;
2552
2563
  var enc4 = encodeURIComponent;
2553
2564
  var Sandbox = class _Sandbox {
@@ -2588,8 +2599,10 @@ var Sandbox = class _Sandbox {
2588
2599
  const body = { name: opts.name ?? `sbx-${randomSuffix()}` };
2589
2600
  if (opts.archiveMs !== void 0) body.archiveSeconds = toSeconds(opts.archiveMs, "archiveMs");
2590
2601
  if (opts.autoSuspendMs !== void 0) body.autoSuspendAfterSeconds = toIdleSeconds(opts.autoSuspendMs);
2591
- const template = typeof a === "string" ? a : await defaultTemplate(http);
2592
- 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;
2593
2606
  if (opts.vcpus !== void 0) body.vcpus = opts.vcpus;
2594
2607
  if (opts.memMiB !== void 0) body.memMiB = opts.memMiB;
2595
2608
  if (opts.diskGiB !== void 0) body.persistentDiskGiB = opts.diskGiB;
@@ -2598,15 +2611,16 @@ var Sandbox = class _Sandbox {
2598
2611
  if (opts.vault === false) body.vault = false;
2599
2612
  const op = await createMachine(http, body);
2600
2613
  const done = await http.waitForOperation(op);
2601
- const machine = await getMachine(http, done.machineId);
2614
+ const machine = await untilPlaced(http, await getMachine(http, done.machineId));
2602
2615
  return new _Sandbox(http, machine, opts);
2603
2616
  }
2604
2617
  /** Attaches to an existing sandbox. Resumes it if it is paused or stopped, unless `resume: false`. */
2605
2618
  static async connect(sandboxId, opts = {}) {
2619
+ const start = startBody(opts.queue);
2606
2620
  const http = new HttpClient(opts);
2607
2621
  const sbx = new _Sandbox(http, await getMachine(http, sandboxId), opts);
2608
2622
  await sbx.settle(false);
2609
- if (opts.resume !== false) await sbx.wake();
2623
+ if (opts.resume !== false) await sbx.wake(start);
2610
2624
  return sbx;
2611
2625
  }
2612
2626
  /** Lists your sandboxes (all pages), optionally only those matching `metadata`. */
@@ -2644,6 +2658,31 @@ var Sandbox = class _Sandbox {
2644
2658
  static async usage(opts = {}) {
2645
2659
  return new HttpClient(opts).request("GET", "/v1/usage");
2646
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
+ }
2647
2686
  /** Lists the caller's private snapshots. Requires images:read. */
2648
2687
  static async listSnapshots(opts = {}) {
2649
2688
  const result = await new HttpClient(opts).request("GET", "/v1/snapshots");
@@ -2703,6 +2742,27 @@ var Sandbox = class _Sandbox {
2703
2742
  async setTimeout(..._args) {
2704
2743
  throw timeoutRemoved("setTimeout()", "Use setAutoSuspend(ms) to pause the sandbox once it has been idle that long");
2705
2744
  }
2745
+ /**
2746
+ * Gives the sandbox another of its plan's sizes (paid plans). A stopped sandbox takes it at its next
2747
+ * start. A running or paused one is stopped, resized and started again by one server operation: files
2748
+ * stay, running processes and paused memory do not. If it cannot start at the new size, the server
2749
+ * starts it again at the old one and this throws. A size the plan does not offer throws
2750
+ * `InstaboxQuotaError` (`spec_not_allowed`). Requires machines:write.
2751
+ */
2752
+ async resize(opts) {
2753
+ const vcpus = wholeCount("vcpus", opts.vcpus);
2754
+ const memMiB = wholeCount("memMiB", opts.memMiB);
2755
+ await this.settle();
2756
+ if (this.machine.spec.vcpus === vcpus && this.machine.spec.memMiB === memMiB) return;
2757
+ const body = { vcpus, memMiB };
2758
+ if (this.machine.state !== "stopped") body.apply = "restart";
2759
+ const r = await this.http.request("PATCH", `/v1/machines/${enc4(this.sandboxId)}`, { body });
2760
+ try {
2761
+ if ("machineId" in r) await this.http.waitForOperation(r);
2762
+ } finally {
2763
+ this.machine = await getMachine(this.http, this.sandboxId).catch(() => this.machine);
2764
+ }
2765
+ }
2706
2766
  /** Replaces the sandbox's metadata (`{}` clears it). */
2707
2767
  async setMetadata(metadata) {
2708
2768
  this.machine = await this.http.request("PATCH", `/v1/machines/${enc4(this.sandboxId)}`, {
@@ -2741,15 +2801,23 @@ var Sandbox = class _Sandbox {
2741
2801
  async pause() {
2742
2802
  await this.mutate("POST", "suspend");
2743
2803
  }
2744
- /** Resumes a paused sandbox from its snapshot, or starts a stopped one. */
2745
- 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);
2746
2807
  await this.settle();
2747
- await this.wake();
2808
+ await this.wake(start);
2748
2809
  }
2749
- /** Resumes or starts based on the cached state; callers make sure the cache is fresh. */
2750
- async wake() {
2751
- if (this.machine.state === "suspended") await this.mutate("POST", "resume");
2752
- 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
+ }
2753
2821
  }
2754
2822
  /** Stops the sandbox (guest shutdown; processes end, `/data` is kept). */
2755
2823
  async stop() {
@@ -2822,8 +2890,9 @@ var Sandbox = class _Sandbox {
2822
2890
  this.machine = await getMachine(this.http, this.sandboxId);
2823
2891
  }
2824
2892
  }
2825
- async mutate(method, action) {
2826
- 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 } : {});
2827
2896
  await this.http.waitForOperation(op);
2828
2897
  this.machine = await getMachine(this.http, this.sandboxId);
2829
2898
  }
@@ -2831,6 +2900,66 @@ var Sandbox = class _Sandbox {
2831
2900
  async function getMachine(http, id) {
2832
2901
  return http.request("GET", `/v1/machines/${enc4(id)}`);
2833
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
+ }
2834
2963
  async function getMetrics(http, id, opts) {
2835
2964
  const out = await http.request("GET", `/v1/machines/${enc4(id)}/metrics`, {
2836
2965
  query: { since: opts.since?.toISOString() }