@benchsdk/client

中文文档
0.5.12发布于 2026/11/04MITTypeScriptESM + CJS构建来源已验证近 30 天下载 5965

Client and worker helpers for the ComputeSDK benchmark orchestrator

原始使用文档
文档目录8 节
  1. Installation
  2. Authentication
  3. Run A Worker
  4. Create A Platform Run
  5. API
  6. Worker Engine
  7. Low-Level Client
  8. Task Result Shape

@benchsdk/client

Backwards-compatibility shim. @benchsdk/client re-exports the full @benchsdk/runner surface and preserves the legacy createBenchmarkClient().runWorker(options) spelling. New projects should import from @benchsdk/runner for authoring/operator helpers or @benchsdk/api for raw REST types.

Client and worker helpers for the ComputeSDK benchmark orchestrator.

This package talks to the platform-owned benchmark/run/participant/worker API. It does not mint canonical run, worker, attempt, event, or task IDs. Workers claim platform-assigned work, execute task indexes in their assigned range, and send task_results batches back to the platform.

Installation

npm install @benchsdk/client

Higher-level benchmark authoring (defineBenchmarkConfig / defineTask and the local orchestrator) lives in @benchsdk/runner. This package is REST transport plus the worker engine only.

Authentication

createBenchmarkClient requires a platform API key or OAuth token. Provide apiKey/token directly, or set BENCHMARKS_PLATFORM_API_KEY or BENCHMARKS_PLATFORM_TOKEN in the environment.

Run A Worker

import { createBenchmarkClient } from '@benchsdk/client';
import { compute } from 'computesdk';

const client = createBenchmarkClient({
  apiKey: process.env.BENCHMARKS_PLATFORM_API_KEY,
});

// `task` is a raw function; declare named steps imperatively via `step(...)`,
// so values flow between steps with closures and cleanup runs in a `finally`.
const { assignment, records } = await client.runWorker({
  benchmarkSlug: 'scale',
  runId: process.env.BENCHMARK_RUN_ID!,
  participantSlug: 'e2b',
  processKind: 'container',
  processKey: process.env.HOSTNAME,
  concurrency: 100,
  task: async ({ assignment, step }) => {
    const sandbox = await step('create', () =>
      compute.sandbox.create({ provider: assignment.provider ?? 'e2b' }),
    );
    try {
      await step('readiness', () => sandbox.runCommand('true'), { readiness: 'internal' });
      await step('exec.first-command', () => sandbox.runCommand('node -v'));
      // A `readiness: 'poll'` step reports active concurrency and waits until
      // the platform reports the participant's step is ready (a barrier).
      await step('pause', () => {}, { readiness: 'poll' });
      return { sandboxId: sandbox.id };
    } finally {
      await step('destroy', () => sandbox.destroy());
    }
  },
});

client.runWorker(...) claims the next pending platform assignment for the participant. If no work is available, it returns { assignment: null, records: [] }.

Task results are flushed to the platform in batches of 1,000 records by default. Set batchSize to tune this per worker; the SDK validates the platform limit of 5,000 records per batch. Workers also flush partial batches every 30 seconds by default via flushIntervalMs, and always flush pending records during final completion or shutdown.

Create A Platform Run

import { createBenchmarkClient } from '@benchsdk/client';

const client = createBenchmarkClient({
  apiKey: process.env.BENCHMARKS_PLATFORM_API_KEY,
});

await client.upsertBenchmark('scale', {
  name: 'Scale',
  config: { timeoutMs: 120_000 },
});

const { run } = await client.createRun('scale', {
  name: '10k smoke',
  totalTasks: 10_000,
  workerCount: 20,
  participants: ['e2b', 'modal'],
  config: { timeoutMs: 120_000 },
});

await client.planWorkers('scale', run.id, 'e2b');
await client.planWorkers('scale', run.id, 'modal');

console.log(run.id);

Workers must be planned before client.runWorker(...) can claim assignments.

API

Worker Engine

client.runWorker(options)

The task function receives:

FieldTypeDescription
assignmentBenchmarkAssignmentPlatform-owned assignment for this worker
taskIndexnumberDeterministic task index within the benchmark run
step(name, fn, options?) => Promise<R>Runs fn as a named platform step and records its timing/outcome

If the task returns a JSON object, it is stored as the task result data.

step(name, fn, options) supports step-level progress coordination via options:

OptionTypeDescription
reportConcurrencyboolean?Include active count for this step in worker heartbeats. Defaults to true
concurrencynumber?Per-worker target for this step. Defaults to worker concurrency/assignment target
readiness'poll' | 'internal'?Readiness coordination mode. Defaults to 'internal'. Use 'poll' for platform-coordinated barrier steps
readyPollIntervalMsnumber?Poll interval while waiting. Defaults to 1000
readyTimeoutMsnumber?Maximum readiness wait time

Low-Level Client

