@godspeedai/cognate-events

中文文档
0.10.0发布于 2026/11/16Apache-2.0ES Module构建来源已验证近 30 天下载 6438

Event envelope, durable store port, and the store conformance kit.

原始使用文档
文档目录9 节
  1. Installation
  2. The envelope
  3. Quick start
  4. What DurableStore covers
  5. Delivering outbox work
  6. Conformance kit for store implementers
  7. Limitations
  8. Related packages
  9. License

@godspeedai/cognate-events

The durable state plane contract for Cognate: the canonical event envelope, the DurableStore port every store implements, and an outbox dispatcher for work that happens after commit. This package defines the contract — it ships no storage.

When to use this package: you are implementing a durable store, building tooling over an event log, or delivering outbox work yourself. Applications get a working store through @godspeedai/cognate-store-sqlite or @godspeedai/cognate-store-memory, both of which implement this contract.

Installation

bun add @godspeedai/cognate-events

Requires Bun >= 1.4.0.

The envelope

NewEvent is what a decision submits. The store assigns eventId, streamId, streamSequence (gap-free per stream), position (store-wide commit order), and recordedAt. Sequence and position are the ordering authority — occurredAt is source-claimed provenance and never orders events.

validateNewEvent enforces the envelope before anything is written: required fields present, lower-case dotted eventType, positive integer schemaVersion, ISO-8601 occurredAt, a JSON payload within 1 MiB (MAX_PAYLOAD_BYTES). Failures throw EnvelopeValidationError listing every problem.

fingerprint computes a stable, key-order-independent SHA-256 of a JSON request — what idempotency uses to tell a replay apart from a different request.

Quick start

import { fingerprint, validateNewEvent } from "@godspeedai/cognate-events";

const placed = {
  eventType: "order.placed",
  schemaVersion: 1,
  occurredAt: new Date().toISOString(),
  tenant: "tenant-a",
  correlationId: "corr-1",
  causationId: null,
  runId: null,
  scopeId: "root",
  payload: { sku: "widget", quantity: 2 },
};
validateNewEvent(placed);

const commit = {
  idempotency: { scope: "alice:order", key: "order-1", fingerprint: fingerprint(placed.payload) },
  appends: [{ streamId: "order-1", expectedVersion: 0, events: [placed] }],
  result: { placed: true },
};

Hand commit to any DurableStore — here the in-memory one:

import { createMemoryStore } from "@godspeedai/cognate-store-memory";

const store = createMemoryStore();
const outcome = await store.commit(commit);
// { kind: "committed", events: [...], records: [], result: { placed: true } }

Committing the same request again returns { kind: "duplicate", result: { placed: true } } — the originally recorded result, with no new fact written. Reusing the key for a different request throws IdempotencyMismatchError.

What DurableStore covers

One atomic commit per decision — all of it or nothing:

  • stream appends guarded by expected versions (a lost race throws ConcurrencyError; reread and retry, never overwrite);
  • compare-and-swap record writes (RecordConflictError);
  • outbox intents for work to perform after commit;
  • the idempotency result recorded with the decision.

Beyond commit: readStream/readAll page in sequence and position order, getRecord/listRecords read versioned records, onCommitted subscribes to events (called only after the transaction commits), projection checkpoints commit atomically with projection state, blobs are content-addressed (sha256:<hex>), and erasePayload removes an event's payload while keeping its envelope and appending a tombstone event to the $erasures stream.

Delivering outbox work

OutboxDispatcher claims committed intents and delivers them at least once, with bounded exponential backoff:

import { OutboxDispatcher } from "@godspeedai/cognate-events";

const dispatcher = new OutboxDispatcher(store, {
  topic: "email",
  backoff: { baseMs: 100, maxMs: 5_000, maxAttempts: 10 },
  deliver: async (item) => {
    await sendEmail(item.payload);
    return { accepted: item.id };
  },
});

const report = await dispatcher.drain();
// { delivered: [...], retried: [{ id, retryAt }], poisoned: [...] }

Throw PermanentDeliveryError from deliver to poison an item immediately instead of retrying. Poisoned items stay visible via store.listOutbox({ status: "poisoned" }) until an operator calls store.requeueOutbox. Delivery targets must deduplicate by item.id — at-least-once delivery means a retry can deliver twice.

Built-in stores also provide optional fenced claim methods (claimOutboxLeased, renewOutboxLease, and settleOutboxLease). They bind renewal and settlement to an owner and monotonically increasing generation, so a worker whose lease expired or was requeued cannot acknowledge a later claim. OutboxDispatcher uses these methods when available, heartbeats active deliveries, and aborts work after losing its claim. Its concurrency option defaults to one; values above one require fenced lease support. Older adapters remain compatible through the existing methods but do not provide stale-worker protection; run their dispatcher in one process only. See the lease contract for clock and delivery limits.

Conformance kit for store implementers

Implementing a store means implementing it correctly; run the kit unchanged in your test suite:

import { storeConformance } from "@godspeedai/cognate-events/conformance";

storeConformance("my-store", myStoreFactory, { persistent: true, fencedOutbox: true });

Pass persistent: false for stores that do not survive a reopen; persistent stores are additionally tested to keep every committed decision across one. Reference implementations: @godspeedai/cognate-store-memory and @godspeedai/cognate-store-sqlite.

Limitations

  • No storage here: the DurableStore interface is the product. Pick an implementation or write one.
  • Event payloads are capped at 1 MiB; larger content belongs in a blob.
  • Ordering is defined by sequence numbers and positions, never by timestamps.

License

Apache-2.0

版本与发布记录

@godspeedai/cognate-events 共发布 20 个版本,首次发布于 2026/10/09;过去 12 个月发布了 20 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.10.0latest2026/11/16今天
0.9.22026/11/152 天前
0.9.12026/11/143 天前
0.9.02026/11/0610 天前
0.8.02026/10/2720 天前
0.7.12026/10/2523 天前

关于 @godspeedai/cognate-events 的常见问题

@godspeedai/cognate-events 是什么?

Event envelope, durable store port, and the store conformance kit.

如何安装 @godspeedai/cognate-events?

在项目目录运行 npm install @godspeedai/cognate-events,或使用 pnpm add / yarn add / bun add。

@godspeedai/cognate-events 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/godspeedai__cognate-events 是否存在。

@godspeedai/cognate-events 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@godspeedai/cognate-events 可以商用吗?

@godspeedai/cognate-events 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@godspeedai/cognate-events 的下载量有多少?

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

@godspeedai/cognate-events 还在维护吗?

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