burying-beetle - v0.1.0
    Preparing search index...

    burying-beetle - v0.1.0

    burying-beetle

    Burying beetle logo

    Decides, per entity, whether an event is newer than what you already applied, and keeps deleted entities deleted when their events arrive out of order. Works on any event stream: webhooks, queue messages, change-data-capture rows.

    Requires Node 22 or later, or Bun. No runtime dependencies.

    npm install burying-beetle
    
    import { Guard, MemoryStore } from "burying-beetle";

    const guard = new Guard({ store: new MemoryStore({ maxEntries: 100_000 }) });

    const decision = await guard.advance({
    scope: "github:octo/repo",
    id: issue.node_id,
    version: [Date.parse(issue.updated_at), 0],
    kind: action === "deleted" ? "delete" : "write",
    });
    if (decision === "apply") await save(issue);
    // "stale": something newer was applied. "deleted": the entity is gone.

    You read four values out of your own payload: a scope, an ID, a version and whether it is a delete. A version is a non-negative integer, a bigint, or a tuple of them compared left to right. Strings are refused; turn dates into numbers.

    MemoryStore is for one process. For more than one, implement Store (one atomic method) and run checkStore against it. guides/postgres.md has a Postgres store that runs inside your own transaction.

    By default a deleted entity never comes back and its tombstone is kept forever. Two options loosen that, and both are named unsafe*, so grep -rnE "unsafe[A-Z]" . finds them:

    • unsafeAllowRecreate: true: a write at or above the delete's version brings the entity back, for IDs that get reused.
    • unsafeTombstoneExpiry: tombstones count as absent after this many milliseconds, and any later event brings the entity back.

    Not included:

    • Checking who sent the event. Use fishhook-ant.
    • Running a handler once per retried event. Use mycocepurus-smithii.
    • Buffering events until a gap closes. That needs contiguous sequence numbers and durable storage; use a queue.
    • Database drivers. The Postgres store is a file to copy.
    • Equal versions apply. A sender's retry is applied again, and two different events with the same version both apply, the later arrival last. GitHub's updated_at is to the second and comes with nothing to break a tie.
    • A delete that arrives before the entity's first write still leaves a tombstone, so the write is deleted.
    • MemoryStore refuses a new entity with store-full once it holds maxEntries records. It never evicts, because evicting a tombstone would bring an entity back.

    ISC.

    Burying beetles (Nicrophorus) find a dead animal and bury it, and it stays buried. This library keeps deleted entities in the ground when a late update tries to dig them back up. It is the sibling of fishhook-ant, from the same project's webhook handlers.