@entifix/transactions 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,7 +14,7 @@ pnpm add @entifix/transactions effect
14
14
 
15
15
  | Import | What it holds |
16
16
  | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
17
- | `@entifix/transactions` | Command envelopes, transaction events, inbox / outbox / event-bus / lock / sequence / saga ports, `defineSaga`, the facade use case, `TransactionStreamHubTag` |
17
+ | `@entifix/transactions` | Command envelopes, transaction events, the unit of work, inbox / outbox / event-bus / lock / sequence / saga ports, `defineSaga`, the facade use case, `TransactionStreamHubTag` |
18
18
  | `@entifix/transactions/engine` | The mechanism behind those ports: `runSaga`, `resumeSaga`, `resumeStaleSagas` / `startSagaResume`, `acceptTransaction` / `completeTransaction`, `makeLocalSagaDispatcher`, the stream hub's factories |
19
19
 
20
20
  ---
@@ -54,10 +54,9 @@ export type InboxClaimResult = 'claimed' | 'duplicate';
54
54
  *
55
55
  * There is deliberately **no `claimWithin(session)` here**, for the reason
56
56
  * {@link TransactionOutbox} states about `enqueueWithin`: a driver session may
57
- * not enter a framework-free contract. The consumer owns that write, exactly as
58
- * a {@link TransactionHandler} owns the `completed` outbox entry — it holds the
59
- * session, it inserts the document {@link InboxClaim} describes, and this port
60
- * is what a consumer that can claim standalone uses instead.
57
+ * not enter a framework-free contract. A claim that must commit with its side
58
+ * effect is a {@link UnitOfWork}'s `event` claim (ADR 0009); this port is what
59
+ * a consumer that can claim standalone uses instead.
61
60
  *
62
61
  * It follows that **the inbox lives with the side effect, not in one central
63
62
  * place**: the claim and the write must be in the same database to be one fact.
