› cavi-ai/
GitHub ↗

Verified example · TypeScript

Runtime node

examples/runtime-node.ts

@cavi-ai/api-clientv0.21.007f0ee45
TypeScript · complete source
import { ApiClientError, ApiClientErrorCode, ApiClientErrorType, type CapabilityClient, type RuntimeRunStartBody } from "@cavi-ai/api-client";

export async function runAndWait(
  client: CapabilityClient,
  body: RuntimeRunStartBody,
  options: { maxPolls?: number; pollIntervalMs?: number } = {},
) {
  const { maxPolls = 60, pollIntervalMs = 1_000 } = options;
  if (!Number.isInteger(maxPolls) || maxPolls < 0 || !Number.isFinite(pollIntervalMs) || pollIntervalMs < 0) {
    throw new ApiClientError("Use a non-negative poll count and interval.", {
      type: ApiClientErrorType.Validation, code: ApiClientErrorCode.InvalidRequest,
    });
  }
  let result = await client.startRun(body);
  if (!result.ok) throw new ApiClientError(result.gap.note, {
    code: ApiClientErrorCode.RequestFailed, cause: result.gap,
  });
  let run = result.data;
  const active = (status: string) => ["started", "running", "stopping"].includes(status);
  for (let poll = 0; active(run.status) && poll < maxPolls; poll += 1) {
    await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
    result = await client.getRun(run.run_id);
    if (!result.ok) throw new ApiClientError(result.gap.note, {
      code: ApiClientErrorCode.RequestFailed, cause: result.gap,
    });
    run = result.data;
  }
  // A limited wait returns the last observed state; callers decide whether to cancel.
  return run;
}

Package imports

Referenced by

Artifact provenance
Package
@cavi-ai/api-client@0.21.0
Release
v0.21.0
Commit
07f0ee45424c267278f7b0c89a7dcea4e2492cc1
Source
examples/runtime-node.ts
Tarball SHA-256
0924b5d3a7a40869bd44fedc47a9b8eb9844c2af1fd5c7ca77469d8b7c0b8558
Content SHA-256
24eff463c41582eaf5e70c58f42e5ae13bd12d02fa14ae2a886afa3abf5cdf48