@batchactions/core

中文文档
0.0.6发布于 2026/03/14MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 1871

TypeScript batch job engine for ETL and bulk data processing with state management, retries, pause/resume, and lifecycle events

原始使用文档
文档目录13 节
  1. Install
  2. What You Get
  3. Quick Start
  4. In-Memory Records
  5. Serverless / Chunked Processing
  6. Basic Pattern
  7. maxRecords vs maxDurationMs
  8. Important Notes
  9. Main Exports
  10. Compatibility
  11. Related Packages
  12. Links
  13. License

@batchactions/core

Core batch processing engine for the @batchactions ecosystem.

Use this package when you need low-level control of batch orchestration, state transitions, events, and infrastructure adapters.

Install

npm install @batchactions/core

What You Get

  • BatchEngine for streaming batch execution
  • Job lifecycle control: start, pause, resume, abort, process chunk
  • Domain events for job, batch, and record progress
  • Built-in sources: BufferSource, FilePathSource, StreamSource, UrlSource
  • Built-in state stores: InMemoryStateStore, FileStateStore
  • Distributed contracts: DistributedStateStore, BatchReservation, helpers

Quick Start

import { BatchEngine, BufferSource, InMemoryStateStore } from '@batchactions/core';

const engine = new BatchEngine({
  stateStore: new InMemoryStateStore(),
  batchSize: 100,
  maxConcurrentBatches: 2,
  continueOnError: true,
});

engine.from(new BufferSource(JSON.stringify([{ id: 1 }, { id: 2 }])), {
  async *parse(chunk) {
    const rows = JSON.parse(chunk.toString()) as Array<Record<string, unknown>>;
    for (const row of rows) {
      yield row;
    }
  },
});

await engine.start(async (record) => {
  await processRecord(record);
});

In-Memory Records

When your data is already in memory (database results, API responses, etc.), skip the source/parser pipeline entirely:

import { BatchEngine } from '@batchactions/core';

const accounts = [
  { id: 'acc-1', channel: 'email', status: 'active' },
  { id: 'acc-2', channel: 'sms', status: 'active' },
];

const engine = new BatchEngine({
  batchSize: 50,
  maxConcurrentBatches: 4,
  continueOnError: true,
  maxRetries: 2,
});

engine.fromRecords(accounts);

await engine.start(async (record) => {
  await healthCheck(record);
});

Also works with async generators for lazy evaluation:

async function* fetchPages(): AsyncIterable<Record<string, unknown>> {
  let page = 1;
  while (true) {
    const results = await api.getPage(page++);
    if (results.length === 0) break;
    for (const item of results) yield item;
  }
}

engine.fromRecords(fetchPages());

Serverless / Chunked Processing

Use processChunk() with restore() to process records incrementally across multiple invocations — ideal for serverless environments with execution time limits (AWS Lambda, Vercel Functions, Cloudflare Workers).

Basic Pattern

import { BatchEngine, InMemoryStateStore } from '@batchactions/core';

const stateStore = new InMemoryStateStore(); // or FileStateStore, SequelizeStateStore, etc.

export async function handler(event: { jobId?: string }) {
  let engine: BatchEngine;

  if (event.jobId) {
    // Subsequent invocation: restore from persisted state
    const restored = await BatchEngine.restore(event.jobId, { stateStore, batchSize: 100 });
    if (!restored) throw new Error('Job not found');
    engine = restored;
  } else {
    // First invocation: create a new engine
    engine = new BatchEngine({ stateStore, batchSize: 100, continueOnError: true });
  }

  // The source must be re-fed on every invocation (it will be re-streamed)
  engine.from(source, parser);

  const result = await engine.processChunk(
    async (record) => { await processRecord(record); },
    { maxDurationMs: 25_000 },  // stop before Lambda's 30s timeout
  );

  if (!result.done) {
    // Schedule the next invocation with the job ID
    await scheduleNext({ jobId: result.jobId });
  }

  return { done: result.done, processed: result.totalProcessed };
}

maxRecords vs maxDurationMs

OptionWhen to useBoundary behavior
maxRecordsPredictable chunk sizes (e.g., "process 500 records per invocation")Stops after completing the batch that crosses the record limit
maxDurationMsTime-limited environments (e.g., "stop before Lambda timeout")Checks at batch boundaries — actual duration may exceed the limit by one batch

Both options can be combined. The chunk stops when either limit is reached.

Important Notes

  • Re-streaming requirement: The source must be re-fed on every invocation via from() or fromRecords(). The engine re-streams from the beginning and skips completed batches automatically.
  • Batch-level boundaries: Chunk limits are checked between batches, not between records. A batch always completes before the chunk stops. Use a smaller batchSize for finer-grained control.
  • Use a persistent StateStore: InMemoryStateStore loses state between process restarts. For production serverless use, pair with @batchactions/state-sequelize or @batchactions/state-prisma.
  • done flag: The ChunkResult.done property reliably indicates whether all records have been processed. Progress metrics (totalRecords, percentage) may show partial totals until the source has been fully consumed.

Main Exports

  • BatchEngine
  • BatchSplitter
  • EventBus, JobContext
  • JobStatus, BatchStatus
  • BufferSource, FilePathSource, StreamSource, UrlSource
  • InMemoryStateStore, FileStateStore
  • isDistributedStateStore

For full typed exports, see packages/core/src/index.ts.

Compatibility

  • Node.js >= 20.0.0
  • @batchactions/import: high-level import facade
  • @batchactions/distributed: multi-worker orchestration
  • @batchactions/state-sequelize: SQL persistence adapter (Sequelize)
  • @batchactions/state-prisma: SQL persistence adapter (Prisma v6/v7)

License

MIT

版本与发布记录

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

版本发布日期距今
0.0.6latest2026/03/147 个月前
0.0.52026/03/147 个月前
0.0.42026/02/198 个月前
0.0.32026/02/188 个月前
0.0.22026/02/188 个月前
0.0.12026/02/188 个月前

关于 @batchactions/core 的常见问题

@batchactions/core 是什么?

TypeScript batch job engine for ETL and bulk data processing with state management, retries, pause/resume, and lifecycle events

如何安装 @batchactions/core?

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

@batchactions/core 支持 TypeScript 吗?

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

@batchactions/core 支持 ESM 还是 CommonJS?

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

@batchactions/core 需要什么版本的 Node.js?

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

@batchactions/core 可以商用吗?

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

@batchactions/core 的下载量有多少?

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

@batchactions/core 还在维护吗?

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