client.updateBenchmark(benchmarkSlug, input)
client.updateRun(benchmarkSlug, runId, input)
client.updateParticipant(benchmarkSlug, runId, participantSlug, input)
client.planWorkers(benchmarkSlug, runId, participantSlug)
client.getWorker(benchmarkSlug, runId, workerId)
client.updateWorker(benchmarkSlug, runId, workerId, input)
client.claimWorker(benchmarkSlug, runId, participantSlug, { processKind, processKey })
client.sendTaskResults({ benchmarkSlug, runId, workerId, attemptId, sequenceNumber, isFinal, records })
client.uploadWorkerArtifact(benchmarkSlug, runId, workerId, {
  attemptId,
  kind: 'log',
  name: 'coordinator.log',
  contentType: 'text/plain; charset=utf-8',
  body: logText,
})
client.heartbeatWorker(benchmarkSlug, runId, workerId, {
  attemptId,
  currentStep: 'pause',
  concurrency: [{ step: 'pause', active: 100, target: 100 }],
})
client.getRunProgress(benchmarkSlug, runId)
client.getBenchmarkResults(benchmarkSlug, { limit })
client.getRunResults(benchmarkSlug, runId)
client.getRunTaskResults(benchmarkSlug, runId, { bucketSize, failureLimit })
client.getRunTimeline(benchmarkSlug, runId, { bucketMs })
client.getRunImports(benchmarkSlug, runId)
client.completeWorker(benchmarkSlug, runId, workerId, attemptId)
client.failWorker(benchmarkSlug, runId, workerId, attemptId, error)
client.runWorker(options)

For custom coordinators that do not fit runWorker, use the best-effort reporter wrapper:

const reporter = await BenchmarkReporter.claim({
  benchmarkSlug: 'scale',
  runId,
  participantSlug: 'e2b',
  processKind: 'container',
  processKey: instanceId,
});

reporter?.setProgress({ done, inFlight, errors });
reporter?.recordResult(record);
await reporter?.waitForStepReady({ step: 'ready.barrier', timeoutMs: 15 * 60_000 });
await reporter?.uploadArtifact({
  kind: 'log',
  name: 'coordinator.log',
  contentType: 'text/plain; charset=utf-8',
  body: logText,
});
await reporter?.finish(false);

BenchmarkReporter swallows platform telemetry failures for claim, heartbeat, result flushing, artifact upload, and finish calls. Benchmark work can continue even when reporting is temporarily unavailable.

For runWorker, use onFinish to upload worker-level logs once, after final task results are flushed and before the worker attempt is completed or failed:

client.runWorker({
  benchmarkSlug: 'scale',
  runId,
  participantSlug: 'e2b',
  task,
  onFinish: async ({ uploadArtifact }) => {
    await uploadArtifact({
      kind: 'log',
      name: 'coordinator.log',
      contentType: 'text/plain; charset=utf-8',
      body: logText,
    });
  },
});

For coordinator health artifacts, sample system metrics:

const metrics = createSystemMetricsCollector();
const samples = [await metrics.sample()];
metrics.stop();

client.getRunProgress(...) returns a run summary plus per-participant worker, task, and concurrency progress:

const progress = await client.getRunProgress('scale', runId);

console.log(progress.summary.status);
console.log(progress.summary.participants);

const participant = progress.participants.find((item) => item.slug === 'e2b');
console.log(participant?.status);
console.log(participant?.workers);
console.log(participant?.tasks.completionRatio);
console.log(participant?.concurrency.find((item) => item.step === 'pause')?.ready);

Most workers should use client.runWorker(...).

Task Result Shape

{
  "taskIndex": 0,
  "status": "success",
  "startedAt": "2026-06-03T00:00:00.000Z",
  "completedAt": "2026-06-03T00:00:01.000Z",
  "latencyMs": 1000,
  "steps": [
    { "name": "create", "status": "success", "startedAt": "...", "completedAt": "...", "latencyMs": 700 },
    { "name": "exec.first-command", "status": "success", "startedAt": "...", "completedAt": "...", "latencyMs": 120 },
    { "name": "destroy", "status": "success", "startedAt": "...", "completedAt": "...", "latencyMs": 180 }
  ],
  "data": {
    "sandboxId": "..."
  }
}

版本与发布记录

@benchsdk/client 共发布 13 个版本,首次发布于 2026/07/28;过去 12 个月发布了 13 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.5.12latest2026/11/043 天前
0.5.112026/10/2910 天前
0.5.102026/10/2811 天前
0.5.92026/10/2514 天前
0.5.82026/10/2315 天前
0.5.62026/10/2216 天前

关于 @benchsdk/client 的常见问题

@benchsdk/client 是什么?

Client and worker helpers for the ComputeSDK benchmark orchestrator

如何安装 @benchsdk/client?

在项目目录运行 npm install @benchsdk/client,或使用 pnpm add / yarn add / bun add。

@benchsdk/client 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@benchsdk/client 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@benchsdk/client 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@benchsdk/client 可以商用吗?

@benchsdk/client 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@benchsdk/client 的下载量有多少?

根据 npm 官方下载统计,@benchsdk/client 在 2026/10/08 – 2026/11/06 这 30 天内被下载 5,965 次,日均约 199 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@benchsdk/client 还在维护吗?

最新版本 0.5.12 发布于 2026/11/04(3 天前);至今共发布 13 个版本,其中过去 12 个月发布了 13 个;首次发布于 2026/07/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。