@entifix/testing-unit 0.10.1 → 0.11.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/dist/contracts/flow-engine.contract.d.ts +16 -0
- package/dist/contracts/flow-engine.contract.d.ts.map +1 -0
- package/dist/contracts/flow-engine.contract.js +163 -0
- package/dist/contracts/flow-engine.contract.js.map +1 -0
- package/dist/contracts/idempotency-store.contract.d.ts +17 -0
- package/dist/contracts/idempotency-store.contract.d.ts.map +1 -0
- package/dist/contracts/idempotency-store.contract.js +94 -0
- package/dist/contracts/idempotency-store.contract.js.map +1 -0
- package/dist/contracts/index.d.ts +4 -0
- package/dist/contracts/index.d.ts.map +1 -1
- package/dist/contracts/index.js +4 -0
- package/dist/contracts/index.js.map +1 -1
- package/dist/contracts/outbox.contract.d.ts +18 -0
- package/dist/contracts/outbox.contract.d.ts.map +1 -0
- package/dist/contracts/outbox.contract.js +117 -0
- package/dist/contracts/outbox.contract.js.map +1 -0
- package/dist/contracts/transaction-ports.contract.d.ts +1 -1
- package/dist/contracts/transaction-ports.contract.d.ts.map +1 -1
- package/dist/contracts/transaction-ports.contract.js +10 -1
- package/dist/contracts/transaction-ports.contract.js.map +1 -1
- package/dist/contracts/unit-of-work.contract.d.ts.map +1 -1
- package/dist/contracts/unit-of-work.contract.js +5 -0
- package/dist/contracts/unit-of-work.contract.js.map +1 -1
- package/dist/contracts/variants.contract.d.ts +15 -0
- package/dist/contracts/variants.contract.d.ts.map +1 -0
- package/dist/contracts/variants.contract.js +39 -0
- package/dist/contracts/variants.contract.js.map +1 -0
- package/dist/doubles/flow-engine.d.ts +22 -0
- package/dist/doubles/flow-engine.d.ts.map +1 -0
- package/dist/doubles/flow-engine.js +137 -0
- package/dist/doubles/flow-engine.js.map +1 -0
- package/dist/doubles/idempotency-store.d.ts +12 -0
- package/dist/doubles/idempotency-store.d.ts.map +1 -0
- package/dist/doubles/idempotency-store.js +40 -0
- package/dist/doubles/idempotency-store.js.map +1 -0
- package/dist/doubles/outbox.d.ts +15 -0
- package/dist/doubles/outbox.d.ts.map +1 -0
- package/dist/doubles/outbox.js +70 -0
- package/dist/doubles/outbox.js.map +1 -0
- package/dist/doubles/unit-of-work.d.ts +2 -3
- package/dist/doubles/unit-of-work.d.ts.map +1 -1
- package/dist/doubles/unit-of-work.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/contracts/transaction-ports.contract.ts"],"sourcesContent":["import type { DomainEvent } from '@entifix/core';\nimport type {\n EventBus,\n LockService,\n SequenceService,\n Subscription,\n TransactionInbox,\n} from '@entifix/transactions';\nimport { Duration, Effect, Exit, Fiber } from 'effect';\nimport { TestClock } from 'effect/testing';\nimport { describe, expect, it } from 'vitest';\n\n/**\n * Runs an Effect test on a `TestClock`, so a retry budget measured in seconds\n * costs none of the wall clock.\n */\nconst effectIt = {\n effect: (name: string, body: () => Effect.Effect<unknown, unknown>) =>\n it(name, () =>\n Effect.runPromise(\n body().pipe(Effect.provide(TestClock.layer()), Effect.scoped),\n ),\n ),\n};\n\nconst run = <TValue, TError>(effect: Effect.Effect<TValue, TError>) =>\n Effect.runPromise(effect);\n\n/**\n * What every {@link LockService} must guarantee: exclusivity while held,\n * availability after release, and a release that only frees the caller's own\n * lock. The last one is why `release` takes a handle rather than a key — a lock\n * that lapsed and was re-acquired by someone else must not be freed by the\n * previous holder.\n */\nexport const describeLockServiceContract = (\n name: string,\n makeLockService: () => LockService | Promise<LockService>,\n): void => {\n describe(`LockService contract: ${name}`, () => {\n it('acquires an uncontended key', async () => {\n const locks = await makeLockService();\n\n const handle = await run(locks.acquire('contract:free'));\n\n expect(handle.key).toBe('contract:free');\n expect(handle.token).toBeTruthy();\n });\n\n // An implementation may retry before giving up (the Redis adapter waits out\n // a bounded budget), so this runs on a TestClock: the assertion is about\n // exclusivity, and it should not cost seconds of wall clock to make.\n effectIt.effect('refuses a key that is already held', () =>\n Effect.gen(function* () {\n const locks = yield* Effect.promise(async () => makeLockService());\n yield* locks.acquire('contract:taken');\n\n const fiber = yield* Effect.forkChild(locks.acquire('contract:taken'));\n yield* TestClock.adjust(Duration.minutes(1));\n const exit = yield* Fiber.await(fiber);\n\n expect(Exit.isFailure(exit)).toBe(true);\n }),\n );\n\n it('makes the key available again after release', async () => {\n const locks = await makeLockService();\n const handle = await run(locks.acquire('contract:cycle'));\n\n await run(locks.release(handle));\n const reacquired = await run(locks.acquire('contract:cycle'));\n\n expect(reacquired.key).toBe('contract:cycle');\n });\n\n effectIt.effect('ignores a release whose token does not match', () =>\n Effect.gen(function* () {\n const locks = yield* Effect.promise(async () => makeLockService());\n const handle = yield* locks.acquire('contract:stolen');\n\n yield* locks.release({ key: handle.key, token: 'not-mine' });\n\n // Still held, so a fresh acquisition must fail.\n const fiber = yield* Effect.forkChild(locks.acquire('contract:stolen'));\n yield* TestClock.adjust(Duration.minutes(1));\n const exit = yield* Fiber.await(fiber);\n\n expect(Exit.isFailure(exit)).toBe(true);\n }),\n );\n });\n};\n\n/**\n * What every {@link SequenceService} must guarantee: strictly increasing values\n * per name, never repeating, with names independent of one another. This is the\n * property incremental codes rest on.\n */\nexport const describeSequenceServiceContract = (\n name: string,\n makeSequenceService: () => SequenceService | Promise<SequenceService>,\n): void => {\n describe(`SequenceService contract: ${name}`, () => {\n it('starts at 1', async () => {\n const sequences = await makeSequenceService();\n\n expect(await run(sequences.next('contract:fresh'))).toBe(1);\n });\n\n it('never returns the same value twice for a name', async () => {\n const sequences = await makeSequenceService();\n\n const drawn = [\n await run(sequences.next('contract:codes')),\n await run(sequences.next('contract:codes')),\n await run(sequences.next('contract:codes')),\n ];\n\n expect(drawn).toEqual([1, 2, 3]);\n expect(new Set(drawn).size).toBe(drawn.length);\n });\n\n it('keeps separate names independent', async () => {\n const sequences = await makeSequenceService();\n await run(sequences.next('contract:a'));\n await run(sequences.next('contract:a'));\n\n expect(await run(sequences.next('contract:b'))).toBe(1);\n });\n });\n};\n\nexport interface EventBusContractHarness {\n bus: EventBus;\n /** Delivers `event` to whatever subscribed, as the broker would. */\n deliver(event: DomainEvent): Promise<void>;\n /** Everything the bus published, decoded back into events. */\n published(): DomainEvent[];\n}\n\n/** Every subscription in this contract, unless a test says otherwise. */\nconst ANY_WIDGET_EVENT = 'contract.widget.*';\n\n/**\n * A `work` subscription for `pattern`. The mode and the ceiling are broker\n * facts with no bearing on routing, so a test about routing states them once\n * here rather than repeating them at every call.\n */\nconst on = (pattern: string): Subscription => ({\n slice: 'contract',\n pattern,\n mode: 'work',\n maxAttempts: 5,\n});\n\n/**\n * A handler that records what it is given. Shared by both routing tests so the\n * \"nothing was delivered\" case asserts on the *same* handler the positive case\n * proves works — otherwise it could pass against a handler that was simply\n * never wired up.\n */\nconst collectInto = (sink: DomainEvent[]) => (event: DomainEvent) =>\n Effect.sync(() => {\n sink.push(event);\n });\n\nconst anEvent = (\n id: string,\n name = 'contract.widget.created',\n): DomainEvent => ({\n name,\n id,\n source: 'contract-slice',\n at: new Date('2026-01-01T00:00:00.000Z').toISOString(),\n correlationId: id,\n data: { entity: 'contract-widget' },\n});\n\n/**\n * What every {@link EventBus} must guarantee: what goes out comes back\n * unchanged, subscribers receive deliveries, and a subscriber receives only what\n * its pattern matches. The transports differ wildly (an array here, a topic\n * exchange in RabbitMQ) — the observable contract does not.\n */\nexport const describeEventBusContract = (\n name: string,\n makeHarness: () => EventBusContractHarness | Promise<EventBusContractHarness>,\n): void => {\n describe(`EventBus contract: ${name}`, () => {\n it('publishes an event verbatim', async () => {\n const harness = await makeHarness();\n const event = anEvent('tx-1');\n\n await run(harness.bus.publish(event));\n\n expect(harness.published()).toEqual([event]);\n });\n\n it('delivers published events to a subscriber', async () => {\n const harness = await makeHarness();\n const received: DomainEvent[] = [];\n await run(\n harness.bus.subscribe(on(ANY_WIDGET_EVENT), collectInto(received)),\n );\n\n await harness.deliver(anEvent('tx-2'));\n\n expect(received.map(event => event.id)).toEqual(['tx-2']);\n });\n\n // Routing is the transport's job. A bus that hands every subscriber every\n // event lets a consumer pass while receiving traffic it never bound to —\n // which is precisely the fault the fanout exchange had.\n it('delivers nothing to a subscriber whose pattern does not match', async () => {\n const harness = await makeHarness();\n const received: DomainEvent[] = [];\n await run(\n harness.bus.subscribe(on('contract.other.*'), collectInto(received)),\n );\n\n await harness.deliver(anEvent('tx-5'));\n\n expect(received).toEqual([]);\n });\n\n it('preserves publication order', async () => {\n const harness = await makeHarness();\n\n await run(harness.bus.publish(anEvent('tx-3')));\n await run(harness.bus.publish(anEvent('tx-4')));\n\n expect(harness.published().map(event => event.id)).toEqual([\n 'tx-3',\n 'tx-4',\n ]);\n });\n });\n};\n\n/**\n * What every {@link TransactionInbox} must guarantee: a first claim is granted,\n * every repeat of it is refused, and one consumer's claim says nothing about\n * another's.\n *\n * That last one is the property with teeth. Two consumers legitimately process\n * the same event — the saga tracker's fold and the SSE hub both bind\n * `transaction.*` — so an implementation keyed on `eventId` alone passes the\n * first two cases and silently starves every consumer but the first. It looks\n * like exactly-once from inside one consumer, which is why it is asserted here\n * rather than left to each adapter's own spec.\n */\nexport const describeTransactionInboxContract = (\n name: string,\n makeInbox: (consumer: string) => TransactionInbox | Promise<TransactionInbox>,\n): void => {\n describe(`TransactionInbox contract: ${name}`, () => {\n it('grants a first claim', async () => {\n const inbox = await makeInbox('contract.consumer');\n\n expect(await run(inbox.claim('tx-1:completed'))).toBe('claimed');\n });\n\n it('refuses a redelivery of the same event', async () => {\n const inbox = await makeInbox('contract.consumer');\n await run(inbox.claim('tx-2:completed'));\n\n expect(await run(inbox.claim('tx-2:completed'))).toBe('duplicate');\n });\n\n it('refuses every repeat, not only the second', async () => {\n const inbox = await makeInbox('contract.consumer');\n await run(inbox.claim('tx-3:completed'));\n\n expect(await run(inbox.claim('tx-3:completed'))).toBe('duplicate');\n expect(await run(inbox.claim('tx-3:completed'))).toBe('duplicate');\n });\n\n it('claims each step of one transaction separately', async () => {\n // `<transactionId>:<step>`, never the transaction id alone: one\n // transaction emits up to three messages, and keying on the correlation\n // id would make `completed` read as a redelivery of `accepted`.\n const inbox = await makeInbox('contract.consumer');\n\n expect(await run(inbox.claim('tx-4:accepted'))).toBe('claimed');\n expect(await run(inbox.claim('tx-4:completed'))).toBe('claimed');\n });\n\n it('does not let one consumer consume another consumer’s claim', async () => {\n const first = await makeInbox('contract.first');\n const second = await makeInbox('contract.second');\n await run(first.claim('tx-5:completed'));\n\n expect(await run(second.claim('tx-5:completed'))).toBe('claimed');\n });\n });\n};\n"],"names":["Duration","Effect","Exit","Fiber","TestClock","describe","expect","it","effectIt","effect","name","body","runPromise","pipe","provide","layer","scoped","run","describeLockServiceContract","makeLockService","locks","handle","acquire","key","toBe","token","toBeTruthy","gen","promise","fiber","forkChild","adjust","minutes","exit","await","isFailure","release","reacquired","describeSequenceServiceContract","makeSequenceService","sequences","next","drawn","toEqual","Set","size","length","ANY_WIDGET_EVENT","on","pattern","slice","mode","maxAttempts","collectInto","sink","event","sync","push","anEvent","id","source","at","Date","toISOString","correlationId","data","entity","describeEventBusContract","makeHarness","harness","bus","publish","published","received","subscribe","deliver","map","describeTransactionInboxContract","makeInbox","inbox","claim","first","second"],"mappings":"AAQA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,QAAQ,SAAS;AACvD,SAASC,SAAS,QAAQ,iBAAiB;AAC3C,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAE9C;;;CAGC,GACD,MAAMC,WAAW;IACfC,QAAQ,CAACC,MAAcC,OACrBJ,GAAGG,MAAM,IACPT,OAAOW,UAAU,CACfD,OAAOE,IAAI,CAACZ,OAAOa,OAAO,CAACV,UAAUW,KAAK,KAAKd,OAAOe,MAAM;AAGpE;AAEA,MAAMC,MAAM,CAAiBR,SAC3BR,OAAOW,UAAU,CAACH;AAEpB;;;;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xD,IAAI,CAAC;QACxD;QAEAjB,GAAG,8DAA8D;YAC/D,MAAM0E,QAAQ,MAAMH,UAAU;YAC9B,MAAMI,SAAS,MAAMJ,UAAU;YAC/B,MAAM7D,IAAIgE,MAAMD,KAAK,CAAC;YAEtB1E,OAAO,MAAMW,IAAIiE,OAAOF,KAAK,CAAC,oBAAoBxD,IAAI,CAAC;QACzD;IACF;AACF,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../src/contracts/transaction-ports.contract.ts"],"sourcesContent":["import { type DomainEvent, registerEvent } from '@entifix/core';\nimport type {\n EventBus,\n LockService,\n SequenceService,\n Subscription,\n TransactionInbox,\n} from '@entifix/transactions';\nimport { Duration, Effect, Exit, Fiber, Schema } from 'effect';\nimport { TestClock } from 'effect/testing';\nimport { describe, expect, it } from 'vitest';\n\n/**\n * Runs an Effect test on a `TestClock`, so a retry budget measured in seconds\n * costs none of the wall clock.\n */\nconst effectIt = {\n effect: (name: string, body: () => Effect.Effect<unknown, unknown>) =>\n it(name, () =>\n Effect.runPromise(\n body().pipe(Effect.provide(TestClock.layer()), Effect.scoped),\n ),\n ),\n};\n\nconst run = <TValue, TError>(effect: Effect.Effect<TValue, TError>) =>\n Effect.runPromise(effect);\n\n/**\n * What every {@link LockService} must guarantee: exclusivity while held,\n * availability after release, and a release that only frees the caller's own\n * lock. The last one is why `release` takes a handle rather than a key — a lock\n * that lapsed and was re-acquired by someone else must not be freed by the\n * previous holder.\n */\nexport const describeLockServiceContract = (\n name: string,\n makeLockService: () => LockService | Promise<LockService>,\n): void => {\n describe(`LockService contract: ${name}`, () => {\n it('acquires an uncontended key', async () => {\n const locks = await makeLockService();\n\n const handle = await run(locks.acquire('contract:free'));\n\n expect(handle.key).toBe('contract:free');\n expect(handle.token).toBeTruthy();\n });\n\n // An implementation may retry before giving up (the Redis adapter waits out\n // a bounded budget), so this runs on a TestClock: the assertion is about\n // exclusivity, and it should not cost seconds of wall clock to make.\n effectIt.effect('refuses a key that is already held', () =>\n Effect.gen(function* () {\n const locks = yield* Effect.promise(async () => makeLockService());\n yield* locks.acquire('contract:taken');\n\n const fiber = yield* Effect.forkChild(locks.acquire('contract:taken'));\n yield* TestClock.adjust(Duration.minutes(1));\n const exit = yield* Fiber.await(fiber);\n\n expect(Exit.isFailure(exit)).toBe(true);\n }),\n );\n\n it('makes the key available again after release', async () => {\n const locks = await makeLockService();\n const handle = await run(locks.acquire('contract:cycle'));\n\n await run(locks.release(handle));\n const reacquired = await run(locks.acquire('contract:cycle'));\n\n expect(reacquired.key).toBe('contract:cycle');\n });\n\n effectIt.effect('ignores a release whose token does not match', () =>\n Effect.gen(function* () {\n const locks = yield* Effect.promise(async () => makeLockService());\n const handle = yield* locks.acquire('contract:stolen');\n\n yield* locks.release({ key: handle.key, token: 'not-mine' });\n\n // Still held, so a fresh acquisition must fail.\n const fiber = yield* Effect.forkChild(locks.acquire('contract:stolen'));\n yield* TestClock.adjust(Duration.minutes(1));\n const exit = yield* Fiber.await(fiber);\n\n expect(Exit.isFailure(exit)).toBe(true);\n }),\n );\n });\n};\n\n/**\n * What every {@link SequenceService} must guarantee: strictly increasing values\n * per name, never repeating, with names independent of one another. This is the\n * property incremental codes rest on.\n */\nexport const describeSequenceServiceContract = (\n name: string,\n makeSequenceService: () => SequenceService | Promise<SequenceService>,\n): void => {\n describe(`SequenceService contract: ${name}`, () => {\n it('starts at 1', async () => {\n const sequences = await makeSequenceService();\n\n expect(await run(sequences.next('contract:fresh'))).toBe(1);\n });\n\n it('never returns the same value twice for a name', async () => {\n const sequences = await makeSequenceService();\n\n const drawn = [\n await run(sequences.next('contract:codes')),\n await run(sequences.next('contract:codes')),\n await run(sequences.next('contract:codes')),\n ];\n\n expect(drawn).toEqual([1, 2, 3]);\n expect(new Set(drawn).size).toBe(drawn.length);\n });\n\n it('keeps separate names independent', async () => {\n const sequences = await makeSequenceService();\n await run(sequences.next('contract:a'));\n await run(sequences.next('contract:a'));\n\n expect(await run(sequences.next('contract:b'))).toBe(1);\n });\n });\n};\n\nexport interface EventBusContractHarness {\n bus: EventBus;\n /** Delivers `event` to whatever subscribed, as the broker would. */\n deliver(event: DomainEvent): Promise<void>;\n /** Everything the bus published, decoded back into events. */\n published(): DomainEvent[];\n}\n\n/** Every subscription in this contract, unless a test says otherwise. */\nconst ANY_WIDGET_EVENT = 'contract.widget.*';\n\n/**\n * A `work` subscription for `pattern`. The mode and the ceiling are broker\n * facts with no bearing on routing, so a test about routing states them once\n * here rather than repeating them at every call.\n */\nconst on = (pattern: string): Subscription => ({\n slice: 'contract',\n pattern,\n mode: 'work',\n maxAttempts: 5,\n});\n\n/**\n * A handler that records what it is given. Shared by both routing tests so the\n * \"nothing was delivered\" case asserts on the *same* handler the positive case\n * proves works — otherwise it could pass against a handler that was simply\n * never wired up.\n */\nconst collectInto = (sink: DomainEvent[]) => (event: DomainEvent) =>\n Effect.sync(() => {\n sink.push(event);\n });\n\n// A transport encodes and decodes through the registry, so the suite's own\n// event is registered like any other — audience-free, since nothing here\n// delivers to a person.\nregisterEvent(\n 'contract.widget.created',\n Schema.Struct({ entity: Schema.String }),\n { audience: 'none' },\n);\n\nconst anEvent = (\n id: string,\n name = 'contract.widget.created',\n): DomainEvent => ({\n name,\n id,\n source: 'contract-slice',\n at: new Date('2026-01-01T00:00:00.000Z').toISOString(),\n correlationId: id,\n data: { entity: 'contract-widget' },\n});\n\n/**\n * What every {@link EventBus} must guarantee: what goes out comes back\n * unchanged, subscribers receive deliveries, and a subscriber receives only what\n * its pattern matches. The transports differ wildly (an array here, a topic\n * exchange in RabbitMQ) — the observable contract does not.\n */\nexport const describeEventBusContract = (\n name: string,\n makeHarness: () => EventBusContractHarness | Promise<EventBusContractHarness>,\n): void => {\n describe(`EventBus contract: ${name}`, () => {\n it('publishes an event verbatim', async () => {\n const harness = await makeHarness();\n const event = anEvent('tx-1');\n\n await run(harness.bus.publish(event));\n\n expect(harness.published()).toEqual([event]);\n });\n\n it('delivers published events to a subscriber', async () => {\n const harness = await makeHarness();\n const received: DomainEvent[] = [];\n await run(\n harness.bus.subscribe(on(ANY_WIDGET_EVENT), collectInto(received)),\n );\n\n await harness.deliver(anEvent('tx-2'));\n\n expect(received.map(event => event.id)).toEqual(['tx-2']);\n });\n\n // Routing is the transport's job. A bus that hands every subscriber every\n // event lets a consumer pass while receiving traffic it never bound to —\n // which is precisely the fault the fanout exchange had.\n it('delivers nothing to a subscriber whose pattern does not match', async () => {\n const harness = await makeHarness();\n const received: DomainEvent[] = [];\n await run(\n harness.bus.subscribe(on('contract.other.*'), collectInto(received)),\n );\n\n await harness.deliver(anEvent('tx-5'));\n\n expect(received).toEqual([]);\n });\n\n it('preserves publication order', async () => {\n const harness = await makeHarness();\n\n await run(harness.bus.publish(anEvent('tx-3')));\n await run(harness.bus.publish(anEvent('tx-4')));\n\n expect(harness.published().map(event => event.id)).toEqual([\n 'tx-3',\n 'tx-4',\n ]);\n });\n });\n};\n\n/**\n * What every {@link TransactionInbox} must guarantee: a first claim is granted,\n * every repeat of it is refused, and one consumer's claim says nothing about\n * another's.\n *\n * That last one is the property with teeth. Two consumers legitimately process\n * the same event — the saga tracker's fold and the SSE hub both bind\n * `transaction.*` — so an implementation keyed on `eventId` alone passes the\n * first two cases and silently starves every consumer but the first. It looks\n * like exactly-once from inside one consumer, which is why it is asserted here\n * rather than left to each adapter's own spec.\n */\nexport const describeTransactionInboxContract = (\n name: string,\n makeInbox: (consumer: string) => TransactionInbox | Promise<TransactionInbox>,\n): void => {\n describe(`TransactionInbox contract: ${name}`, () => {\n it('grants a first claim', async () => {\n const inbox = await makeInbox('contract.consumer');\n\n expect(await run(inbox.claim('tx-1:completed'))).toBe('claimed');\n });\n\n it('refuses a redelivery of the same event', async () => {\n const inbox = await makeInbox('contract.consumer');\n await run(inbox.claim('tx-2:completed'));\n\n expect(await run(inbox.claim('tx-2:completed'))).toBe('duplicate');\n });\n\n it('refuses every repeat, not only the second', async () => {\n const inbox = await makeInbox('contract.consumer');\n await run(inbox.claim('tx-3:completed'));\n\n expect(await run(inbox.claim('tx-3:completed'))).toBe('duplicate');\n expect(await run(inbox.claim('tx-3:completed'))).toBe('duplicate');\n });\n\n it('claims each step of one transaction separately', async () => {\n // `<transactionId>:<step>`, never the transaction id alone: one\n // transaction emits up to three messages, and keying on the correlation\n // id would make `completed` read as a redelivery of `accepted`.\n const inbox = await makeInbox('contract.consumer');\n\n expect(await run(inbox.claim('tx-4:accepted'))).toBe('claimed');\n expect(await run(inbox.claim('tx-4:completed'))).toBe('claimed');\n });\n\n it('does not let one consumer consume another consumer’s claim', async () => {\n const first = await makeInbox('contract.first');\n const second = await makeInbox('contract.second');\n await run(first.claim('tx-5:completed'));\n\n expect(await run(second.claim('tx-5:completed'))).toBe('claimed');\n });\n });\n};\n"],"names":["registerEvent","Duration","Effect","Exit","Fiber","Schema","TestClock","describe","expect","it","effectIt","effect","name","body","runPromise","pipe","provide","layer","scoped","run","describeLockServiceContract","makeLockService","locks","handle","acquire","key","toBe","token","toBeTruthy","gen","promise","fiber","forkChild","adjust","minutes","exit","await","isFailure","release","reacquired","describeSequenceServiceContract","makeSequenceService","sequences","next","drawn","toEqual","Set","size","length","ANY_WIDGET_EVENT","on","pattern","slice","mode","maxAttempts","collectInto","sink","event","sync","push","Struct","entity","String","audience","anEvent","id","source","at","Date","toISOString","correlationId","data","describeEventBusContract","makeHarness","harness","bus","publish","published","received","subscribe","deliver","map","describeTransactionInboxContract","makeInbox","inbox","claim","first","second"],"mappings":"AAAA,SAA2BA,aAAa,QAAQ,gBAAgB;AAQhE,SAASC,QAAQ,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,MAAM,QAAQ,SAAS;AAC/D,SAASC,SAAS,QAAQ,iBAAiB;AAC3C,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAE9C;;;CAGC,GACD,MAAMC,WAAW;IACfC,QAAQ,CAACC,MAAcC,OACrBJ,GAAGG,MAAM,IACPV,OAAOY,UAAU,CACfD,OAAOE,IA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AIiE,MAAMC,KAAK,CAAC,oBAAoB3D,IAAI,CAAC;QACxD;QAEAjB,GAAG,kDAAkD;YACnD,gEAAgE;YAChE,wEAAwE;YACxE,gEAAgE;YAChE,MAAM2E,QAAQ,MAAMD,UAAU;YAE9B3E,OAAO,MAAMW,IAAIiE,MAAMC,KAAK,CAAC,mBAAmB3D,IAAI,CAAC;YACrDlB,OAAO,MAAMW,IAAIiE,MAAMC,KAAK,CAAC,oBAAoB3D,IAAI,CAAC;QACxD;QAEAjB,GAAG,8DAA8D;YAC/D,MAAM6E,QAAQ,MAAMH,UAAU;YAC9B,MAAMI,SAAS,MAAMJ,UAAU;YAC/B,MAAMhE,IAAImE,MAAMD,KAAK,CAAC;YAEtB7E,OAAO,MAAMW,IAAIoE,OAAOF,KAAK,CAAC,oBAAoB3D,IAAI,CAAC;QACzD;IACF;AACF,EAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unit-of-work.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/unit-of-work.contract.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"unit-of-work.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/unit-of-work.contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,UAAU,EAAe,MAAM,eAAe,CAAC;AAC7D,OAAO,KAAK,EAAe,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,MAAM,EAAU,MAAM,QAAQ,CAAC;AAGxC,wEAAwE;AACxE,MAAM,WAAW,yBAAyB,CAAC,CAAC;IAC1C,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC;IACnC,mDAAmD;IACnD,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;IAC9D,+DAA+D;IAC/D,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;IAClE,0DAA0D;IAC1D,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACrC,+CAA+C;IAC/C,QAAQ,IAAI,OAAO,CAAC,SAAS,MAAM,EAAE,CAAC,CAAC;CACxC;AAeD;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,GAAI,CAAC,EAC1C,MAAM,MAAM,EACZ,aAAa,MACX,yBAAyB,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAAC,CAAC,CAAC,KACrE,IA6MF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/contracts/unit-of-work.contract.ts"],"sourcesContent":["import { type DomainEvent, type StoreFault, Unavailable } from '@entifix/core';\nimport type { UnitOfWork } from '@entifix/transactions';\nimport { Effect, Option } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\n/** What {@link describeUnitOfWorkContract} needs to observe a store. */\nexport interface UnitOfWorkContractHarness<H> {\n readonly unitOfWork: UnitOfWork<H>;\n /** Writes one record through the unit's handle. */\n write(handle: H, id: string): Effect.Effect<void, StoreFault>;\n /** Whether a record exists, read through the unit's handle. */\n readIn(handle: H, id: string): Effect.Effect<boolean, StoreFault>;\n /** Whether a record is durable, read outside any unit. */\n stored(id: string): Promise<boolean>;\n /** The ids of every event the outbox holds. */\n recorded(): Promise<readonly string[]>;\n}\n\nconst anEvent = (id: string): DomainEvent => ({\n name: 'contract.widget.changed',\n id,\n source: 'contract-slice',\n at: '2026-01-01T00:00:00.000Z',\n correlationId: id,\n data: {},\n});\n\nconst run = <A, E>(effect: Effect.Effect<A, E>) => Effect.runPromise(effect);\n\n/**\n * What every {@link UnitOfWork} must guarantee: the writes, the events and the\n * claim of one unit commit or vanish together; a taken claim turns the next\n * unit into a `duplicate` without running it; a business failure is an\n * `aborted` value and a store failure is an error; and what a unit wrote is\n * visible to itself before it commits.\n */\nexport const describeUnitOfWorkContract = <H>(\n name: string,\n makeHarness: () =>\n UnitOfWorkContractHarness<H> | Promise<UnitOfWorkContractHarness<H>>,\n): void => {\n describe(`UnitOfWork contract: ${name}`, () => {\n it('commits the writes and the events together', async () => {\n const harness = await makeHarness();\n\n const outcome = await run(\n harness.unitOfWork.run(unit =>\n harness.write(unit.handle, 'w-1').pipe(\n Effect.tap(() => Effect.sync(() => unit.emit(anEvent('e-1')))),\n Effect.as('done'),\n ),\n ),\n );\n\n expect(outcome).toEqual({ _tag: 'committed', value: 'done' });\n expect(await harness.stored('w-1')).toBe(true);\n expect(await harness.recorded()).toContain('e-1');\n });\n\n it('answers a business failure as aborted, and writes nothing', async () => {\n const harness = await makeHarness();\n\n const outcome = await run(\n harness.unitOfWork.run(unit =>\n harness.write(unit.handle, 'w-2').pipe(\n Effect.tap(() => Effect.sync(() => unit.emit(anEvent('e-2')))),\n Effect.andThen(Effect.fail('outOfStock' as const)),\n ),\n ),\n );\n\n expect(outcome).toEqual({ _tag: 'aborted', reason: 'outOfStock' });\n expect(await harness.stored('w-2')).toBe(false);\n expect(await harness.recorded()).not.toContain('e-2');\n });\n\n it('surfaces a store failure as an error, and writes nothing', async () => {\n const harness = await makeHarness();\n\n const error = await run(\n harness.unitOfWork\n .run(unit =>\n harness\n .write(unit.handle, 'w-3')\n .pipe(\n Effect.andThen(\n Effect.fail(new Unavailable({ dependency: 'store' })),\n ),\n ),\n )\n .pipe(Effect.flip),\n );\n\n expect(error).toMatchObject({ _tag: 'Unavailable' });\n expect(await harness.stored('w-3')).toBe(false);\n });\n\n it('lets a unit read its own uncommitted writes', async () => {\n const harness = await makeHarness();\n\n const outcome = await run(\n harness.unitOfWork.run(unit =>\n harness\n .write(unit.handle, 'w-4')\n .pipe(Effect.andThen(harness.readIn(unit.handle, 'w-4'))),\n ),\n );\n\n expect(outcome).toEqual({ _tag: 'committed', value: true });\n });\n\n it('turns a second unit on a taken event claim into a duplicate that does not run', async () => {\n const harness = await makeHarness();\n const claim = {\n kind: 'event',\n consumer: 'contract.fold',\n eventId: 'm-1',\n } as const;\n let runs = 0;\n const body = (unit: { handle: H }) =>\n Effect.suspend(() => {\n runs += 1;\n return harness.write(unit.handle, `fold-${runs}`);\n });\n\n const first = await run(harness.unitOfWork.run(body, { claim }));\n const second = await run(harness.unitOfWork.run(body, { claim }));\n\n expect(first._tag).toBe('committed');\n expect(second).toEqual({ _tag: 'duplicate', replay: Option.none() });\n expect(await harness.stored('fold-2')).toBe(false);\n });\n\n it('keys an event claim on the consumer as well as the event', async () => {\n const harness = await makeHarness();\n const noop = () => Effect.void;\n\n const one = await run(\n harness.unitOfWork.run(noop, {\n claim: { kind: 'event', consumer: 'contract.a', eventId: 'm-2' },\n }),\n );\n const other = await run(\n harness.unitOfWork.run(noop, {\n claim: { kind: 'event', consumer: 'contract.b', eventId: 'm-2' },\n }),\n );\n\n expect(one._tag).toBe('committed');\n expect(other._tag).toBe('committed');\n });\n\n it('answers a duplicate command with what the first run remembered', async () => {\n const harness = await makeHarness();\n const claim = { kind: 'command', commandId: 'c-1' } as const;\n const options = {\n claim,\n replay: (value: { paymentId: string }) => value,\n };\n\n let runs = 0;\n const capture = (unit: { handle: H }) =>\n Effect.suspend(() => {\n runs += 1;\n const paymentId = `pay-${runs}`;\n return harness\n .write(unit.handle, paymentId)\n .pipe(Effect.as({ paymentId }));\n });\n\n await run(harness.unitOfWork.run(capture, options));\n const again = await run(harness.unitOfWork.run(capture, options));\n\n expect(again).toEqual({\n _tag: 'duplicate',\n replay: Option.some({ paymentId: 'pay-1' }),\n });\n // A redelivered capture must not charge again, so the body never reruns.\n expect(runs).toBe(1);\n expect(await run(harness.unitOfWork.replay('c-1'))).toEqual(\n Option.some({ paymentId: 'pay-1' }),\n );\n expect(await run(harness.unitOfWork.replay('c-unknown'))).toEqual(\n Option.none(),\n );\n });\n\n it('leaves a claim untaken when its unit aborts', async () => {\n const harness = await makeHarness();\n const claim = { kind: 'command', commandId: 'c-2' } as const;\n\n const refused = await run(\n harness.unitOfWork.run(() => Effect.fail('declined' as const), {\n claim,\n }),\n );\n const retried = await run(\n harness.unitOfWork.run(() => Effect.succeed('ok'), { claim }),\n );\n\n expect(refused._tag).toBe('aborted');\n expect(retried).toEqual({ _tag: 'committed', value: 'ok' });\n });\n\n it('treats an event id already in the outbox as a duplicate', async () => {\n const harness = await makeHarness();\n const announce = (id: string) =>\n harness.unitOfWork.run(unit =>\n harness\n .write(unit.handle, id)\n .pipe(\n Effect.tap(() => Effect.sync(() => unit.emit(anEvent('e-same')))),\n ),\n );\n\n await run(announce('w-5'));\n const again = await run(announce('w-6'));\n\n expect(again._tag).toBe('duplicate');\n expect(await harness.stored('w-6')).toBe(false);\n });\n\n it('runs afterCommit only on commit, and never lets it change the outcome', async () => {\n const harness = await makeHarness();\n const ran: string[] = [];\n const after = (label: string) => ({\n afterCommit: Effect.sync(() => ran.push(label)).pipe(\n Effect.andThen(Effect.fail('drain failed')),\n ),\n });\n\n const committed = await run(\n harness.unitOfWork.run(() => Effect.succeed(1), after('commit')),\n );\n await run(\n harness.unitOfWork.run(\n () => Effect.fail('no' as const),\n after('abort'),\n ),\n );\n\n expect(committed).toEqual({ _tag: 'committed', value: 1 });\n expect(ran).toEqual(['commit']);\n });\n });\n};\n"],"names":["Unavailable","Effect","Option","describe","expect","it","anEvent","id","name","source","at","correlationId","data","run","effect","runPromise","describeUnitOfWorkContract","makeHarness","harness","outcome","unitOfWork","unit","write","handle","pipe","tap","sync","emit","as","toEqual","_tag","value","stored","toBe","recorded","toContain","andThen","fail","reason","not","error","dependency","flip","toMatchObject","readIn","claim","kind","consumer","eventId","runs","body","suspend","first","second","replay","none","noop","void","one","other","commandId","options","capture","paymentId","again","some","refused","retried","succeed","announce","ran","after","label","afterCommit","push","committed"],"mappings":"AAAA,SAA4CA,WAAW,QAAQ,gBAAgB;AAE/E,SAASC,MAAM,EAAEC,MAAM,QA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nBiB,IAAI,CACHvB,OAAOwB,GAAG,CAAC,IAAMxB,OAAOyB,IAAI,CAAC,IAAML,KAAKM,IAAI,CAACrB,QAAQ;YAI7D,MAAMO,IAAIwD,SAAS;YACnB,MAAML,QAAQ,MAAMnD,IAAIwD,SAAS;YAEjCjE,OAAO4D,MAAMlC,IAAI,EAAEG,IAAI,CAAC;YACxB7B,OAAO,MAAMc,QAAQc,MAAM,CAAC,QAAQC,IAAI,CAAC;QAC3C;QAEA5B,GAAG,yEAAyE;YAC1E,MAAMa,UAAU,MAAMD;YACtB,MAAMqD,MAAgB,EAAE;YACxB,MAAMC,QAAQ,CAACC,QAAmB,CAAA;oBAChCC,aAAaxE,OAAOyB,IAAI,CAAC,IAAM4C,IAAII,IAAI,CAACF,QAAQhD,IAAI,CAClDvB,OAAOmC,OAAO,CAACnC,OAAOoC,IAAI,CAAC;gBAE/B,CAAA;YAEA,MAAMsC,YAAY,MAAM9D,IACtBK,QAAQE,UAAU,CAACP,GAAG,CAAC,IAAMZ,OAAOmE,OAAO,CAAC,IAAIG,MAAM;YAExD,MAAM1D,IACJK,QAAQE,UAAU,CAACP,GAAG,CACpB,IAAMZ,OAAOoC,IAAI,CAAC,OAClBkC,MAAM;YAIVnE,OAAOuE,WAAW9C,OAAO,CAAC;gBAAEC,MAAM;gBAAaC,OAAO;YAAE;YACxD3B,OAAOkE,KAAKzC,OAAO,CAAC;gBAAC;aAAS;QAChC;IACF;AACF,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../src/contracts/unit-of-work.contract.ts"],"sourcesContent":["import { type StoreFault, Unavailable } from '@entifix/core';\nimport type { OutboxEvent, UnitOfWork } from '@entifix/transactions';\nimport { Effect, Option } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\n/** What {@link describeUnitOfWorkContract} needs to observe a store. */\nexport interface UnitOfWorkContractHarness<H> {\n readonly unitOfWork: UnitOfWork<H>;\n /** Writes one record through the unit's handle. */\n write(handle: H, id: string): Effect.Effect<void, StoreFault>;\n /** Whether a record exists, read through the unit's handle. */\n readIn(handle: H, id: string): Effect.Effect<boolean, StoreFault>;\n /** Whether a record is durable, read outside any unit. */\n stored(id: string): Promise<boolean>;\n /** The ids of every event the outbox holds. */\n recorded(): Promise<readonly string[]>;\n}\n\nconst anEvent = (id: string): OutboxEvent => ({\n name: 'contract.widget.changed',\n id,\n source: 'contract-slice',\n at: '2026-01-01T00:00:00.000Z',\n correlationId: id,\n aggregate: { type: 'contract-widget', id },\n version: 1,\n data: {},\n});\n\nconst run = <A, E>(effect: Effect.Effect<A, E>) => Effect.runPromise(effect);\n\n/**\n * What every {@link UnitOfWork} must guarantee: the writes, the events and the\n * claim of one unit commit or vanish together; a taken claim turns the next\n * unit into a `duplicate` without running it; a business failure is an\n * `aborted` value and a store failure is an error; and what a unit wrote is\n * visible to itself before it commits.\n */\nexport const describeUnitOfWorkContract = <H>(\n name: string,\n makeHarness: () =>\n UnitOfWorkContractHarness<H> | Promise<UnitOfWorkContractHarness<H>>,\n): void => {\n describe(`UnitOfWork contract: ${name}`, () => {\n it('commits the writes and the events together', async () => {\n const harness = await makeHarness();\n\n const outcome = await run(\n harness.unitOfWork.run(unit =>\n harness.write(unit.handle, 'w-1').pipe(\n Effect.tap(() => Effect.sync(() => unit.emit(anEvent('e-1')))),\n Effect.as('done'),\n ),\n ),\n );\n\n expect(outcome).toEqual({ _tag: 'committed', value: 'done' });\n expect(await harness.stored('w-1')).toBe(true);\n expect(await harness.recorded()).toContain('e-1');\n });\n\n it('answers a business failure as aborted, and writes nothing', async () => {\n const harness = await makeHarness();\n\n const outcome = await run(\n harness.unitOfWork.run(unit =>\n harness.write(unit.handle, 'w-2').pipe(\n Effect.tap(() => Effect.sync(() => unit.emit(anEvent('e-2')))),\n Effect.andThen(Effect.fail('outOfStock' as const)),\n ),\n ),\n );\n\n expect(outcome).toEqual({ _tag: 'aborted', reason: 'outOfStock' });\n expect(await harness.stored('w-2')).toBe(false);\n expect(await harness.recorded()).not.toContain('e-2');\n });\n\n it('surfaces a store failure as an error, and writes nothing', async () => {\n const harness = await makeHarness();\n\n const error = await run(\n harness.unitOfWork\n .run(unit =>\n harness\n .write(unit.handle, 'w-3')\n .pipe(\n Effect.andThen(\n Effect.fail(new Unavailable({ dependency: 'store' })),\n ),\n ),\n )\n .pipe(Effect.flip),\n );\n\n expect(error).toMatchObject({ _tag: 'Unavailable' });\n expect(await harness.stored('w-3')).toBe(false);\n });\n\n it('lets a unit read its own uncommitted writes', async () => {\n const harness = await makeHarness();\n\n const outcome = await run(\n harness.unitOfWork.run(unit =>\n harness\n .write(unit.handle, 'w-4')\n .pipe(Effect.andThen(harness.readIn(unit.handle, 'w-4'))),\n ),\n );\n\n expect(outcome).toEqual({ _tag: 'committed', value: true });\n });\n\n it('turns a second unit on a taken event claim into a duplicate that does not run', async () => {\n const harness = await makeHarness();\n const claim = {\n kind: 'event',\n consumer: 'contract.fold',\n eventId: 'm-1',\n } as const;\n let runs = 0;\n const body = (unit: { handle: H }) =>\n Effect.suspend(() => {\n runs += 1;\n return harness.write(unit.handle, `fold-${runs}`);\n });\n\n const first = await run(harness.unitOfWork.run(body, { claim }));\n const second = await run(harness.unitOfWork.run(body, { claim }));\n\n expect(first._tag).toBe('committed');\n expect(second).toEqual({ _tag: 'duplicate', replay: Option.none() });\n expect(await harness.stored('fold-2')).toBe(false);\n });\n\n it('keys an event claim on the consumer as well as the event', async () => {\n const harness = await makeHarness();\n const noop = () => Effect.void;\n\n const one = await run(\n harness.unitOfWork.run(noop, {\n claim: { kind: 'event', consumer: 'contract.a', eventId: 'm-2' },\n }),\n );\n const other = await run(\n harness.unitOfWork.run(noop, {\n claim: { kind: 'event', consumer: 'contract.b', eventId: 'm-2' },\n }),\n );\n\n expect(one._tag).toBe('committed');\n expect(other._tag).toBe('committed');\n });\n\n it('answers a duplicate command with what the first run remembered', async () => {\n const harness = await makeHarness();\n const claim = { kind: 'command', commandId: 'c-1' } as const;\n const options = {\n claim,\n replay: (value: { paymentId: string }) => value,\n };\n\n let runs = 0;\n const capture = (unit: { handle: H }) =>\n Effect.suspend(() => {\n runs += 1;\n const paymentId = `pay-${runs}`;\n return harness\n .write(unit.handle, paymentId)\n .pipe(Effect.as({ paymentId }));\n });\n\n await run(harness.unitOfWork.run(capture, options));\n const again = await run(harness.unitOfWork.run(capture, options));\n\n expect(again).toEqual({\n _tag: 'duplicate',\n replay: Option.some({ paymentId: 'pay-1' }),\n });\n // A redelivered capture must not charge again, so the body never reruns.\n expect(runs).toBe(1);\n expect(await run(harness.unitOfWork.replay('c-1'))).toEqual(\n Option.some({ paymentId: 'pay-1' }),\n );\n expect(await run(harness.unitOfWork.replay('c-unknown'))).toEqual(\n Option.none(),\n );\n });\n\n it('leaves a claim untaken when its unit aborts', async () => {\n const harness = await makeHarness();\n const claim = { kind: 'command', commandId: 'c-2' } as const;\n\n const refused = await run(\n harness.unitOfWork.run(() => Effect.fail('declined' as const), {\n claim,\n }),\n );\n const retried = await run(\n harness.unitOfWork.run(() => Effect.succeed('ok'), { claim }),\n );\n\n expect(refused._tag).toBe('aborted');\n expect(retried).toEqual({ _tag: 'committed', value: 'ok' });\n });\n\n it('treats an event id already in the outbox as a duplicate', async () => {\n const harness = await makeHarness();\n const announce = (id: string) =>\n harness.unitOfWork.run(unit =>\n harness\n .write(unit.handle, id)\n .pipe(\n Effect.tap(() => Effect.sync(() => unit.emit(anEvent('e-same')))),\n ),\n );\n\n await run(announce('w-5'));\n const again = await run(announce('w-6'));\n\n expect(again._tag).toBe('duplicate');\n expect(await harness.stored('w-6')).toBe(false);\n });\n\n it('runs afterCommit only on commit, and never lets it change the outcome', async () => {\n const harness = await makeHarness();\n const ran: string[] = [];\n const after = (label: string) => ({\n afterCommit: Effect.sync(() => ran.push(label)).pipe(\n Effect.andThen(Effect.fail('drain failed')),\n ),\n });\n\n const committed = await run(\n harness.unitOfWork.run(() => Effect.succeed(1), after('commit')),\n );\n await run(\n harness.unitOfWork.run(\n () => Effect.fail('no' as const),\n after('abort'),\n ),\n );\n\n expect(committed).toEqual({ _tag: 'committed', value: 1 });\n expect(ran).toEqual(['commit']);\n });\n });\n};\n"],"names":["Unavailable","Effect","Option","describe","expect","it","anEvent","id","name","source","at","correlationId","aggregate","type","version","data","run","effect","runPromise","describeUnitOfWorkContract","makeHarness","harness","outcome","unitOfWork","unit","write","handle","pipe","tap","sync","emit","as","toEqual","_tag","value","stored","toBe","recorded","toContain","andThen","fail","reason","not","error","dependency","flip","toMatchObject","readIn","claim","kind","consumer","eventId","runs","body","suspend","first","second","replay","none","noop","void","one","other","commandId","options","capture","paymentId","again","some","refused","retried","succeed","announce","ran","after","label","afterCommit","push","committed"],"mappings":"AAAA,SAA0BA,WAAW,QAAQ,gBAAgB;AAE7D,SAASC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AACxC,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAe9C,MAAMC,UAAU,CAACC,KAA6B,CAAA;QAC5CC,MAAM;QACND;QACAE,QAAQ;QACRC,IAAI;QACJC,eAAeJ;QACfK,WAAW;YAAEC,MAAM;YAAmBN;QAAG;QACzCO,SAAS;QACTC,MAAM,CAAC;IACT,CAAA;AAEA,MAAMC,MAAM,CAAOC,SAAgChB,OAAOiB,UAAU,CAACD;AAErE;;;;;;CAMC,GACD,OAAO,MAAME,6BAA6B,CACxCX,MACAY;IAGAjB,SAAS,CAAC,qBAAqB,EAAEK,MAAM,EAAE;QACvCH,GAAG,8CAA8C;YAC/C,MAAMgB,UAAU,MAAMD;YAEtB,MAAME,UAAU,MAAMN,IACpBK,QAAQE,UAAU,CAACP,GAAG,CAACQ,CAAAA,OACrBH,QAAQI,KAAK,CAACD,KAAKE,MAAM,EAAE,OAAOC,IAAI,CACpC1B,OAAO2B,GAAG,CAAC,IAAM3B,OAAO4B,IAAI,CAAC,IAAML,KAAKM,IAAI,CAACxB,QAAQ,WACrDL,OAAO8B,EAAE,CAAC;YAKhB3B,OAAOkB,SAASU,OAAO,CAAC;gBAA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ACJK,QAAQE,UAAU,CAACP,GAAG,CACpB,IAAMf,OAAOuC,IAAI,CAAC,OAClBkC,MAAM;YAIVtE,OAAO0E,WAAW9C,OAAO,CAAC;gBAAEC,MAAM;gBAAaC,OAAO;YAAE;YACxD9B,OAAOqE,KAAKzC,OAAO,CAAC;gBAAC;aAAS;QAChC;IACF;AACF,EAAE"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { DefinedVariants, Variant } from '@entifix/business';
|
|
2
|
+
/**
|
|
3
|
+
* Runs one use case's contract suite once per variant
|
|
4
|
+
* ([ADR 0015](../../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)):
|
|
5
|
+
* a variant is an implementation of the use case, so it is held to the same
|
|
6
|
+
* contract as every other. The `describe` names the variant, so a failure says
|
|
7
|
+
* which implementation broke it.
|
|
8
|
+
*/
|
|
9
|
+
export declare const forEachVariant: <I, S>(defined: DefinedVariants<I, S>, suite: (impl: S, variant: Variant<S>) => void) => void;
|
|
10
|
+
/**
|
|
11
|
+
* Every variant of the given use cases that no {@link forEachVariant} call has
|
|
12
|
+
* run a contract against — what a conventions check asserts is empty.
|
|
13
|
+
*/
|
|
14
|
+
export declare const variantsWithoutContract: (definitions: readonly DefinedVariants<unknown, unknown>[]) => readonly string[];
|
|
15
|
+
//# sourceMappingURL=variants.contract.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"variants.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/variants.contract.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAgBlE;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GAAI,CAAC,EAAE,CAAC,EACjC,SAAS,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,EAC9B,OAAO,CAAC,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,IAAI,KAC5C,IASF,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,uBAAuB,GAClC,aAAa,SAAS,eAAe,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,KACxD,SAAS,MAAM,EAQf,CAAC"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { describe } from 'vitest';
|
|
2
|
+
/**
|
|
3
|
+
* The variants a contract suite has run against in this process, per use
|
|
4
|
+
* case. Shared through `globalThis` so two copies of this module — a spec
|
|
5
|
+
* importing the source and a helper importing the build — agree.
|
|
6
|
+
*/ const COVERED_KEY = Symbol.for('@entifix/testing-unit/variants-covered');
|
|
7
|
+
const covered = ()=>{
|
|
8
|
+
var _holder, _COVERED_KEY, _;
|
|
9
|
+
const holder = globalThis;
|
|
10
|
+
(_ = (_holder = holder)[_COVERED_KEY = COVERED_KEY]) != null ? _ : _holder[_COVERED_KEY] = new Map();
|
|
11
|
+
return holder[COVERED_KEY];
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Runs one use case's contract suite once per variant
|
|
15
|
+
* ([ADR 0015](../../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)):
|
|
16
|
+
* a variant is an implementation of the use case, so it is held to the same
|
|
17
|
+
* contract as every other. The `describe` names the variant, so a failure says
|
|
18
|
+
* which implementation broke it.
|
|
19
|
+
*/ export const forEachVariant = (defined, suite)=>{
|
|
20
|
+
for (const variant of defined.variants){
|
|
21
|
+
var _covered_get;
|
|
22
|
+
const names = (_covered_get = covered().get(defined.useCase)) != null ? _covered_get : new Set();
|
|
23
|
+
names.add(variant.name);
|
|
24
|
+
covered().set(defined.useCase, names);
|
|
25
|
+
describe(`${defined.useCase} — variant '${variant.name}'`, ()=>{
|
|
26
|
+
suite(variant.impl, variant);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Every variant of the given use cases that no {@link forEachVariant} call has
|
|
32
|
+
* run a contract against — what a conventions check asserts is empty.
|
|
33
|
+
*/ export const variantsWithoutContract = (definitions)=>definitions.flatMap((defined)=>defined.variants.filter((variant)=>{
|
|
34
|
+
var _ref;
|
|
35
|
+
var _covered_get;
|
|
36
|
+
return !((_ref = (_covered_get = covered().get(defined.useCase)) == null ? void 0 : _covered_get.has(variant.name)) != null ? _ref : false);
|
|
37
|
+
}).map((variant)=>`${defined.useCase}:${variant.name}`));
|
|
38
|
+
|
|
39
|
+
//# sourceMappingURL=variants.contract.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/contracts/variants.contract.ts"],"sourcesContent":["import type { DefinedVariants, Variant } from '@entifix/business';\nimport { describe } from 'vitest';\n\n/**\n * The variants a contract suite has run against in this process, per use\n * case. Shared through `globalThis` so two copies of this module — a spec\n * importing the source and a helper importing the build — agree.\n */\nconst COVERED_KEY = Symbol.for('@entifix/testing-unit/variants-covered');\n\nconst covered = (): Map<string, Set<string>> => {\n const holder = globalThis as { [COVERED_KEY]?: Map<string, Set<string>> };\n holder[COVERED_KEY] ??= new Map();\n return holder[COVERED_KEY];\n};\n\n/**\n * Runs one use case's contract suite once per variant\n * ([ADR 0015](../../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)):\n * a variant is an implementation of the use case, so it is held to the same\n * contract as every other. The `describe` names the variant, so a failure says\n * which implementation broke it.\n */\nexport const forEachVariant = <I, S>(\n defined: DefinedVariants<I, S>,\n suite: (impl: S, variant: Variant<S>) => void,\n): void => {\n for (const variant of defined.variants) {\n const names = covered().get(defined.useCase) ?? new Set<string>();\n names.add(variant.name);\n covered().set(defined.useCase, names);\n describe(`${defined.useCase} — variant '${variant.name}'`, () => {\n suite(variant.impl, variant);\n });\n }\n};\n\n/**\n * Every variant of the given use cases that no {@link forEachVariant} call has\n * run a contract against — what a conventions check asserts is empty.\n */\nexport const variantsWithoutContract = (\n definitions: readonly DefinedVariants<unknown, unknown>[],\n): readonly string[] =>\n definitions.flatMap(defined =>\n defined.variants\n .filter(\n variant =>\n !(covered().get(defined.useCase)?.has(variant.name) ?? false),\n )\n .map(variant => `${defined.useCase}:${variant.name}`),\n );\n"],"names":["describe","COVERED_KEY","Symbol","for","covered","holder","globalThis","Map","forEachVariant","defined","suite","variant","variants","names","get","useCase","Set","add","name","set","impl","variantsWithoutContract","definitions","flatMap","filter","has","map"],"mappings":"AACA,SAASA,QAAQ,QAAQ,SAAS;AAElC;;;;CAIC,GACD,MAAMC,cAAcC,OAAOC,GAAG,CAAC;AAE/B,MAAMC,UAAU;QAEdC,SAAOJ,cAAPI;IADA,MAAMA,SAASC;KACfD,IAAAA,CAAAA,UAAAA,OAAM,CAACJ,eAAAA,YAAY,YAAnBI,IAAAA,OAAM,CAACJ,aAAY,GAAK,IAAIM;IAC5B,OAAOF,MAAM,CAACJ,YAAY;AAC5B;AAEA;;;;;;CAMC,GACD,OAAO,MAAMO,iBAAiB,CAC5BC,SACAC;IAEA,KAAK,MAAMC,WAAWF,QAAQG,QAAQ,CAAE;YACxBR;QAAd,MAAMS,SAAQT,eAAAA,UAAUU,GAAG,CAACL,QAAQM,OAAO,aAA7BX,eAAkC,IAAIY;QACpDH,MAAMI,GAAG,CAACN,QAAQO,IAAI;QACtBd,UAAUe,GAAG,CAACV,QAAQM,OAAO,EAAEF;QAC/Bb,SAAS,GAAGS,QAAQM,OAAO,CAAC,YAAY,EAAEJ,QAAQO,IAAI,CAAC,CAAC,CAAC,EAAE;YACzDR,MAAMC,QAAQS,IAAI,EAAET;QACtB;IACF;AACF,EAAE;AAEF;;;CAGC,GACD,OAAO,MAAMU,0BAA0B,CACrCC,cAEAA,YAAYC,OAAO,CAACd,CAAAA,UAClBA,QAAQG,QAAQ,CACbY,MAAM,CACLb,CAAAA;;gBACIP;mBAAF,WAAEA,eAAAA,UAAUU,GAAG,CAACL,QAAQM,OAAO,sBAA7BX,aAAgCqB,GAAG,CAACd,QAAQO,IAAI,oBAAK;WAE1DQ,GAAG,CAACf,CAAAA,UAAW,GAAGF,QAAQM,OAAO,CAAC,CAAC,EAAEJ,QAAQO,IAAI,EAAE,GACtD"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { FragmentCatalog, SlipStep } from '@entifix/business/flow';
|
|
2
|
+
import { type DomainEvent } from '@entifix/core';
|
|
3
|
+
import { type FlowEngine, type FlowEventData } from '@entifix/transactions';
|
|
4
|
+
import { Effect } from 'effect';
|
|
5
|
+
/** What a fake participant does for one step: succeed with an outcome, or fail. */
|
|
6
|
+
export type FakeParticipant = (step: SlipStep) => Effect.Effect<unknown, unknown>;
|
|
7
|
+
export interface FakeFlowEngine extends FlowEngine {
|
|
8
|
+
/** Every `flow.*` event the engine announced, in order. */
|
|
9
|
+
readonly events: readonly DomainEvent<FlowEventData>[];
|
|
10
|
+
/** Every compensation it ran, as `compensate:<step>`, in order. */
|
|
11
|
+
readonly compensations: readonly string[];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* An in-memory {@link FlowEngine} with the semantics a durable one must have
|
|
15
|
+
* ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):
|
|
16
|
+
* a failure before the commit point — the pivot's own included — compensates
|
|
17
|
+
* the steps that succeeded, in reverse; a failure after it suspends the flow;
|
|
18
|
+
* a `wait` parks it until a signal names that step. It runs synchronously and
|
|
19
|
+
* durably remembers nothing, which is what makes it a fake.
|
|
20
|
+
*/
|
|
21
|
+
export declare const makeFakeFlowEngine: (catalog: FragmentCatalog, participant: FakeParticipant) => FakeFlowEngine;
|
|
22
|
+
//# sourceMappingURL=flow-engine.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"flow-engine.d.ts","sourceRoot":"","sources":["../../src/doubles/flow-engine.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAQ,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAE9E,OAAO,EAAE,KAAK,WAAW,EAAa,MAAM,eAAe,CAAC;AAC5D,OAAO,EACL,KAAK,UAAU,EAEf,KAAK,aAAa,EAInB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,mFAAmF;AACnF,MAAM,MAAM,eAAe,GAAG,CAC5B,IAAI,EAAE,QAAQ,KACX,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAErC,MAAM,WAAW,cAAe,SAAQ,UAAU;IAChD,2DAA2D;IAC3D,QAAQ,CAAC,MAAM,EAAE,SAAS,WAAW,CAAC,aAAa,CAAC,EAAE,CAAC;IACvD,mEAAmE;IACnE,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;CAC3C;AAgBD;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,GAC7B,SAAS,eAAe,EACxB,aAAa,eAAe,KAC3B,cAiHF,CAAC"}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { slipSteps } from '@entifix/business/flow';
|
|
3
|
+
import { isFailure } from '@entifix/core';
|
|
4
|
+
import { flowEvent, FlowNotFound, FlowSignalRejected } from '@entifix/transactions';
|
|
5
|
+
import { Effect } from 'effect';
|
|
6
|
+
const failureOf = (error)=>isFailure(error) ? {
|
|
7
|
+
code: error.code,
|
|
8
|
+
category: error.category
|
|
9
|
+
} : {
|
|
10
|
+
code: 'internal',
|
|
11
|
+
category: 'internal'
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* An in-memory {@link FlowEngine} with the semantics a durable one must have
|
|
15
|
+
* ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):
|
|
16
|
+
* a failure before the commit point — the pivot's own included — compensates
|
|
17
|
+
* the steps that succeeded, in reverse; a failure after it suspends the flow;
|
|
18
|
+
* a `wait` parks it until a signal names that step. It runs synchronously and
|
|
19
|
+
* durably remembers nothing, which is what makes it a fake.
|
|
20
|
+
*/ export const makeFakeFlowEngine = (catalog, participant)=>{
|
|
21
|
+
const runs = new Map();
|
|
22
|
+
const byKey = new Map();
|
|
23
|
+
const events = [];
|
|
24
|
+
const compensations = [];
|
|
25
|
+
const kindOf = (step)=>{
|
|
26
|
+
var _ref;
|
|
27
|
+
var _catalog_get;
|
|
28
|
+
return (_ref = (_catalog_get = catalog.get(step.ref)) == null ? void 0 : _catalog_get.kind) != null ? _ref : 'retriable';
|
|
29
|
+
};
|
|
30
|
+
const announce = (run, name, step, extra = {})=>{
|
|
31
|
+
events.push(flowEvent({
|
|
32
|
+
name: name,
|
|
33
|
+
source: 'fake-flow-engine',
|
|
34
|
+
at: new Date(0).toISOString(),
|
|
35
|
+
step,
|
|
36
|
+
ordinal: events.length,
|
|
37
|
+
audience: [
|
|
38
|
+
{
|
|
39
|
+
kind: 'flow',
|
|
40
|
+
id: run.slip.flowId
|
|
41
|
+
}
|
|
42
|
+
],
|
|
43
|
+
data: _extends({
|
|
44
|
+
flowId: run.slip.flowId,
|
|
45
|
+
definition: run.slip.recipe,
|
|
46
|
+
slipVersion: run.slip.slipVersion,
|
|
47
|
+
step
|
|
48
|
+
}, extra)
|
|
49
|
+
}));
|
|
50
|
+
};
|
|
51
|
+
const walk = (run)=>Effect.gen(function*() {
|
|
52
|
+
const steps = slipSteps(run.slip);
|
|
53
|
+
const commitAt = steps.findIndex((step)=>kindOf(step) === 'pivot');
|
|
54
|
+
while(run.next < steps.length){
|
|
55
|
+
const step = steps[run.next];
|
|
56
|
+
run.step = step.step;
|
|
57
|
+
if (kindOf(step) === 'wait') {
|
|
58
|
+
run.state = 'waiting';
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const result = yield* Effect.result(participant(step));
|
|
62
|
+
if (result._tag === 'Failure') {
|
|
63
|
+
const error = result.failure;
|
|
64
|
+
const preCommit = commitAt === -1 || run.next <= commitAt;
|
|
65
|
+
if (preCommit) {
|
|
66
|
+
for (const done of [
|
|
67
|
+
...run.done
|
|
68
|
+
].reverse())if (kindOf(done) === 'compensatable') compensations.push(`compensate:${done.step}`);
|
|
69
|
+
run.state = 'compensated';
|
|
70
|
+
announce(run, 'flow.failed', step.step, {
|
|
71
|
+
failure: failureOf(error)
|
|
72
|
+
});
|
|
73
|
+
} else {
|
|
74
|
+
run.state = 'suspended';
|
|
75
|
+
announce(run, 'flow.suspended', step.step, {
|
|
76
|
+
failure: failureOf(error)
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
run.done.push(step);
|
|
82
|
+
run.next += 1;
|
|
83
|
+
}
|
|
84
|
+
run.state = 'completed';
|
|
85
|
+
run.step = undefined;
|
|
86
|
+
announce(run, 'flow.completed', 'completed');
|
|
87
|
+
});
|
|
88
|
+
const find = (flowId)=>{
|
|
89
|
+
const run = runs.get(flowId);
|
|
90
|
+
return run === undefined ? Effect.fail(new FlowNotFound({
|
|
91
|
+
flowId
|
|
92
|
+
})) : Effect.succeed(run);
|
|
93
|
+
};
|
|
94
|
+
return {
|
|
95
|
+
events,
|
|
96
|
+
compensations,
|
|
97
|
+
start: (slip, idempotencyKey)=>Effect.gen(function*() {
|
|
98
|
+
const known = byKey.get(idempotencyKey);
|
|
99
|
+
if (known !== undefined) return {
|
|
100
|
+
flowId: known
|
|
101
|
+
};
|
|
102
|
+
const run = {
|
|
103
|
+
slip,
|
|
104
|
+
state: 'running',
|
|
105
|
+
next: 0,
|
|
106
|
+
done: []
|
|
107
|
+
};
|
|
108
|
+
runs.set(slip.flowId, run);
|
|
109
|
+
byKey.set(idempotencyKey, slip.flowId);
|
|
110
|
+
announce(run, 'flow.started', 'started');
|
|
111
|
+
yield* walk(run);
|
|
112
|
+
return {
|
|
113
|
+
flowId: slip.flowId
|
|
114
|
+
};
|
|
115
|
+
}),
|
|
116
|
+
status: (flowId)=>Effect.map(find(flowId), (run)=>_extends({
|
|
117
|
+
flowId,
|
|
118
|
+
state: run.state
|
|
119
|
+
}, run.step === undefined ? {} : {
|
|
120
|
+
step: run.step
|
|
121
|
+
})),
|
|
122
|
+
signal: (flowId, token)=>Effect.flatMap(find(flowId), (run)=>{
|
|
123
|
+
if (run.state !== 'waiting' || run.step !== token) return Effect.fail(new FlowSignalRejected({
|
|
124
|
+
flowId,
|
|
125
|
+
token
|
|
126
|
+
}));
|
|
127
|
+
run.state = 'running';
|
|
128
|
+
run.next += 1;
|
|
129
|
+
return walk(run);
|
|
130
|
+
}),
|
|
131
|
+
interrupt: (flowId)=>Effect.map(find(flowId), (run)=>{
|
|
132
|
+
if (run.state === 'running' || run.state === 'waiting') run.state = 'interrupted';
|
|
133
|
+
})
|
|
134
|
+
};
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
//# sourceMappingURL=flow-engine.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/doubles/flow-engine.ts"],"sourcesContent":["import type { FragmentCatalog, Slip, SlipStep } from '@entifix/business/flow';\nimport { slipSteps } from '@entifix/business/flow';\nimport { type DomainEvent, isFailure } from '@entifix/core';\nimport {\n type FlowEngine,\n flowEvent,\n type FlowEventData,\n FlowNotFound,\n FlowSignalRejected,\n type FlowState,\n} from '@entifix/transactions';\nimport { Effect } from 'effect';\n\n/** What a fake participant does for one step: succeed with an outcome, or fail. */\nexport type FakeParticipant = (\n step: SlipStep,\n) => Effect.Effect<unknown, unknown>;\n\nexport interface FakeFlowEngine extends FlowEngine {\n /** Every `flow.*` event the engine announced, in order. */\n readonly events: readonly DomainEvent<FlowEventData>[];\n /** Every compensation it ran, as `compensate:<step>`, in order. */\n readonly compensations: readonly string[];\n}\n\ninterface Run {\n readonly slip: Slip;\n state: FlowState;\n step?: string;\n /** The next step to run. */\n next: number;\n readonly done: SlipStep[];\n}\n\nconst failureOf = (error: unknown) =>\n isFailure(error)\n ? { code: error.code, category: error.category }\n : { code: 'internal', category: 'internal' };\n\n/**\n * An in-memory {@link FlowEngine} with the semantics a durable one must have\n * ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):\n * a failure before the commit point — the pivot's own included — compensates\n * the steps that succeeded, in reverse; a failure after it suspends the flow;\n * a `wait` parks it until a signal names that step. It runs synchronously and\n * durably remembers nothing, which is what makes it a fake.\n */\nexport const makeFakeFlowEngine = (\n catalog: FragmentCatalog,\n participant: FakeParticipant,\n): FakeFlowEngine => {\n const runs = new Map<string, Run>();\n const byKey = new Map<string, string>();\n const events: DomainEvent<FlowEventData>[] = [];\n const compensations: string[] = [];\n\n const kindOf = (step: SlipStep) => catalog.get(step.ref)?.kind ?? 'retriable';\n\n const announce = (\n run: Run,\n name: DomainEvent['name'] & `flow.${string}`,\n step: string,\n extra: Partial<FlowEventData> = {},\n ) => {\n events.push(\n flowEvent({\n name: name as 'flow.started',\n source: 'fake-flow-engine',\n at: new Date(0).toISOString(),\n step,\n ordinal: events.length,\n audience: [{ kind: 'flow', id: run.slip.flowId }],\n data: {\n flowId: run.slip.flowId,\n definition: run.slip.recipe,\n slipVersion: run.slip.slipVersion,\n step,\n ...extra,\n },\n }),\n );\n };\n\n const walk = (run: Run): Effect.Effect<void> =>\n Effect.gen(function* () {\n const steps = slipSteps(run.slip);\n const commitAt = steps.findIndex(step => kindOf(step) === 'pivot');\n while (run.next < steps.length) {\n const step = steps[run.next] as SlipStep;\n run.step = step.step;\n if (kindOf(step) === 'wait') {\n run.state = 'waiting';\n return;\n }\n const result = yield* Effect.result(participant(step));\n if (result._tag === 'Failure') {\n const error = result.failure;\n const preCommit = commitAt === -1 || run.next <= commitAt;\n if (preCommit) {\n for (const done of [...run.done].reverse())\n if (kindOf(done) === 'compensatable')\n compensations.push(`compensate:${done.step}`);\n run.state = 'compensated';\n announce(run, 'flow.failed', step.step, {\n failure: failureOf(error),\n });\n } else {\n run.state = 'suspended';\n announce(run, 'flow.suspended', step.step, {\n failure: failureOf(error),\n });\n }\n return;\n }\n run.done.push(step);\n run.next += 1;\n }\n run.state = 'completed';\n run.step = undefined;\n announce(run, 'flow.completed', 'completed');\n });\n\n const find = (flowId: string) => {\n const run = runs.get(flowId);\n return run === undefined\n ? Effect.fail(new FlowNotFound({ flowId }))\n : Effect.succeed(run);\n };\n\n return {\n events,\n compensations,\n start: (slip, idempotencyKey) =>\n Effect.gen(function* () {\n const known = byKey.get(idempotencyKey);\n if (known !== undefined) return { flowId: known };\n const run: Run = { slip, state: 'running', next: 0, done: [] };\n runs.set(slip.flowId, run);\n byKey.set(idempotencyKey, slip.flowId);\n announce(run, 'flow.started', 'started');\n yield* walk(run);\n return { flowId: slip.flowId };\n }),\n status: flowId =>\n Effect.map(find(flowId), run => ({\n flowId,\n state: run.state,\n ...(run.step === undefined ? {} : { step: run.step }),\n })),\n signal: (flowId, token) =>\n Effect.flatMap(find(flowId), run => {\n if (run.state !== 'waiting' || run.step !== token)\n return Effect.fail(new FlowSignalRejected({ flowId, token }));\n run.state = 'running';\n run.next += 1;\n return walk(run);\n }),\n interrupt: flowId =>\n Effect.map(find(flowId), run => {\n if (run.state === 'running' || run.state === 'waiting')\n run.state = 'interrupted';\n }),\n };\n};\n"],"names":["slipSteps","isFailure","flowEvent","FlowNotFound","FlowSignalRejected","Effect","failureOf","error","code","category","makeFakeFlowEngine","catalog","participant","runs","Map","byKey","events","compensations","kindOf","step","get","ref","kind","announce","run","name","extra","push","source","at","Date","toISOString","ordinal","length","audience","id","slip","flowId","data","definition","recipe","slipVersion","walk","gen","steps","commitAt","findIndex","next","state","result","_tag","failure","preCommit","done","reverse","undefined","find","fail","succeed","start","idempotencyKey","known","set","status","map","signal","token","flatMap","interrupt"],"mappings":";AACA,SAASA,SAAS,QAAQ,yBAAyB;AACnD,SAA2BC,SAAS,QAAQ,gBAAgB;AAC5D,SAEEC,SAAS,EAETC,YAAY,EACZC,kBAAkB,QAEb,wBAAwB;AAC/B,SAASC,MAAM,QAAQ,SAAS;AAuBhC,MAAMC,YAAY,CAACC,QACjBN,UAAUM,SACN;QAAEC,MAAMD,MAAMC,IAAI;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AAC;gBAC7DxC,KAAKiD,GAAG,CAAC1B,KAAKC,MAAM,EAAEb;gBACtBT,MAAM+C,GAAG,CAACF,gBAAgBxB,KAAKC,MAAM;gBACrCd,SAASC,KAAK,gBAAgB;gBAC9B,OAAOkB,KAAKlB;gBACZ,OAAO;oBAAEa,QAAQD,KAAKC,MAAM;gBAAC;YAC/B;QACF0B,QAAQ1B,CAAAA,SACNhC,OAAO2D,GAAG,CAACR,KAAKnB,SAASb,CAAAA,MAAQ;oBAC/Ba;oBACAW,OAAOxB,IAAIwB,KAAK;mBACZxB,IAAIL,IAAI,KAAKoC,YAAY,CAAC,IAAI;oBAAEpC,MAAMK,IAAIL,IAAI;gBAAC;QAEvD8C,QAAQ,CAAC5B,QAAQ6B,QACf7D,OAAO8D,OAAO,CAACX,KAAKnB,SAASb,CAAAA;gBAC3B,IAAIA,IAAIwB,KAAK,KAAK,aAAaxB,IAAIL,IAAI,KAAK+C,OAC1C,OAAO7D,OAAOoD,IAAI,CAAC,IAAIrD,mBAAmB;oBAAEiC;oBAAQ6B;gBAAM;gBAC5D1C,IAAIwB,KAAK,GAAG;gBACZxB,IAAIuB,IAAI,IAAI;gBACZ,OAAOL,KAAKlB;YACd;QACF4C,WAAW/B,CAAAA,SACThC,OAAO2D,GAAG,CAACR,KAAKnB,SAASb,CAAAA;gBACvB,IAAIA,IAAIwB,KAAK,KAAK,aAAaxB,IAAIwB,KAAK,KAAK,WAC3CxB,IAAIwB,KAAK,GAAG;YAChB;IACJ;AACF,EAAE"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { IdempotencyRecord, IdempotencyStore } from '@entifix/business';
|
|
2
|
+
export interface IdempotencyStoreOptions {
|
|
3
|
+
/** How long a record lives, in milliseconds. */
|
|
4
|
+
readonly retentionMs: number;
|
|
5
|
+
/** The clock, in epoch milliseconds; defaults to `Date.now`. */
|
|
6
|
+
readonly now?: () => number;
|
|
7
|
+
}
|
|
8
|
+
/** An {@link IdempotencyStore} over a `Map`, for a spec that has no store. */
|
|
9
|
+
export declare const makeInMemoryIdempotencyStore: ({ retentionMs, now, }: IdempotencyStoreOptions) => IdempotencyStore & {
|
|
10
|
+
readonly records: ReadonlyMap<string, IdempotencyRecord>;
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=idempotency-store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"idempotency-store.d.ts","sourceRoot":"","sources":["../../src/doubles/idempotency-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAG7E,MAAM,WAAW,uBAAuB;IACtC,gDAAgD;IAChD,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,gEAAgE;IAChE,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CAC7B;AAED,8EAA8E;AAC9E,eAAO,MAAM,4BAA4B,GAAI,uBAG1C,uBAAuB,KAAG,gBAAgB,GAAG;IAC9C,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;CAmC1D,CAAC"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { Effect } from 'effect';
|
|
3
|
+
/** An {@link IdempotencyStore} over a `Map`, for a spec that has no store. */ export const makeInMemoryIdempotencyStore = ({ retentionMs, now = Date.now })=>{
|
|
4
|
+
const records = new Map();
|
|
5
|
+
const live = (dedupKey)=>{
|
|
6
|
+
const record = records.get(dedupKey);
|
|
7
|
+
return record !== undefined && Date.parse(record.expiresAt) > now() ? record : undefined;
|
|
8
|
+
};
|
|
9
|
+
return {
|
|
10
|
+
records,
|
|
11
|
+
claim: (dedupKey, fingerprint)=>Effect.sync(()=>{
|
|
12
|
+
const existing = live(dedupKey);
|
|
13
|
+
if (existing !== undefined) return {
|
|
14
|
+
_tag: 'existing',
|
|
15
|
+
record: existing
|
|
16
|
+
};
|
|
17
|
+
records.set(dedupKey, {
|
|
18
|
+
dedupKey,
|
|
19
|
+
fingerprint,
|
|
20
|
+
state: 'inFlight',
|
|
21
|
+
expiresAt: new Date(now() + retentionMs).toISOString()
|
|
22
|
+
});
|
|
23
|
+
return {
|
|
24
|
+
_tag: 'claimed'
|
|
25
|
+
};
|
|
26
|
+
}),
|
|
27
|
+
complete: (dedupKey, response)=>Effect.sync(()=>{
|
|
28
|
+
const existing = records.get(dedupKey);
|
|
29
|
+
if (existing !== undefined) records.set(dedupKey, _extends({}, existing, {
|
|
30
|
+
state: 'completed',
|
|
31
|
+
response
|
|
32
|
+
}));
|
|
33
|
+
}),
|
|
34
|
+
release: (dedupKey)=>Effect.sync(()=>{
|
|
35
|
+
records.delete(dedupKey);
|
|
36
|
+
})
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
//# sourceMappingURL=idempotency-store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/doubles/idempotency-store.ts"],"sourcesContent":["import type { IdempotencyRecord, IdempotencyStore } from '@entifix/business';\nimport { Effect } from 'effect';\n\nexport interface IdempotencyStoreOptions {\n /** How long a record lives, in milliseconds. */\n readonly retentionMs: number;\n /** The clock, in epoch milliseconds; defaults to `Date.now`. */\n readonly now?: () => number;\n}\n\n/** An {@link IdempotencyStore} over a `Map`, for a spec that has no store. */\nexport const makeInMemoryIdempotencyStore = ({\n retentionMs,\n now = Date.now,\n}: IdempotencyStoreOptions): IdempotencyStore & {\n readonly records: ReadonlyMap<string, IdempotencyRecord>;\n} => {\n const records = new Map<string, IdempotencyRecord>();\n const live = (dedupKey: string) => {\n const record = records.get(dedupKey);\n return record !== undefined && Date.parse(record.expiresAt) > now()\n ? record\n : undefined;\n };\n return {\n records,\n claim: (dedupKey, fingerprint) =>\n Effect.sync(() => {\n const existing = live(dedupKey);\n if (existing !== undefined)\n return { _tag: 'existing' as const, record: existing };\n records.set(dedupKey, {\n dedupKey,\n fingerprint,\n state: 'inFlight',\n expiresAt: new Date(now() + retentionMs).toISOString(),\n });\n return { _tag: 'claimed' as const };\n }),\n complete: (dedupKey, response) =>\n Effect.sync(() => {\n const existing = records.get(dedupKey);\n if (existing !== undefined)\n records.set(dedupKey, { ...existing, state: 'completed', response });\n }),\n release: dedupKey =>\n Effect.sync(() => {\n records.delete(dedupKey);\n }),\n };\n};\n"],"names":["Effect","makeInMemoryIdempotencyStore","retentionMs","now","Date","records","Map","live","dedupKey","record","get","undefined","parse","expiresAt","claim","fingerprint","sync","existing","_tag","set","state","toISOString","complete","response","release","delete"],"mappings":";AACA,SAASA,MAAM,QAAQ,SAAS;AAShC,4EAA4E,GAC5E,OAAO,MAAMC,+BAA+B,CAAC,EAC3CC,WAAW,EACXC,MAAMC,KAAKD,GAAG,EACU;IAGxB,MAAME,UAAU,IAAIC;IACpB,MAAMC,OAAO,CAACC;QACZ,MAAMC,SAASJ,QAAQK,GAAG,CAACF;QAC3B,OAAOC,WAAWE,aAAaP,KAAKQ,KAAK,CAACH,OAAOI,SAAS,IAAIV,QAC1DM,SACAE;IACN;IACA,OAAO;QACLN;QACAS,OAAO,CAACN,UAAUO,cAChBf,OAAOgB,IAAI,CAAC;gBACV,MAAMC,WAAWV,KAAKC;gBACtB,IAAIS,aAAaN,WACf,OAAO;oBAAEO,MAAM;oBAAqBT,QAAQQ;gBAAS;gBACvDZ,QAAQc,GAAG,CAACX,UAAU;oBACpBA;oBACAO;oBACAK,OAAO;oBACPP,WAAW,IAAIT,KAAKD,QAAQD,aAAamB,WAAW;gBACtD;gBACA,OAAO;oBAAEH,MAAM;gBAAmB;YACpC;QACFI,UAAU,CAACd,UAAUe,WACnBvB,OAAOgB,IAAI,CAAC;gBACV,MAAMC,WAAWZ,QAAQK,GAAG,CAACF;gBAC7B,IAAIS,aAAaN,WACfN,QAAQc,GAAG,CAACX,UAAU,aAAKS;oBAAUG,OAAO;oBAAaG;;YAC7D;QACFC,SAAShB,CAAAA,WACPR,OAAOgB,IAAI,CAAC;gBACVX,QAAQoB,MAAM,CAACjB;YACjB;IACJ;AACF,EAAE"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type EventBus, type Outbox, type OutboxEntry } from '@entifix/transactions';
|
|
2
|
+
import { Effect } from 'effect';
|
|
3
|
+
export interface InMemoryOutbox extends Outbox {
|
|
4
|
+
/** Every entry, in enqueue order. */
|
|
5
|
+
readonly entries: readonly OutboxEntry[];
|
|
6
|
+
/**
|
|
7
|
+
* One relay pass with the semantics every relay has: oldest first, in order
|
|
8
|
+
* within each aggregate, a failing head holding back only its own aggregate,
|
|
9
|
+
* and quarantine at `maxAttempts`.
|
|
10
|
+
*/
|
|
11
|
+
readonly drain: (bus: EventBus, maxAttempts: number) => Effect.Effect<number>;
|
|
12
|
+
}
|
|
13
|
+
/** An {@link Outbox} over an array, for a spec that has no store. */
|
|
14
|
+
export declare const makeInMemoryOutbox: () => InMemoryOutbox;
|
|
15
|
+
//# sourceMappingURL=outbox.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"outbox.d.ts","sourceRoot":"","sources":["../../src/doubles/outbox.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,QAAQ,EACb,KAAK,MAAM,EACX,KAAK,WAAW,EACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAU,MAAM,QAAQ,CAAC;AAExC,MAAM,WAAW,cAAe,SAAQ,MAAM;IAC5C,qCAAqC;IACrC,QAAQ,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;IACzC;;;;OAIG;IACH,QAAQ,CAAC,KAAK,EAAE,CAAC,GAAG,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,KAAK,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;CAC/E;AAED,qEAAqE;AACrE,eAAO,MAAM,kBAAkB,QAAO,cAiFrC,CAAC"}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { aggregateKey } from '@entifix/transactions';
|
|
3
|
+
import { Effect, Result } from 'effect';
|
|
4
|
+
/** An {@link Outbox} over an array, for a spec that has no store. */ export const makeInMemoryOutbox = ()=>{
|
|
5
|
+
const entries = [];
|
|
6
|
+
const find = (eventId)=>entries.find((entry)=>entry.eventId === eventId);
|
|
7
|
+
const pendingOnes = ()=>entries.filter((entry)=>!entry.sent && !entry.quarantined).sort((a, b)=>a.createdAt.localeCompare(b.createdAt) || a.version - b.version);
|
|
8
|
+
const outbox = {
|
|
9
|
+
enqueue: (event)=>Effect.sync(()=>{
|
|
10
|
+
if (find(event.id) !== undefined) return 'duplicate';
|
|
11
|
+
entries.push({
|
|
12
|
+
eventId: event.id,
|
|
13
|
+
aggregate: event.aggregate,
|
|
14
|
+
version: event.version,
|
|
15
|
+
event,
|
|
16
|
+
sent: false,
|
|
17
|
+
attempts: 0,
|
|
18
|
+
quarantined: false,
|
|
19
|
+
createdAt: event.at
|
|
20
|
+
});
|
|
21
|
+
return 'enqueued';
|
|
22
|
+
}),
|
|
23
|
+
pending: (limit)=>Effect.sync(()=>pendingOnes().slice(0, limit)),
|
|
24
|
+
markSent: (entry)=>Effect.sync(()=>{
|
|
25
|
+
const stored = find(entry.eventId);
|
|
26
|
+
if (stored !== undefined) stored.sent = true;
|
|
27
|
+
}),
|
|
28
|
+
recordFailure: (entry, error, quarantine)=>Effect.sync(()=>{
|
|
29
|
+
const stored = find(entry.eventId);
|
|
30
|
+
if (stored === undefined) return;
|
|
31
|
+
stored.attempts += 1;
|
|
32
|
+
stored.lastError = error;
|
|
33
|
+
stored.quarantined = quarantine;
|
|
34
|
+
}),
|
|
35
|
+
stats: ()=>Effect.sync(()=>{
|
|
36
|
+
const pending = pendingOnes();
|
|
37
|
+
const oldest = pending[0];
|
|
38
|
+
return _extends({
|
|
39
|
+
pending: pending.length,
|
|
40
|
+
quarantined: entries.filter((entry)=>entry.quarantined).length
|
|
41
|
+
}, oldest === undefined ? {} : {
|
|
42
|
+
oldestPendingAt: oldest.createdAt
|
|
43
|
+
});
|
|
44
|
+
})
|
|
45
|
+
};
|
|
46
|
+
const drain = (bus, maxAttempts)=>Effect.gen(function*() {
|
|
47
|
+
const held = new Set();
|
|
48
|
+
let sent = 0;
|
|
49
|
+
for (const entry of yield* outbox.pending(Number.MAX_SAFE_INTEGER)){
|
|
50
|
+
const key = aggregateKey(entry.aggregate);
|
|
51
|
+
if (held.has(key)) continue;
|
|
52
|
+
const outcome = yield* Effect.result(bus.publish(entry.event));
|
|
53
|
+
if (Result.isFailure(outcome)) {
|
|
54
|
+
const quarantine = entry.attempts + 1 >= maxAttempts;
|
|
55
|
+
yield* outbox.recordFailure(entry, outcome.failure.message, quarantine);
|
|
56
|
+
if (!quarantine) held.add(key);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
yield* outbox.markSent(entry);
|
|
60
|
+
sent += 1;
|
|
61
|
+
}
|
|
62
|
+
return sent;
|
|
63
|
+
}).pipe(Effect.orDie);
|
|
64
|
+
return _extends({}, outbox, {
|
|
65
|
+
entries,
|
|
66
|
+
drain
|
|
67
|
+
});
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
//# sourceMappingURL=outbox.js.map
|