@@ -1 +1 @@
1
- {"version":3,"file":"inbox.d.ts","sourceRoot":"","sources":["../../src/contracts/inbox.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,O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,wBAGf;CAAG"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/inbox.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * A consumer's claim on one delivered message.\n *\n * The mirror of an {@link OutboxEntry}: the outbox makes a publisher's event\n * survive a broker outage, the inbox makes a consumer's side effect survive a\n * redelivery. Each end owns one unique index, and the value in it is the same\n * `event.id`.\n */\nexport interface InboxClaim {\n /**\n * Which consumer claimed it — the subscription's durable work-queue name\n * (`<slice>.<pattern>`).\n *\n * **Half of the key, and the half that is easy to leave out.** Two consumers\n * legitimately process the same event: the saga tracker's fold and the SSE\n * hub both bind `transaction.*` today. Keyed on `eventId` alone, whichever\n * claimed first would starve the other of every message — a consumer that\n * silently stops working while the broker, the queue and the handler all\n * report success.\n */\n consumer: string;\n /**\n * The message's own id, which for a transaction step is\n * `<transactionId>:<step>`.\n *\n * Never `correlationId`: one transaction emits up to three messages, so\n * keying on the correlation id would make `completed` look like a\n * redelivery of `accepted`.\n */\n eventId: string;\n /** ISO-8601, for retention — nothing reads it to make a decision. */\n claimedAt: string;\n}\n\n/**\n * Whether {@link TransactionInbox.claim} actually wrote.\n *\n * `duplicate` is not a failure — it is how a **redelivery** is recognised, the\n * same way `OutboxEnqueueResult`'s `duplicate` recognises a replayed command.\n * Delivery is at-least-once by construction (a crash between `publish` and\n * `markSent` re-sends), so a consumer seeing this should skip its side effect\n * and ack, not error.\n */\nexport type InboxClaimResult = 'claimed' | 'duplicate';\n\n/**\n * The consumer-side half of exactly-once processing over an at-least-once bus.\n *\n * A claim is only worth anything if it is written **in the same storage\n * transaction as the side effect it guards**. Claim-then-act leaves a crash\n * window in which the claim is taken and the effect never ran, so the\n * redelivery is skipped and the work is lost — strictly worse than doing it\n * twice.\n *\n * There is deliberately **no `claimWithin(session)` here**, for the reason\n * {@link TransactionOutbox} states about `enqueueWithin`: a driver session may\n * not enter a framework-free contract. The consumer owns that write, exactly as\n * a {@link TransactionHandler} owns the `completed` outbox entry — it holds the\n * session, it inserts the document {@link InboxClaim} describes, and this port\n * is what a consumer that can claim standalone uses instead.\n *\n * It follows that **the inbox lives with the side effect, not in one central\n * place**: the claim and the write must be in the same database to be one fact.\n * The outbox is per-tenant because the entity is; the saga tracker's inbox is in\n * the `saga` database because that is where its fold writes.\n */\nexport interface TransactionInbox {\n /**\n * Claim an event for this consumer. Idempotent per `(consumer, eventId)`.\n *\n * Answering `duplicate` means some earlier delivery already ran the side\n * effect to completion, because the claim and the effect commit together.\n */\n claim(eventId: string): Effect.Effect<InboxClaimResult, EntifixConnError>;\n}\n\nexport class TransactionInboxTag extends Context.Service<\n TransactionInboxTag,\n TransactionInbox\n>()('TransactionInboxTag') {}\n"],"names":["Context","TransactionInboxTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AA8E9C,OAAO,MAAMC,4BAA4BD,QAAQE,OAAO,GAGpD;AAAwB"}
1
+ {"version":3,"sources":["../../src/contracts/inbox.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * A consumer's claim on one delivered message.\n *\n * The mirror of an {@link OutboxEntry}: the outbox makes a publisher's event\n * survive a broker outage, the inbox makes a consumer's side effect survive a\n * redelivery. Each end owns one unique index, and the value in it is the same\n * `event.id`.\n */\nexport interface InboxClaim {\n /**\n * Which consumer claimed it — the subscription's durable work-queue name\n * (`<slice>.<pattern>`).\n *\n * **Half of the key, and the half that is easy to leave out.** Two consumers\n * legitimately process the same event: the saga tracker's fold and the SSE\n * hub both bind `transaction.*` today. Keyed on `eventId` alone, whichever\n * claimed first would starve the other of every message — a consumer that\n * silently stops working while the broker, the queue and the handler all\n * report success.\n */\n consumer: string;\n /**\n * The message's own id, which for a transaction step is\n * `<transactionId>:<step>`.\n *\n * Never `correlationId`: one transaction emits up to three messages, so\n * keying on the correlation id would make `completed` look like a\n * redelivery of `accepted`.\n */\n eventId: string;\n /** ISO-8601, for retention — nothing reads it to make a decision. */\n claimedAt: string;\n}\n\n/**\n * Whether {@link TransactionInbox.claim} actually wrote.\n *\n * `duplicate` is not a failure — it is how a **redelivery** is recognised, the\n * same way `OutboxEnqueueResult`'s `duplicate` recognises a replayed command.\n * Delivery is at-least-once by construction (a crash between `publish` and\n * `markSent` re-sends), so a consumer seeing this should skip its side effect\n * and ack, not error.\n */\nexport type InboxClaimResult = 'claimed' | 'duplicate';\n\n/**\n * The consumer-side half of exactly-once processing over an at-least-once bus.\n *\n * A claim is only worth anything if it is written **in the same storage\n * transaction as the side effect it guards**. Claim-then-act leaves a crash\n * window in which the claim is taken and the effect never ran, so the\n * redelivery is skipped and the work is lost — strictly worse than doing it\n * twice.\n *\n * There is deliberately **no `claimWithin(session)` here**, for the reason\n * {@link TransactionOutbox} states about `enqueueWithin`: a driver session may\n * not enter a framework-free contract. A claim that must commit with its side\n * effect is a {@link UnitOfWork}'s `event` claim (ADR 0009); this port is what\n * a consumer that can claim standalone uses instead.\n *\n * It follows that **the inbox lives with the side effect, not in one central\n * place**: the claim and the write must be in the same database to be one fact.\n * The outbox is per-tenant because the entity is; the saga tracker's inbox is in\n * the `saga` database because that is where its fold writes.\n */\nexport interface TransactionInbox {\n /**\n * Claim an event for this consumer. Idempotent per `(consumer, eventId)`.\n *\n * Answering `duplicate` means some earlier delivery already ran the side\n * effect to completion, because the claim and the effect commit together.\n */\n claim(eventId: string): Effect.Effect<InboxClaimResult, EntifixConnError>;\n}\n\nexport class TransactionInboxTag extends Context.Service<\n TransactionInboxTag,\n TransactionInbox\n>()('TransactionInboxTag') {}\n"],"names":["Context","TransactionInboxTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AA6E9C,OAAO,MAAMC,4BAA4BD,QAAQE,OAAO,GAGpD;AAAwB"}
@@ -88,11 +88,11 @@ export interface OutboxStats {
88
88
  * {@link EventBus} — which is what keeps the engine framework-free and lets the
89
89
  * relay be tested without either a database or a broker.
90
90
  *
91
- * There is no `enqueueWithin(session)` here on purpose. Making the `completed`
92
- * entry atomic with the entity write needs the storage driver's own session, and
93
- * putting one in this port (or in `EntityRepository`) would drag Mongo into a
94
- * framework-free contract. The handler owns that write instead — see
95
- * {@link TransactionHandler}.
91
+ * There is no `enqueueWithin(session)` here on purpose: a driver session in
92
+ * this port would drag a datastore into a framework-free contract. A write that
93
+ * must be atomic with its event runs in a {@link UnitOfWork} instead, whose
94
+ * handle is opaque and whose `emit` records the event inside the same
95
+ * transaction (ADR 0009). `enqueue` is for an event with no write to join.
96
96
  */
97
97
  export interface TransactionOutbox {
98
98
  /** Record an event durably. Idempotent per `event.id`. */
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/outbox.ts"],"sourcesContent":["import type { DomainEvent, EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * A transaction event recorded durably *before* it reaches the broker.\n *\n * The point of the outbox is that a state change and the event announcing it\n * become one fact. `execute` used to write Mongo and then call `bus.publish`\n * separately: with the broker down between the two, the write happened and the\n * event never did, so the saga record sat `PENDING` until the sweep mislabelled\n * a successful transaction `STALE`. An entry written in the same transaction as\n * the state change cannot be lost that way, and a relay carries it to the bus\n * afterwards.\n */\nexport interface OutboxEntry {\n /**\n * The message's own id, denormalized out of `event` so the unique index sits\n * on a plain top-level field rather than a nested path.\n *\n * This **is** the idempotency claim: for a transaction step it is\n * `<transactionId>:<step>`, so a replayed command collides here and is\n * recognised as a retry before any lock is taken or work forked.\n */\n eventId: string;\n event: DomainEvent;\n sent: boolean;\n /**\n * Publish attempts already spent on this entry.\n *\n * The relay drains in order and stops at the first failure, which is what\n * keeps `accepted` ahead of a terminal event — and is also why an entry that\n * can *never* publish used to block everything behind it forever. Counting\n * the attempts is what turns \"retrying\" into a state with an end.\n */\n attempts: number;\n /**\n * Why the last attempt failed. Absent until one has, so its presence alone\n * says this entry has been tried.\n */\n lastError?: string;\n /**\n * Set once the attempts are spent. A quarantined entry is **skipped** rather\n * than retried, so the head of the line moves; nothing deletes it, because a\n * stuck transaction nobody is told about is the same as a lost one.\n */\n quarantined: boolean;\n /** ISO-8601, and the drain order: entries publish oldest-first. */\n createdAt: string;\n}\n\n/**\n * Whether {@link TransactionOutbox.enqueue} actually wrote.\n *\n * `duplicate` is not a failure — it is how a *retry* is recognised. The\n * transaction id is the client's idempotency key, so a repeated\n * command must return the first one's answer rather than execute twice. The\n * adapter owns the detection because the mechanism is storage-specific (a Mongo\n * `E11000` against the unique index on `eventId`), and translating it here keeps\n * driver error codes out of route handlers.\n */\nexport type OutboxEnqueueResult = 'enqueued' | 'duplicate';\n\n/**\n * An aggregate view of one outbox, for {@link TransactionOutbox.stats}.\n *\n * Counts and one timestamp — **no ids and no payloads**. That is what makes it\n * safe where a listing is not: an outbox holds event payloads, and once\n * `catalog.published` carries a whole offering an unfiltered read of one is a\n * tenant-data surface.\n */\nexport interface OutboxStats {\n /** Unsent, un-quarantined entries — the same set {@link pending} drains. */\n pending: number;\n /**\n * `createdAt` of the oldest such entry, absent when there are none.\n *\n * The age derived from this is the metric that makes a stuck relay visible.\n * An entry that can never publish no longer blocks the ones behind it —\n * quarantine gave the relay a ceiling — but a quarantine is reported only as a log line,\n * so *how far behind* the head has fallen is otherwise unanswerable.\n */\n oldestPendingAt?: string;\n /** Entries past the ceiling, which {@link pending} skips and nothing deletes. */\n quarantined: number;\n}\n\n/**\n * The durable hand-off between a transactional write and the event bus.\n *\n * Deliberately **not** a publisher: it never touches the broker. `enqueue` is\n * the only write, and the relay composes `pending`/`markSent` with an\n * {@link EventBus} — which is what keeps the engine framework-free and lets the\n * relay be tested without either a database or a broker.\n *\n * There is no `enqueueWithin(session)` here on purpose. Making the `completed`\n * entry atomic with the entity write needs the storage driver's own session, and\n * putting one in this port (or in `EntityRepository`) would drag Mongo into a\n * framework-free contract. The handler owns that write instead — see\n * {@link TransactionHandler}.\n */\nexport interface TransactionOutbox {\n /** Record an event durably. Idempotent per `event.id`. */\n enqueue(\n event: DomainEvent,\n ): Effect.Effect<OutboxEnqueueResult, EntifixConnError>;\n /**\n * Unsent, un-quarantined entries, oldest first — the relay's input.\n *\n * Excluding the quarantined ones here rather than in the relay is deliberate:\n * a skip the caller has to remember is a skip the next caller forgets.\n */\n pending(\n limit: number,\n ): Effect.Effect<readonly OutboxEntry[], EntifixConnError>;\n /**\n * Mark an entry published. A crash between the publish and this call re-sends\n * the event on the next drain, which is why delivery is at-least-once and why\n * a consumer that must not fold twice dedupes on `event.id`.\n */\n markSent(entry: OutboxEntry): Effect.Effect<void, EntifixConnError>;\n /**\n * Record a failed publish: increments `attempts` and stores `error`.\n *\n * `quarantine` is the caller's decision rather than the adapter's, because\n * the ceiling is configuration the relay reads and the store has no business\n * knowing it. Once set, {@link pending} must stop returning the entry — that\n * is the whole mechanism by which the queue's head moves.\n */\n recordFailure(\n entry: OutboxEntry,\n error: string,\n quarantine: boolean,\n ): Effect.Effect<void, EntifixConnError>;\n /**\n * Depth and age, for the relay to sample once per sweep.\n *\n * An aggregate rather than a read, deliberately: `pending(limit)` truncates at\n * the relay's batch size, so counting what it returns answers \"is the batch\n * full\" and not \"how far behind are we\" — which are the same number right up\n * to the moment the second one starts to matter.\n */\n stats(): Effect.Effect<OutboxStats, EntifixConnError>;\n}\n\nexport class TransactionOutboxTag extends Context.Service<\n TransactionOutboxTag,\n TransactionOutbox\n>()('TransactionOutboxTag') {}\n"],"names":["Context","TransactionOutboxTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AA+I9C,OAAO,MAAMC,6BAA6BD,QAAQE,OAAO,GAGrD;AAAyB"}
1
+ {"version":3,"sources":["../../src/contracts/outbox.ts"],"sourcesContent":["import type { DomainEvent, EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * A transaction event recorded durably *before* it reaches the broker.\n *\n * The point of the outbox is that a state change and the event announcing it\n * become one fact. `execute` used to write Mongo and then call `bus.publish`\n * separately: with the broker down between the two, the write happened and the\n * event never did, so the saga record sat `PENDING` until the sweep mislabelled\n * a successful transaction `STALE`. An entry written in the same transaction as\n * the state change cannot be lost that way, and a relay carries it to the bus\n * afterwards.\n */\nexport interface OutboxEntry {\n /**\n * The message's own id, denormalized out of `event` so the unique index sits\n * on a plain top-level field rather than a nested path.\n *\n * This **is** the idempotency claim: for a transaction step it is\n * `<transactionId>:<step>`, so a replayed command collides here and is\n * recognised as a retry before any lock is taken or work forked.\n */\n eventId: string;\n event: DomainEvent;\n sent: boolean;\n /**\n * Publish attempts already spent on this entry.\n *\n * The relay drains in order and stops at the first failure, which is what\n * keeps `accepted` ahead of a terminal event — and is also why an entry that\n * can *never* publish used to block everything behind it forever. Counting\n * the attempts is what turns \"retrying\" into a state with an end.\n */\n attempts: number;\n /**\n * Why the last attempt failed. Absent until one has, so its presence alone\n * says this entry has been tried.\n */\n lastError?: string;\n /**\n * Set once the attempts are spent. A quarantined entry is **skipped** rather\n * than retried, so the head of the line moves; nothing deletes it, because a\n * stuck transaction nobody is told about is the same as a lost one.\n */\n quarantined: boolean;\n /** ISO-8601, and the drain order: entries publish oldest-first. */\n createdAt: string;\n}\n\n/**\n * Whether {@link TransactionOutbox.enqueue} actually wrote.\n *\n * `duplicate` is not a failure — it is how a *retry* is recognised. The\n * transaction id is the client's idempotency key, so a repeated\n * command must return the first one's answer rather than execute twice. The\n * adapter owns the detection because the mechanism is storage-specific (a Mongo\n * `E11000` against the unique index on `eventId`), and translating it here keeps\n * driver error codes out of route handlers.\n */\nexport type OutboxEnqueueResult = 'enqueued' | 'duplicate';\n\n/**\n * An aggregate view of one outbox, for {@link TransactionOutbox.stats}.\n *\n * Counts and one timestamp — **no ids and no payloads**. That is what makes it\n * safe where a listing is not: an outbox holds event payloads, and once\n * `catalog.published` carries a whole offering an unfiltered read of one is a\n * tenant-data surface.\n */\nexport interface OutboxStats {\n /** Unsent, un-quarantined entries — the same set {@link pending} drains. */\n pending: number;\n /**\n * `createdAt` of the oldest such entry, absent when there are none.\n *\n * The age derived from this is the metric that makes a stuck relay visible.\n * An entry that can never publish no longer blocks the ones behind it —\n * quarantine gave the relay a ceiling — but a quarantine is reported only as a log line,\n * so *how far behind* the head has fallen is otherwise unanswerable.\n */\n oldestPendingAt?: string;\n /** Entries past the ceiling, which {@link pending} skips and nothing deletes. */\n quarantined: number;\n}\n\n/**\n * The durable hand-off between a transactional write and the event bus.\n *\n * Deliberately **not** a publisher: it never touches the broker. `enqueue` is\n * the only write, and the relay composes `pending`/`markSent` with an\n * {@link EventBus} — which is what keeps the engine framework-free and lets the\n * relay be tested without either a database or a broker.\n *\n * There is no `enqueueWithin(session)` here on purpose: a driver session in\n * this port would drag a datastore into a framework-free contract. A write that\n * must be atomic with its event runs in a {@link UnitOfWork} instead, whose\n * handle is opaque and whose `emit` records the event inside the same\n * transaction (ADR 0009). `enqueue` is for an event with no write to join.\n */\nexport interface TransactionOutbox {\n /** Record an event durably. Idempotent per `event.id`. */\n enqueue(\n event: DomainEvent,\n ): Effect.Effect<OutboxEnqueueResult, EntifixConnError>;\n /**\n * Unsent, un-quarantined entries, oldest first — the relay's input.\n *\n * Excluding the quarantined ones here rather than in the relay is deliberate:\n * a skip the caller has to remember is a skip the next caller forgets.\n */\n pending(\n limit: number,\n ): Effect.Effect<readonly OutboxEntry[], EntifixConnError>;\n /**\n * Mark an entry published. A crash between the publish and this call re-sends\n * the event on the next drain, which is why delivery is at-least-once and why\n * a consumer that must not fold twice dedupes on `event.id`.\n */\n markSent(entry: OutboxEntry): Effect.Effect<void, EntifixConnError>;\n /**\n * Record a failed publish: increments `attempts` and stores `error`.\n *\n * `quarantine` is the caller's decision rather than the adapter's, because\n * the ceiling is configuration the relay reads and the store has no business\n * knowing it. Once set, {@link pending} must stop returning the entry — that\n * is the whole mechanism by which the queue's head moves.\n */\n recordFailure(\n entry: OutboxEntry,\n error: string,\n quarantine: boolean,\n ): Effect.Effect<void, EntifixConnError>;\n /**\n * Depth and age, for the relay to sample once per sweep.\n *\n * An aggregate rather than a read, deliberately: `pending(limit)` truncates at\n * the relay's batch size, so counting what it returns answers \"is the batch\n * full\" and not \"how far behind are we\" — which are the same number right up\n * to the moment the second one starts to matter.\n */\n stats(): Effect.Effect<OutboxStats, EntifixConnError>;\n}\n\nexport class TransactionOutboxTag extends Context.Service<\n TransactionOutboxTag,\n TransactionOutbox\n>()('TransactionOutboxTag') {}\n"],"names":["Context","TransactionOutboxTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AA+I9C,OAAO,MAAMC,6BAA6BD,QAAQE,OAAO,GAGrD;AAAyB"}
@@ -0,0 +1,112 @@
1
+ import type { DomainEvent, EntifixConnError } from '@entifix/core';
2
+ import type { Effect, Option } from 'effect';
3
+ /**
4
+ * What a unit of work deduplicates on, if anything. At most one per unit.
5
+ *
6
+ * Two kinds, because there are two directions a duplicate arrives from:
7
+ *
8
+ * - `event` — a consumer folding a bus message. Keyed on `(consumer, eventId)`,
9
+ * the inbox's compound key: two consumers legitimately process one event,
10
+ * and a key on `eventId` alone would let whichever claimed first starve the
11
+ * other.
12
+ * - `command` — a participant answering a dispatched command. Keyed on the
13
+ * command id alone, and it **remembers an answer**: a redelivered command must
14
+ * be told what the first delivery decided, not that it was a duplicate.
15
+ */
16
+ export type UnitClaim = {
17
+ readonly kind: 'event';
18
+ readonly consumer: string;
19
+ readonly eventId: string;
20
+ } | {
21
+ readonly kind: 'command';
22
+ readonly commandId: string;
23
+ };
24
+ /**
25
+ * The view a unit's body gets of the transaction it runs in.
26
+ *
27
+ * `handle` is the store's own — a driver session and the database it is bound
28
+ * to, for Mongo. It is opaque to this package on purpose: the contract states
29
+ * what commits together, and only the adapter that implements it (and the
30
+ * persistence code written against that adapter) ever looks inside.
31
+ */
32
+ export interface Unit<H> {
33
+ readonly handle: H;
34
+ /**
35
+ * Record an event to publish **if and only if** the unit commits.
36
+ *
37
+ * Recorded, not published. The adapter writes it to the outbox inside the
38
+ * same transaction, so the state change and its announcement are one fact,
39
+ * and the relay carries it to the bus afterwards.
40
+ */
41
+ emit(event: DomainEvent): void;
42
+ }
43
+ /**
44
+ * How a unit ended. A failure of the store itself is not one of these — it is
45
+ * the `EntifixConnError` in the error channel of {@link UnitOfWork.run}.
46
+ *
47
+ * - `committed` — every write, every event and the claim are durable.
48
+ * - `duplicate` — the claim was already taken, so the body's work had already
49
+ * committed once. Nothing was written. `replay` is what the first run asked
50
+ * to be remembered (`command` claims only).
51
+ * - `aborted` — the body failed with a business reason. Nothing was written.
52
+ * This is how a refusal leaves a unit: as a typed value, never as a thrown
53
+ * sentinel caught three frames up.
54
+ */
55
+ export type UnitOutcome<A, E> = {
56
+ readonly _tag: 'committed';
57
+ readonly value: A;
58
+ } | {
59
+ readonly _tag: 'duplicate';
60
+ readonly replay: Option.Option<unknown>;
61
+ } | {
62
+ readonly _tag: 'aborted';
63
+ readonly reason: E;
64
+ };
65
+ export interface UnitRunOptions<A, R = never> {
66
+ readonly claim?: UnitClaim;
67
+ /**
68
+ * What a later duplicate of this `command` claim is answered with, derived
69
+ * from the committed value. Stored with the claim, in the same transaction.
70
+ *
71
+ * It must be JSON: it is written to the store and read back by a different
72
+ * process, possibly after a restart.
73
+ */
74
+ readonly replay?: (value: A) => unknown;
75
+ /**
76
+ * Runs once the unit has committed, and never otherwise — the place to drain
77
+ * the outbox inline so the event leaves now rather than at the next sweep.
78
+ *
79
+ * Its failure does not undo the commit, and is not reported as the unit's: a
80
+ * drain that fails here is retried by the sweep, which is exactly the
81
+ * fallback the outbox exists to provide.
82
+ */
83
+ readonly afterCommit?: Effect.Effect<void, unknown, R>;
84
+ }
85
+ /**
86
+ * One storage transaction that the outbox, the inbox and a command claim all
87
+ * join: domain writes, zero or more events, and at most one claim, which commit
88
+ * or vanish together.
89
+ *
90
+ * The body may run **more than once**. A store that retries a transient
91
+ * conflict re-runs it from the start, so the body must be a pure function of
92
+ * its inputs and the handle — no clock read that has to match a value already
93
+ * returned, no call to another service, no counter drawn from outside the
94
+ * store. Do those before the unit and pass the results in.
95
+ *
96
+ * The body's typed failure is the abort: `run` rolls back and answers
97
+ * `aborted` with it. An `EntifixConnError` is the exception — the store failing
98
+ * is not a business decision, so it rolls back and surfaces in `run`'s own
99
+ * error channel instead.
100
+ *
101
+ * Reads through the handle see the unit's own uncommitted writes.
102
+ */
103
+ export interface UnitOfWork<H> {
104
+ run<A, E, R>(body: (unit: Unit<H>) => Effect.Effect<A, E, R>, options?: UnitRunOptions<A, R>): Effect.Effect<UnitOutcome<A, Exclude<E, EntifixConnError>>, EntifixConnError, R>;
105
+ /**
106
+ * What the run that took this `command` claim asked to be remembered, or
107
+ * `none` if no run has taken it — for a caller that has to answer a duplicate
108
+ * outside a unit.
109
+ */
110
+ replay(commandId: string): Effect.Effect<Option.Option<unknown>, EntifixConnError>;
111
+ }
112
+ //# sourceMappingURL=unit-of-work.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unit-of-work.d.ts","sourceRoot":"","sources":["../../src/contracts/unit-of-work.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACnE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE7C;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,SAAS,GACjB;IACE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CAC1B,GACD;IAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC;AAE7D;;;;;;;GAOG;AACH,MAAM,WAAW,IAAI,CAAC,CAAC;IACrB,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;IACnB;;;;;;OAMG;IACH,IAAI,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI,CAAC;CAChC;AAED;;;;;;;;;;;GAWG;AACH,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M,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,gBAAgB,CAAC,CAAC;CAC5D"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * One storage transaction that the outbox, the inbox and a command claim all
3
+ * join: domain writes, zero or more events, and at most one claim, which commit
4
+ * or vanish together.
5
+ *
6
+ * The body may run **more than once**. A store that retries a transient
7
+ * conflict re-runs it from the start, so the body must be a pure function of
8
+ * its inputs and the handle — no clock read that has to match a value already
9
+ * returned, no call to another service, no counter drawn from outside the
10
+ * store. Do those before the unit and pass the results in.
11
+ *
12
+ * The body's typed failure is the abort: `run` rolls back and answers
13
+ * `aborted` with it. An `EntifixConnError` is the exception — the store failing
14
+ * is not a business decision, so it rolls back and surfaces in `run`'s own
15
+ * error channel instead.
16
+ *
17
+ * Reads through the handle see the unit's own uncommitted writes.
18
+ */ export { };
19
+
20
+ //# sourceMappingURL=unit-of-work.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/contracts/unit-of-work.ts"],"sourcesContent":["import type { DomainEvent, EntifixConnError } from '@entifix/core';\nimport type { Effect, Option } from 'effect';\n\n/**\n * What a unit of work deduplicates on, if anything. At most one per unit.\n *\n * Two kinds, because there are two directions a duplicate arrives from:\n *\n * - `event` — a consumer folding a bus message. Keyed on `(consumer, eventId)`,\n * the inbox's compound key: two consumers legitimately process one event,\n * and a key on `eventId` alone would let whichever claimed first starve the\n * other.\n * - `command` — a participant answering a dispatched command. Keyed on the\n * command id alone, and it **remembers an answer**: a redelivered command must\n * be told what the first delivery decided, not that it was a duplicate.\n */\nexport type UnitClaim =\n | {\n readonly kind: 'event';\n readonly consumer: string;\n readonly eventId: string;\n }\n | { readonly kind: 'command'; readonly commandId: string };\n\n/**\n * The view a unit's body gets of the transaction it runs in.\n *\n * `handle` is the store's own — a driver session and the database it is bound\n * to, for Mongo. It is opaque to this package on purpose: the contract states\n * what commits together, and only the adapter that implements it (and the\n * persistence code written against that adapter) ever looks inside.\n */\nexport interface Unit<H> {\n readonly handle: H;\n /**\n * Record an event to publish **if and only if** the unit commits.\n *\n * Recorded, not published. The adapter writes it to the outbox inside the\n * same transaction, so the state change and its announcement are one fact,\n * and the relay carries it to the bus afterwards.\n */\n emit(event: DomainEvent): void;\n}\n\n/**\n * How a unit ended. A failure of the store itself is not one of these — it is\n * the `EntifixConnError` in the error channel of {@link UnitOfWork.run}.\n *\n * - `committed` — every write, every event and the claim are durable.\n * - `duplicate` — the claim was already taken, so the body's work had already\n * committed once. Nothing was written. `replay` is what the first run asked\n * to be remembered (`command` claims only).\n * - `aborted` — the body failed with a business reason. Nothing was written.\n * This is how a refusal leaves a unit: as a typed value, never as a thrown\n * sentinel caught three frames up.\n */\nexport type UnitOutcome<A, E> =\n | { readonly _tag: 'committed'; readonly value: A }\n | { readonly _tag: 'duplicate'; readonly replay: Option.Option<unknown> }\n | { readonly _tag: 'aborted'; readonly reason: E };\n\nexport interface UnitRunOptions<A, R = never> {\n readonly claim?: UnitClaim;\n /**\n * What a later duplicate of this `command` claim is answered with, derived\n * from the committed value. Stored with the claim, in the same transaction.\n *\n * It must be JSON: it is written to the store and read back by a different\n * process, possibly after a restart.\n */\n readonly replay?: (value: A) => unknown;\n /**\n * Runs once the unit has committed, and never otherwise — the place to drain\n * the outbox inline so the event leaves now rather than at the next sweep.\n *\n * Its failure does not undo the commit, and is not reported as the unit's: a\n * drain that fails here is retried by the sweep, which is exactly the\n * fallback the outbox exists to provide.\n */\n readonly afterCommit?: Effect.Effect<void, unknown, R>;\n}\n\n/**\n * One storage transaction that the outbox, the inbox and a command claim all\n * join: domain writes, zero or more events, and at most one claim, which commit\n * or vanish together.\n *\n * The body may run **more than once**. A store that retries a transient\n * conflict re-runs it from the start, so the body must be a pure function of\n * its inputs and the handle — no clock read that has to match a value already\n * returned, no call to another service, no counter drawn from outside the\n * store. Do those before the unit and pass the results in.\n *\n * The body's typed failure is the abort: `run` rolls back and answers\n * `aborted` with it. An `EntifixConnError` is the exception — the store failing\n * is not a business decision, so it rolls back and surfaces in `run`'s own\n * error channel instead.\n *\n * Reads through the handle see the unit's own uncommitted writes.\n */\nexport interface UnitOfWork<H> {\n run<A, E, R>(\n body: (unit: Unit<H>) => Effect.Effect<A, E, R>,\n options?: UnitRunOptions<A, R>,\n ): Effect.Effect<\n UnitOutcome<A, Exclude<E, EntifixConnError>>,\n EntifixConnError,\n R\n >;\n /**\n * What the run that took this `command` claim asked to be remembered, or\n * `none` if no run has taken it — for a caller that has to answer a duplicate\n * outside a unit.\n */\n replay(\n commandId: string,\n ): Effect.Effect<Option.Option<unknown>, EntifixConnError>;\n}\n"],"names":[],"mappings":"AAkFA;;;;;;;;;;;;;;;;;CAiBC,GACD,WAiBC"}
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@ export * from './contracts/inbox.js';
4
4
  export * from './contracts/outbox.js';
5
5
  export * from './contracts/record.js';
6
6
  export * from './contracts/saga-definition.js';
7
+ export * from './contracts/unit-of-work.js';
7
8
  export * from './mixins/transaction-mixins.js';
8
9
  export * from './ports/event-bus.js';
9
10
  export * from './ports/event-source.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,uBAAuB,CAAC;AACtC,cAAc,uBAAuB,CAAC;AACtC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,yBAAyB,CAAC;AACxC,cAAc,yBAAyB,CAAC;AACxC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,mCAAmC,CAAC;AAClD,cAAc,yBAAyB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,uBAAuB,CAAC;AACtC,cAAc,uBAAuB,CAAC;AACtC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,yBAAyB,CAAC;AACxC,cAAc,yBAAyB,CAAC;AACxC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,mCAAmC,CAAC;AAClD,cAAc,yBAAyB,CAAC"}
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ export * from './contracts/inbox.js';
4
4
  export * from './contracts/outbox.js';
5
5
  export * from './contracts/record.js';
6
6
  export * from './contracts/saga-definition.js';
7
+ export * from './contracts/unit-of-work.js';
7
8
  export * from './mixins/transaction-mixins.js';
8
9
  export * from './ports/event-bus.js';
9
10
  export * from './ports/event-source.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './contracts/command.js';\nexport * from './contracts/event.js';\nexport * from './contracts/inbox.js';\nexport * from './contracts/outbox.js';\nexport * from './contracts/record.js';\nexport * from './contracts/saga-definition.js';\nexport * from './mixins/transaction-mixins.js';\nexport * from './ports/event-bus.js';\nexport * from './ports/event-source.js';\nexport * from './ports/lock-service.js';\nexport * from './ports/saga-dispatcher.js';\nexport * from './ports/saga-store.js';\nexport * from './ports/sequence-service.js';\nexport * from './ports/transaction-handler.js';\nexport * from './ports/transaction-sink.js';\nexport * from './ports/transaction-stream-hub.js';\nexport * from './use-case/facade.uc.js';\n"],"names":[],"mappings":"AAAA,cAAc,yBAAyB;AACvC,cAAc,uBAAuB;AACrC,cAAc,uBAAuB;AACrC,cAAc,wBAAwB;AACtC,cAAc,wBAAwB;AACtC,cAAc,iCAAiC;AAC/C,cAAc,iCAAiC;AAC/C,cAAc,uBAAuB;AACrC,cAAc,0BAA0B;AACxC,cAAc,0BAA0B;AACxC,cAAc,6BAA6B;AAC3C,cAAc,wBAAwB;AACtC,cAAc,8BAA8B;AAC5C,cAAc,iCAAiC;AAC/C,cAAc,8BAA8B;AAC5C,cAAc,oCAAoC;AAClD,cAAc,0BAA0B"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './contracts/command.js';\nexport * from './contracts/event.js';\nexport * from './contracts/inbox.js';\nexport * from './contracts/outbox.js';\nexport * from './contracts/record.js';\nexport * from './contracts/saga-definition.js';\nexport * from './contracts/unit-of-work.js';\nexport * from './mixins/transaction-mixins.js';\nexport * from './ports/event-bus.js';\nexport * from './ports/event-source.js';\nexport * from './ports/lock-service.js';\nexport * from './ports/saga-dispatcher.js';\nexport * from './ports/saga-store.js';\nexport * from './ports/sequence-service.js';\nexport * from './ports/transaction-handler.js';\nexport * from './ports/transaction-sink.js';\nexport * from './ports/transaction-stream-hub.js';\nexport * from './use-case/facade.uc.js';\n"],"names":[],"mappings":"AAAA,cAAc,yBAAyB;AACvC,cAAc,uBAAuB;AACrC,cAAc,uBAAuB;AACrC,cAAc,wBAAwB;AACtC,cAAc,wBAAwB;AACtC,cAAc,iCAAiC;AAC/C,cAAc,8BAA8B;AAC5C,cAAc,iCAAiC;AAC/C,cAAc,uBAAuB;AACrC,cAAc,0BAA0B;AACxC,cAAc,0BAA0B;AACxC,cAAc,6BAA6B;AAC3C,cAAc,wBAAwB;AACtC,cAAc,8BAA8B;AAC5C,cAAc,iCAAiC;AAC/C,cAAc,8BAA8B;AAC5C,cAAc,oCAAoC;AAClD,cAAc,0BAA0B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/transactions",
3
- "version": "0.7.1",
3
+ "version": "0.8.0",
4
4
  "description": "Commands, transactions and sagas: inbox and outbox ports, an event bus, locks, and a declarative saga runner.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -56,8 +56,8 @@
56
56
  },
57
57
  "dependencies": {
58
58
  "@swc/helpers": "0.5.23",
59
- "@entifix/business": "0.7.1",
60
- "@entifix/core": "0.7.1"
59
+ "@entifix/business": "0.8.0",
60
+ "@entifix/core": "0.8.0"
61
61
  },
62
62
  "peerDependencies": {
63
63
  "effect": "^4.0.5"