@entifix/testing-unit 0.11.0 → 0.12.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/breaker.contract.d.ts +25 -0
- package/dist/contracts/breaker.contract.d.ts.map +1 -0
- package/dist/contracts/breaker.contract.js +159 -0
- package/dist/contracts/breaker.contract.js.map +1 -0
- package/dist/contracts/flow-engine.contract.d.ts +1 -1
- package/dist/contracts/flow-engine.contract.d.ts.map +1 -1
- package/dist/contracts/flow-engine.contract.js +46 -10
- package/dist/contracts/flow-engine.contract.js.map +1 -1
- package/dist/contracts/index.d.ts +1 -0
- package/dist/contracts/index.d.ts.map +1 -1
- package/dist/contracts/index.js +1 -0
- package/dist/contracts/index.js.map +1 -1
- package/dist/doubles/entity-repository.d.ts +3 -3
- package/dist/doubles/entity-repository.d.ts.map +1 -1
- package/dist/doubles/entity-repository.js +2 -4
- package/dist/doubles/entity-repository.js.map +1 -1
- package/dist/doubles/flow-engine.d.ts +2 -2
- package/dist/doubles/flow-engine.d.ts.map +1 -1
- package/dist/doubles/flow-engine.js +26 -15
- package/dist/doubles/flow-engine.js.map +1 -1
- package/dist/doubles/link-resolver.d.ts.map +1 -1
- package/dist/doubles/link-resolver.js +3 -4
- package/dist/doubles/link-resolver.js.map +1 -1
- package/dist/drivers/fake-amqp.d.ts +2 -0
- package/dist/drivers/fake-amqp.d.ts.map +1 -1
- package/dist/drivers/fake-amqp.js +8 -0
- package/dist/drivers/fake-amqp.js.map +1 -1
- package/dist/drivers/fake-sql.d.ts.map +1 -1
- package/dist/drivers/fake-sql.js +16 -1
- package/dist/drivers/fake-sql.js.map +1 -1
- package/package.json +5 -5
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { BreakerDials, Bulkhead, CircuitBreaker } from '@entifix/transactions';
|
|
2
|
+
import { Effect } from 'effect';
|
|
3
|
+
import type { ContractClock } from './idempotency-store.contract.js';
|
|
4
|
+
/** What a case is handed: a breaker and a bulkhead over its clock. */
|
|
5
|
+
export interface BreakerUnderTest {
|
|
6
|
+
readonly breaker: CircuitBreaker;
|
|
7
|
+
readonly bulkhead: Bulkhead;
|
|
8
|
+
}
|
|
9
|
+
/** The dials the cases are written against. */
|
|
10
|
+
export declare const BREAKER_CONTRACT_DIALS: BreakerDials;
|
|
11
|
+
/**
|
|
12
|
+
* What every breaker and bulkhead must guarantee
|
|
13
|
+
* ([ADR 0017](../../../../../docs/adr/0017-circuit-breaker-and-bulkhead-ports.md)):
|
|
14
|
+
* a window that opens at its failure or slow-call rate and not before its
|
|
15
|
+
* minimum; an open breaker that refuses without calling, and lets probes
|
|
16
|
+
* through once its wait has passed; probes that close it or reopen it; a
|
|
17
|
+
* `Retry-After` that opens it at once and for as long as was asked; business
|
|
18
|
+
* and protocol failures that never move it; the forced states; and a full
|
|
19
|
+
* bulkhead that refuses rather than queues.
|
|
20
|
+
*
|
|
21
|
+
* `make` builds a fresh pair over the case's clock, with
|
|
22
|
+
* {@link BREAKER_CONTRACT_DIALS} and two bulkhead permits.
|
|
23
|
+
*/
|
|
24
|
+
export declare const describeBreakerContract: (name: string, make: (clock: ContractClock) => Effect.Effect<BreakerUnderTest, unknown>) => void;
|
|
25
|
+
//# sourceMappingURL=breaker.contract.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"breaker.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/breaker.contract.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EACV,YAAY,EACZ,QAAQ,EACR,cAAc,EACf,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAe,MAAM,QAAQ,CAAC;AAG7C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AAErE,sEAAsE;AACtE,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,OAAO,EAAE,cAAc,CAAC;IACjC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;CAC7B;AAED,+CAA+C;AAC/C,eAAO,MAAM,sBAAsB,EAAE,YASpC,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,uBAAuB,GAClC,MAAM,MAAM,EACZ,MAAM,CAAC,KAAK,EAAE,aAAa,KAAK,MAAM,CAAC,MAAM,CAAC,gBAAgB,EAAE,OAAO,CAAC,KACvE,IAqKF,CAAC"}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { Declined, Overloaded, ProtocolFailure, Unavailable } from '@entifix/core';
|
|
3
|
+
import { Effect, Exit, Fiber } from 'effect';
|
|
4
|
+
import { describe, expect, it } from 'vitest';
|
|
5
|
+
/** The dials the cases are written against. */ export const BREAKER_CONTRACT_DIALS = {
|
|
6
|
+
windowType: 'count',
|
|
7
|
+
windowSize: 4,
|
|
8
|
+
failureRateThreshold: 0.5,
|
|
9
|
+
slowCallRateThreshold: 1,
|
|
10
|
+
slowCallDurationMs: 100,
|
|
11
|
+
minimumCalls: 4,
|
|
12
|
+
waitInOpenMs: 1000,
|
|
13
|
+
halfOpenPermits: 2
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* What every breaker and bulkhead must guarantee
|
|
17
|
+
* ([ADR 0017](../../../../../docs/adr/0017-circuit-breaker-and-bulkhead-ports.md)):
|
|
18
|
+
* a window that opens at its failure or slow-call rate and not before its
|
|
19
|
+
* minimum; an open breaker that refuses without calling, and lets probes
|
|
20
|
+
* through once its wait has passed; probes that close it or reopen it; a
|
|
21
|
+
* `Retry-After` that opens it at once and for as long as was asked; business
|
|
22
|
+
* and protocol failures that never move it; the forced states; and a full
|
|
23
|
+
* bulkhead that refuses rather than queues.
|
|
24
|
+
*
|
|
25
|
+
* `make` builds a fresh pair over the case's clock, with
|
|
26
|
+
* {@link BREAKER_CONTRACT_DIALS} and two bulkhead permits.
|
|
27
|
+
*/ export const describeBreakerContract = (name, make)=>{
|
|
28
|
+
const run = (effect)=>Effect.runPromise(effect);
|
|
29
|
+
const fresh = async ()=>{
|
|
30
|
+
let time = Date.UTC(2026, 0, 1);
|
|
31
|
+
const clock = {
|
|
32
|
+
now: ()=>time
|
|
33
|
+
};
|
|
34
|
+
const subject = await run(make(clock));
|
|
35
|
+
return _extends({}, subject, {
|
|
36
|
+
advance: (ms)=>{
|
|
37
|
+
time += ms;
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
const down = Effect.fail(new Unavailable({
|
|
42
|
+
dependency: 'stock'
|
|
43
|
+
}));
|
|
44
|
+
const fine = Effect.succeed('ok');
|
|
45
|
+
const call = (breaker, effect)=>run(Effect.exit(breaker.guard('stock')(effect)));
|
|
46
|
+
const tagOf = (exit)=>{
|
|
47
|
+
var _Exit_findErrorOption_value;
|
|
48
|
+
return Exit.isFailure(exit) ? (_Exit_findErrorOption_value = Exit.findErrorOption(exit).value) == null ? void 0 : _Exit_findErrorOption_value._tag : 'success';
|
|
49
|
+
};
|
|
50
|
+
describe(`CircuitBreaker contract: ${name}`, ()=>{
|
|
51
|
+
it('stays closed below the minimum number of calls', async ()=>{
|
|
52
|
+
const { breaker } = await fresh();
|
|
53
|
+
for(let index = 0; index < 3; index += 1)await call(breaker, down);
|
|
54
|
+
expect(await run(breaker.state('stock'))).toBe('closed');
|
|
55
|
+
});
|
|
56
|
+
it('opens at the failure rate and refuses without calling', async ()=>{
|
|
57
|
+
const { breaker } = await fresh();
|
|
58
|
+
await call(breaker, fine);
|
|
59
|
+
await call(breaker, fine);
|
|
60
|
+
await call(breaker, down);
|
|
61
|
+
await call(breaker, down);
|
|
62
|
+
// A call that ran would end in this defect, not in `BreakerOpen`.
|
|
63
|
+
const refused = await call(breaker, Effect.die('the call was made'));
|
|
64
|
+
expect(await run(breaker.state('stock'))).toBe('open');
|
|
65
|
+
expect(tagOf(refused)).toBe('BreakerOpen');
|
|
66
|
+
});
|
|
67
|
+
it('opens on slow calls even when every call succeeded', async ()=>{
|
|
68
|
+
const subject = await fresh();
|
|
69
|
+
const slow = Effect.sync(()=>subject.advance(150));
|
|
70
|
+
for(let index = 0; index < 4; index += 1)await call(subject.breaker, slow);
|
|
71
|
+
expect(await run(subject.breaker.state('stock'))).toBe('open');
|
|
72
|
+
});
|
|
73
|
+
it('goes half-open after its wait, and closes when the probes succeed', async ()=>{
|
|
74
|
+
const subject = await fresh();
|
|
75
|
+
for(let index = 0; index < 4; index += 1)await call(subject.breaker, down);
|
|
76
|
+
subject.advance(1000);
|
|
77
|
+
expect(await run(subject.breaker.state('stock'))).toBe('halfOpen');
|
|
78
|
+
await call(subject.breaker, fine);
|
|
79
|
+
await call(subject.breaker, fine);
|
|
80
|
+
expect(await run(subject.breaker.state('stock'))).toBe('closed');
|
|
81
|
+
});
|
|
82
|
+
it('reopens when the probes fail, and admits no more probes than its permits', async ()=>{
|
|
83
|
+
const subject = await fresh();
|
|
84
|
+
for(let index = 0; index < 4; index += 1)await call(subject.breaker, down);
|
|
85
|
+
subject.advance(1000);
|
|
86
|
+
const gate = Effect.never;
|
|
87
|
+
const first = Effect.runFork(subject.breaker.guard('stock')(gate));
|
|
88
|
+
const second = Effect.runFork(subject.breaker.guard('stock')(gate));
|
|
89
|
+
await new Promise((resolve)=>setTimeout(resolve, 0));
|
|
90
|
+
expect(tagOf(await call(subject.breaker, fine))).toBe('BreakerOpen');
|
|
91
|
+
await run(Fiber.interrupt(first));
|
|
92
|
+
await run(Fiber.interrupt(second));
|
|
93
|
+
const reprobe = await fresh();
|
|
94
|
+
for(let index = 0; index < 4; index += 1)await call(reprobe.breaker, down);
|
|
95
|
+
reprobe.advance(1000);
|
|
96
|
+
await call(reprobe.breaker, down);
|
|
97
|
+
await call(reprobe.breaker, fine);
|
|
98
|
+
expect(await run(reprobe.breaker.state('stock'))).toBe('open');
|
|
99
|
+
});
|
|
100
|
+
it('opens at once on Retry-After, for at least as long as was asked', async ()=>{
|
|
101
|
+
const subject = await fresh();
|
|
102
|
+
await call(subject.breaker, Effect.fail(new Overloaded({
|
|
103
|
+
retryAfterSeconds: 5
|
|
104
|
+
})));
|
|
105
|
+
expect(await run(subject.breaker.state('stock'))).toBe('open');
|
|
106
|
+
subject.advance(1000);
|
|
107
|
+
expect(await run(subject.breaker.state('stock'))).toBe('open');
|
|
108
|
+
subject.advance(4000);
|
|
109
|
+
expect(await run(subject.breaker.state('stock'))).toBe('halfOpen');
|
|
110
|
+
});
|
|
111
|
+
it('is never moved by a business answer or a protocol failure', async ()=>{
|
|
112
|
+
const { breaker } = await fresh();
|
|
113
|
+
for(let index = 0; index < 4; index += 1){
|
|
114
|
+
await call(breaker, Effect.fail(new Declined({})));
|
|
115
|
+
await call(breaker, Effect.fail(new ProtocolFailure({
|
|
116
|
+
reason: 'x'
|
|
117
|
+
})));
|
|
118
|
+
}
|
|
119
|
+
expect(await run(breaker.state('stock'))).toBe('closed');
|
|
120
|
+
});
|
|
121
|
+
it('obeys an operator: forced open refuses, disabled lets all through', async ()=>{
|
|
122
|
+
const { breaker } = await fresh();
|
|
123
|
+
await run(breaker.force('stock', 'forcedOpen'));
|
|
124
|
+
expect(tagOf(await call(breaker, fine))).toBe('BreakerOpen');
|
|
125
|
+
await run(breaker.force('stock', 'disabled'));
|
|
126
|
+
for(let index = 0; index < 8; index += 1)await call(breaker, down);
|
|
127
|
+
expect(await run(breaker.state('stock'))).toBe('disabled');
|
|
128
|
+
await run(breaker.force('stock', 'closed'));
|
|
129
|
+
expect(tagOf(await call(breaker, fine))).toBe('success');
|
|
130
|
+
});
|
|
131
|
+
it('keeps one key’s failures off another key', async ()=>{
|
|
132
|
+
const { breaker } = await fresh();
|
|
133
|
+
for(let index = 0; index < 4; index += 1)await call(breaker, down);
|
|
134
|
+
expect(await run(breaker.state('order'))).toBe('closed');
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
describe(`Bulkhead contract: ${name}`, ()=>{
|
|
138
|
+
it('refuses a call past its permits at once, and frees a permit however a call ends', async ()=>{
|
|
139
|
+
const { bulkhead } = await fresh();
|
|
140
|
+
const held = [
|
|
141
|
+
Effect.runFork(bulkhead.withPermit('stock')(Effect.never)),
|
|
142
|
+
Effect.runFork(bulkhead.withPermit('stock')(Effect.never))
|
|
143
|
+
];
|
|
144
|
+
await new Promise((resolve)=>setTimeout(resolve, 0));
|
|
145
|
+
expect(await run(bulkhead.inUse('stock'))).toBe(2);
|
|
146
|
+
const refused = await run(Effect.exit(bulkhead.withPermit('stock')(Effect.succeed('late'))));
|
|
147
|
+
expect(tagOf(refused)).toBe('BulkheadFull');
|
|
148
|
+
await run(Fiber.interrupt(held[0]));
|
|
149
|
+
await run(Effect.exit(bulkhead.withPermit('stock')(Effect.fail(new Unavailable({
|
|
150
|
+
dependency: 'stock'
|
|
151
|
+
})))));
|
|
152
|
+
expect(await run(bulkhead.inUse('stock'))).toBe(1);
|
|
153
|
+
await run(Fiber.interrupt(held[1]));
|
|
154
|
+
expect(await run(bulkhead.inUse('stock'))).toBe(0);
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
//# sourceMappingURL=breaker.contract.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/contracts/breaker.contract.ts"],"sourcesContent":["import {\n Declined,\n Overloaded,\n ProtocolFailure,\n Unavailable,\n} from '@entifix/core';\nimport type {\n BreakerDials,\n Bulkhead,\n CircuitBreaker,\n} from '@entifix/transactions';\nimport { Effect, Exit, Fiber } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\nimport type { ContractClock } from './idempotency-store.contract.js';\n\n/** What a case is handed: a breaker and a bulkhead over its clock. */\nexport interface BreakerUnderTest {\n readonly breaker: CircuitBreaker;\n readonly bulkhead: Bulkhead;\n}\n\n/** The dials the cases are written against. */\nexport const BREAKER_CONTRACT_DIALS: BreakerDials = {\n windowType: 'count',\n windowSize: 4,\n failureRateThreshold: 0.5,\n slowCallRateThreshold: 1,\n slowCallDurationMs: 100,\n minimumCalls: 4,\n waitInOpenMs: 1_000,\n halfOpenPermits: 2,\n};\n\n/**\n * What every breaker and bulkhead must guarantee\n * ([ADR 0017](../../../../../docs/adr/0017-circuit-breaker-and-bulkhead-ports.md)):\n * a window that opens at its failure or slow-call rate and not before its\n * minimum; an open breaker that refuses without calling, and lets probes\n * through once its wait has passed; probes that close it or reopen it; a\n * `Retry-After` that opens it at once and for as long as was asked; business\n * and protocol failures that never move it; the forced states; and a full\n * bulkhead that refuses rather than queues.\n *\n * `make` builds a fresh pair over the case's clock, with\n * {@link BREAKER_CONTRACT_DIALS} and two bulkhead permits.\n */\nexport const describeBreakerContract = (\n name: string,\n make: (clock: ContractClock) => Effect.Effect<BreakerUnderTest, unknown>,\n): void => {\n const run = <A, E>(effect: Effect.Effect<A, E>) => Effect.runPromise(effect);\n const fresh = async () => {\n let time = Date.UTC(2026, 0, 1);\n const clock: ContractClock = { now: () => time };\n const subject = await run(make(clock));\n return {\n ...subject,\n advance: (ms: number) => {\n time += ms;\n },\n };\n };\n\n const down = Effect.fail(new Unavailable({ dependency: 'stock' }));\n const fine = Effect.succeed('ok');\n\n const call = <A, E>(breaker: CircuitBreaker, effect: Effect.Effect<A, E>) =>\n run(Effect.exit(breaker.guard('stock')(effect)));\n\n const tagOf = (exit: Exit.Exit<unknown, unknown>) =>\n Exit.isFailure(exit)\n ? (Exit.findErrorOption(exit) as { value?: { _tag?: string } }).value\n ?._tag\n : 'success';\n\n describe(`CircuitBreaker contract: ${name}`, () => {\n it('stays closed below the minimum number of calls', async () => {\n const { breaker } = await fresh();\n for (let index = 0; index < 3; index += 1) await call(breaker, down);\n\n expect(await run(breaker.state('stock'))).toBe('closed');\n });\n\n it('opens at the failure rate and refuses without calling', async () => {\n const { breaker } = await fresh();\n await call(breaker, fine);\n await call(breaker, fine);\n await call(breaker, down);\n await call(breaker, down);\n // A call that ran would end in this defect, not in `BreakerOpen`.\n const refused = await call(breaker, Effect.die('the call was made'));\n\n expect(await run(breaker.state('stock'))).toBe('open');\n expect(tagOf(refused)).toBe('BreakerOpen');\n });\n\n it('opens on slow calls even when every call succeeded', async () => {\n const subject = await fresh();\n const slow = Effect.sync(() => subject.advance(150));\n for (let index = 0; index < 4; index += 1)\n await call(subject.breaker, slow);\n\n expect(await run(subject.breaker.state('stock'))).toBe('open');\n });\n\n it('goes half-open after its wait, and closes when the probes succeed', async () => {\n const subject = await fresh();\n for (let index = 0; index < 4; index += 1)\n await call(subject.breaker, down);\n subject.advance(1_000);\n\n expect(await run(subject.breaker.state('stock'))).toBe('halfOpen');\n await call(subject.breaker, fine);\n await call(subject.breaker, fine);\n expect(await run(subject.breaker.state('stock'))).toBe('closed');\n });\n\n it('reopens when the probes fail, and admits no more probes than its permits', async () => {\n const subject = await fresh();\n for (let index = 0; index < 4; index += 1)\n await call(subject.breaker, down);\n subject.advance(1_000);\n\n const gate = Effect.never;\n const first = Effect.runFork(subject.breaker.guard('stock')(gate));\n const second = Effect.runFork(subject.breaker.guard('stock')(gate));\n await new Promise(resolve => setTimeout(resolve, 0));\n expect(tagOf(await call(subject.breaker, fine))).toBe('BreakerOpen');\n await run(Fiber.interrupt(first));\n await run(Fiber.interrupt(second));\n\n const reprobe = await fresh();\n for (let index = 0; index < 4; index += 1)\n await call(reprobe.breaker, down);\n reprobe.advance(1_000);\n await call(reprobe.breaker, down);\n await call(reprobe.breaker, fine);\n expect(await run(reprobe.breaker.state('stock'))).toBe('open');\n });\n\n it('opens at once on Retry-After, for at least as long as was asked', async () => {\n const subject = await fresh();\n\n await call(\n subject.breaker,\n Effect.fail(new Overloaded({ retryAfterSeconds: 5 })),\n );\n expect(await run(subject.breaker.state('stock'))).toBe('open');\n subject.advance(1_000);\n expect(await run(subject.breaker.state('stock'))).toBe('open');\n subject.advance(4_000);\n expect(await run(subject.breaker.state('stock'))).toBe('halfOpen');\n });\n\n it('is never moved by a business answer or a protocol failure', async () => {\n const { breaker } = await fresh();\n for (let index = 0; index < 4; index += 1) {\n await call(breaker, Effect.fail(new Declined({})));\n await call(breaker, Effect.fail(new ProtocolFailure({ reason: 'x' })));\n }\n\n expect(await run(breaker.state('stock'))).toBe('closed');\n });\n\n it('obeys an operator: forced open refuses, disabled lets all through', async () => {\n const { breaker } = await fresh();\n\n await run(breaker.force('stock', 'forcedOpen'));\n expect(tagOf(await call(breaker, fine))).toBe('BreakerOpen');\n\n await run(breaker.force('stock', 'disabled'));\n for (let index = 0; index < 8; index += 1) await call(breaker, down);\n expect(await run(breaker.state('stock'))).toBe('disabled');\n\n await run(breaker.force('stock', 'closed'));\n expect(tagOf(await call(breaker, fine))).toBe('success');\n });\n\n it('keeps one key’s failures off another key', async () => {\n const { breaker } = await fresh();\n for (let index = 0; index < 4; index += 1) await call(breaker, down);\n\n expect(await run(breaker.state('order'))).toBe('closed');\n });\n });\n\n describe(`Bulkhead contract: ${name}`, () => {\n it('refuses a call past its permits at once, and frees a permit however a call ends', async () => {\n const { bulkhead } = await fresh();\n const held = [\n Effect.runFork(bulkhead.withPermit('stock')(Effect.never)),\n Effect.runFork(bulkhead.withPermit('stock')(Effect.never)),\n ];\n await new Promise(resolve => setTimeout(resolve, 0));\n\n expect(await run(bulkhead.inUse('stock'))).toBe(2);\n const refused = await run(\n Effect.exit(bulkhead.withPermit('stock')(Effect.succeed('late'))),\n );\n expect(tagOf(refused)).toBe('BulkheadFull');\n\n await run(Fiber.interrupt(held[0] as Fiber.Fiber<unknown, unknown>));\n await run(\n Effect.exit(\n bulkhead.withPermit('stock')(\n Effect.fail(new Unavailable({ dependency: 'stock' })),\n ),\n ),\n );\n expect(await run(bulkhead.inUse('stock'))).toBe(1);\n await run(Fiber.interrupt(held[1] as Fiber.Fiber<unknown, unknown>));\n expect(await run(bulkhead.inUse('stock'))).toBe(0);\n });\n });\n};\n"],"names":["Declined","Overloaded","ProtocolFailure","Unavailable","Effect","Exit","Fiber","describe","expect","it","BREAKER_CONTRACT_DIALS","windowType","windowSize","failureRateThreshold","slowCallRateThreshold","slowCallDurationMs","minimumCalls","waitInOpenMs","halfOpenPermits","describeBreakerContract","name","make","run","effect","runPromise","fresh","time","Date","UTC","clock","now","subject","advance","ms","down","fail","dependency","fine","succeed","call","breaker","exit","guard","tagOf","isFailure","findErrorOption","value","_tag","index","state","toBe","refused","die","slow","sync","gate","never","first","runFork","second","Promise","resolve","setTimeout","interrupt","reprobe","retryAfterSeconds","reason","force","bulkhead","held","withPermit","inUse"],"mappings":";AAAA,SACEA,QAAQ,EACRC,UAAU,EACVC,eAAe,EACfC,WAAW,QACN,gBAAgB;AAMvB,SAASC,MAAM,EAAEC,IAAI,EAAEC,KAAK,QAAQ,SAAS;AAC7C,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAU9C,6CAA6C,GAC7C,OAAO,MAAMC,yBAAuC;IAClDC,YAAY;IACZC,YAAY;IACZC,sBAAsB;IACtBC,uBAAuB;IACvBC,oBAAoB;IACpBC,cAAc;IACdC,cAAc;IACdC,iBAAiB;AACnB,EAAE;AAEF;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,0BAA0B,CACrCC,MACAC;IAEA,MAAMC,MAAM,CAAOC,SAAgCnB,OAAOoB,UAAU,CAACD;IACrE,MAAME,QAAQ;QACZ,IAAIC,OAAOC,KAAKC,GAAG,CAAC,MAAM,GAAG;QAC7B,MAAMC,QAAuB;YAAEC,KAAK,IAAMJ;QAAK;QAC/C,MAAMK,UAAU,MAAMT,IAAID,KAAKQ;QAC/B,OAAO,aACFE;YACHC,SAAS,CAACC;gBACRP,QAAQO;YACV;;IAEJ;IAEA,MAAMC,OAAO9B,OAAO+B,IAAI,CAAC,IAAIhC,YAAY;QAAEiC,YAAY;IAAQ;IAC/D,MAAMC,OAAOjC,OAAOkC,OAAO,CAAC;IAE5B,MAAMC,OAAO,CAAOC,SAAyBjB,SAC3CD,IAAIlB,OAAOqC,IAAI,CAACD,QAAQE,KAAK,CAAC,SAASnB;IAEzC,MAAMoB,QAAQ,CAACF;YAET;eADJpC,KAAKuC,SAAS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F,EAAE"}
|
|
@@ -12,5 +12,5 @@ export declare const flowEngineContractCatalog: FragmentCatalog;
|
|
|
12
12
|
* `make` builds a fresh engine over the contract's catalog and the participant
|
|
13
13
|
* a case supplies.
|
|
14
14
|
*/
|
|
15
|
-
export declare const describeFlowEngineContract: (name: string, make: (catalog: FragmentCatalog, participant: FakeParticipant) => FlowEngine) => void;
|
|
15
|
+
export declare const describeFlowEngineContract: (name: string, make: (catalog: FragmentCatalog, participant: FakeParticipant) => FlowEngine | Promise<FlowEngine>) => void;
|
|
16
16
|
//# sourceMappingURL=flow-engine.contract.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow-engine.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/flow-engine.contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,eAAe,EAKrB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAIxD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AA+BjE,sDAAsD;AACtD,eAAO,MAAM,yBAAyB,EAAE,eAKtC,CAAC;AA6BH;;;;;;;;GAQG;AACH,eAAO,MAAM,0BAA0B,GACrC,MAAM,MAAM,EACZ,MAAM,
|
|
1
|
+
{"version":3,"file":"flow-engine.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/flow-engine.contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,eAAe,EAKrB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAIxD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AA+BjE,sDAAsD;AACtD,eAAO,MAAM,yBAAyB,EAAE,eAKtC,CAAC;AA6BH;;;;;;;;GAQG;AACH,eAAO,MAAM,0BAA0B,GACrC,MAAM,MAAM,EACZ,MAAM,CACJ,OAAO,EAAE,eAAe,EACxB,WAAW,EAAE,eAAe,KACzB,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,KACpC,IA2HF,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
2
|
import { defineCatalog, defineFragment, fragmentRef } from '@entifix/business/flow';
|
|
3
3
|
import { Declined } from '@entifix/core';
|
|
4
|
-
import { Effect, Schema } from 'effect';
|
|
4
|
+
import { Effect, Schedule, Schema } from 'effect';
|
|
5
5
|
import { describe, expect, it } from 'vitest';
|
|
6
6
|
const contract = {
|
|
7
7
|
input: Schema.Unknown,
|
|
@@ -73,10 +73,19 @@ const succeeding = ()=>Effect.succeed({
|
|
|
73
73
|
* a case supplies.
|
|
74
74
|
*/ export const describeFlowEngineContract = (name, make)=>{
|
|
75
75
|
const run = (effect)=>Effect.runPromise(effect);
|
|
76
|
-
|
|
76
|
+
/**
|
|
77
|
+
* The flow's status once it has stopped moving. A start answers the flow id,
|
|
78
|
+
* never the outcome — a durable engine runs the slip detached — so a case
|
|
79
|
+
* reads the state the flow comes to rest in, a wait included.
|
|
80
|
+
*/ const settled = (engine, flowId)=>run(engine.status(flowId).pipe(Effect.repeat({
|
|
81
|
+
until: (status)=>status.state !== 'running',
|
|
82
|
+
schedule: Schedule.spaced('10 millis'),
|
|
83
|
+
times: 200
|
|
84
|
+
})));
|
|
85
|
+
const state = async (engine, flowId)=>(await settled(engine, flowId)).state;
|
|
77
86
|
describe(`FlowEngine contract: ${name}`, ()=>{
|
|
78
87
|
it('answers the slip’s flow id, and the same one for a repeated key', async ()=>{
|
|
79
|
-
const engine = make(flowEngineContractCatalog, succeeding);
|
|
88
|
+
const engine = await make(flowEngineContractCatalog, succeeding);
|
|
80
89
|
const slip = slipOf('flow-1', [
|
|
81
90
|
hold,
|
|
82
91
|
take,
|
|
@@ -94,7 +103,7 @@ const succeeding = ()=>Effect.succeed({
|
|
|
94
103
|
});
|
|
95
104
|
});
|
|
96
105
|
it('completes a flow whose every step succeeds', async ()=>{
|
|
97
|
-
const engine = make(flowEngineContractCatalog, succeeding);
|
|
106
|
+
const engine = await make(flowEngineContractCatalog, succeeding);
|
|
98
107
|
await run(engine.start(slipOf('flow-1', [
|
|
99
108
|
hold,
|
|
100
109
|
take,
|
|
@@ -103,7 +112,7 @@ const succeeding = ()=>Effect.succeed({
|
|
|
103
112
|
expect(await state(engine, 'flow-1')).toBe('completed');
|
|
104
113
|
});
|
|
105
114
|
it('compensates a failure before the commit point', async ()=>{
|
|
106
|
-
const engine = make(flowEngineContractCatalog, failing('take'));
|
|
115
|
+
const engine = await make(flowEngineContractCatalog, failing('take'));
|
|
107
116
|
await run(engine.start(slipOf('flow-1', [
|
|
108
117
|
hold,
|
|
109
118
|
take,
|
|
@@ -112,19 +121,19 @@ const succeeding = ()=>Effect.succeed({
|
|
|
112
121
|
expect(await state(engine, 'flow-1')).toBe('compensated');
|
|
113
122
|
});
|
|
114
123
|
it('suspends a failure after the commit point, at that step', async ()=>{
|
|
115
|
-
const engine = make(flowEngineContractCatalog, failing('settle'));
|
|
124
|
+
const engine = await make(flowEngineContractCatalog, failing('settle'));
|
|
116
125
|
await run(engine.start(slipOf('flow-1', [
|
|
117
126
|
hold,
|
|
118
127
|
take,
|
|
119
128
|
settle
|
|
120
129
|
]), 'k'));
|
|
121
|
-
expect(await
|
|
130
|
+
expect(await settled(engine, 'flow-1')).toMatchObject({
|
|
122
131
|
state: 'suspended',
|
|
123
132
|
step: 'settle'
|
|
124
133
|
});
|
|
125
134
|
});
|
|
126
135
|
it('waits for the signal it waits for, and refuses any other', async ()=>{
|
|
127
|
-
const engine = make(flowEngineContractCatalog, succeeding);
|
|
136
|
+
const engine = await make(flowEngineContractCatalog, succeeding);
|
|
128
137
|
await run(engine.start(slipOf('flow-1', [
|
|
129
138
|
take,
|
|
130
139
|
wait,
|
|
@@ -140,20 +149,47 @@ const succeeding = ()=>Effect.succeed({
|
|
|
140
149
|
const late = await run(Effect.flip(engine.signal('flow-1', 'await', {})));
|
|
141
150
|
expect(late._tag).toBe('FlowSignalRejected');
|
|
142
151
|
});
|
|
152
|
+
it('completes a wait by what it is correlated with', async ()=>{
|
|
153
|
+
const engine = await make(flowEngineContractCatalog, succeeding);
|
|
154
|
+
const slip = slipOf('flow-1', [
|
|
155
|
+
take,
|
|
156
|
+
wait,
|
|
157
|
+
settle
|
|
158
|
+
]);
|
|
159
|
+
const correlated = _extends({}, slip, {
|
|
160
|
+
stages: slip.stages.map((stage)=>_extends({}, stage, {
|
|
161
|
+
steps: stage.steps.map((step)=>step.step === 'await' ? _extends({}, step, {
|
|
162
|
+
parameters: {
|
|
163
|
+
correlation: 'order-7'
|
|
164
|
+
}
|
|
165
|
+
}) : step)
|
|
166
|
+
}))
|
|
167
|
+
});
|
|
168
|
+
await run(engine.start(correlated, 'k'));
|
|
169
|
+
expect(await state(engine, 'flow-1')).toBe('waiting');
|
|
170
|
+
const stranger = await run(Effect.flip(engine.signalCorrelated('order-8', 'await', {})));
|
|
171
|
+
expect(stranger._tag).toBe('FlowNotFound');
|
|
172
|
+
await run(engine.signalCorrelated('order-7', 'await', {
|
|
173
|
+
delivered: true
|
|
174
|
+
}));
|
|
175
|
+
expect(await state(engine, 'flow-1')).toBe('completed');
|
|
176
|
+
});
|
|
143
177
|
it('interrupts a waiting flow', async ()=>{
|
|
144
|
-
const engine = make(flowEngineContractCatalog, succeeding);
|
|
178
|
+
const engine = await make(flowEngineContractCatalog, succeeding);
|
|
145
179
|
await run(engine.start(slipOf('flow-1', [
|
|
146
180
|
take,
|
|
147
181
|
wait
|
|
148
182
|
]), 'k'));
|
|
183
|
+
expect(await state(engine, 'flow-1')).toBe('waiting');
|
|
149
184
|
await run(engine.interrupt('flow-1'));
|
|
150
185
|
expect(await state(engine, 'flow-1')).toBe('interrupted');
|
|
151
186
|
});
|
|
152
187
|
it('answers FlowNotFound for a flow it never started', async ()=>{
|
|
153
|
-
const engine = make(flowEngineContractCatalog, succeeding);
|
|
188
|
+
const engine = await make(flowEngineContractCatalog, succeeding);
|
|
154
189
|
for (const effect of [
|
|
155
190
|
engine.status('nope'),
|
|
156
191
|
engine.signal('nope', 'await', {}),
|
|
192
|
+
engine.signalCorrelated('nope', 'await', {}),
|
|
157
193
|
engine.interrupt('nope')
|
|
158
194
|
])expect((await run(Effect.flip(effect)))._tag).toBe('FlowNotFound');
|
|
159
195
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/contracts/flow-engine.contract.ts"],"sourcesContent":["import {\n defineCatalog,\n defineFragment,\n type FragmentCatalog,\n type FragmentDescriptor,\n fragmentRef,\n type Slip,\n type SlipStep,\n} from '@entifix/business/flow';\nimport { Declined } from '@entifix/core';\nimport type { FlowEngine } from '@entifix/transactions';\nimport { Effect, Schema } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\nimport type { FakeParticipant } from '../doubles/flow-engine.js';\n\nconst contract = {\n input: Schema.Unknown,\n output: Schema.Unknown,\n failure: Schema.Unknown,\n};\n\nconst fragment = (\n id: string,\n kind: FragmentDescriptor['kind'],\n): FragmentDescriptor =>\n defineFragment({\n id: `contract.${id}`,\n version: 1,\n module: 'contract',\n kind,\n participant: 'contract',\n call: { method: 'POST', path: `/api/${id}` },\n ...(kind === 'compensatable'\n ? { compensation: { method: 'DELETE', path: `/api/${id}/:id` } as const }\n : {}),\n cardinality: 'one',\n contract,\n });\n\nconst hold = fragment('hold', 'compensatable');\nconst take = fragment('take', 'pivot');\nconst settle = fragment('settle', 'retriable');\nconst wait = fragment('await', 'wait');\n\n/** The catalog every case composes its slips from. */\nexport const flowEngineContractCatalog: FragmentCatalog = defineCatalog([\n hold,\n take,\n settle,\n wait,\n]);\n\nconst stepOf = (descriptor: FragmentDescriptor): SlipStep => ({\n ref: fragmentRef(descriptor),\n step: descriptor.id.replace('contract.', ''),\n cardinality: 'one',\n});\n\nconst slipOf = (\n flowId: string,\n steps: readonly FragmentDescriptor[],\n): Slip => ({\n slipVersion: 1,\n flowId,\n recipe: 'contract',\n stages: [{ name: 'main', steps: steps.map(stepOf) }],\n resolution: [],\n composedAt: '2026-01-01T00:00:00.000Z',\n});\n\nconst failing =\n (failAt: string): FakeParticipant =>\n step =>\n step.step === failAt\n ? Effect.fail(new Declined({ reason: 'refused' }))\n : Effect.succeed({ ok: true });\n\nconst succeeding: FakeParticipant = () => Effect.succeed({ ok: true });\n\n/**\n * What every {@link FlowEngine} must guarantee, whatever runs it: a start is\n * idempotent on its key, a failure before the commit point compensates and one\n * after it suspends, a wait takes the signal it waits for and no other, and an\n * unknown flow is a typed `FlowNotFound`.\n *\n * `make` builds a fresh engine over the contract's catalog and the participant\n * a case supplies.\n */\nexport const describeFlowEngineContract = (\n name: string,\n make: (catalog: FragmentCatalog, participant: FakeParticipant) => FlowEngine,\n): void => {\n const run = <A, E>(effect: Effect.Effect<A, E>) => Effect.runPromise(effect);\n const state = async (engine: FlowEngine, flowId: string) =>\n (await run(engine.status(flowId))).state;\n\n describe(`FlowEngine contract: ${name}`, () => {\n it('answers the slip’s flow id, and the same one for a repeated key', async () => {\n const engine = make(flowEngineContractCatalog, succeeding);\n const slip = slipOf('flow-1', [hold, take, settle]);\n\n const first = await run(engine.start(slip, 'key-1'));\n const again = await run(engine.start(slipOf('flow-2', [hold]), 'key-1'));\n\n expect(first).toEqual({ flowId: 'flow-1' });\n expect(again).toEqual({ flowId: 'flow-1' });\n });\n\n it('completes a flow whose every step succeeds', async () => {\n const engine = make(flowEngineContractCatalog, succeeding);\n await run(engine.start(slipOf('flow-1', [hold, take, settle]), 'k'));\n\n expect(await state(engine, 'flow-1')).toBe('completed');\n });\n\n it('compensates a failure before the commit point', async () => {\n const engine = make(flowEngineContractCatalog, failing('take'));\n await run(engine.start(slipOf('flow-1', [hold, take, settle]), 'k'));\n\n expect(await state(engine, 'flow-1')).toBe('compensated');\n });\n\n it('suspends a failure after the commit point, at that step', async () => {\n const engine = make(flowEngineContractCatalog, failing('settle'));\n await run(engine.start(slipOf('flow-1', [hold, take, settle]), 'k'));\n\n expect(await run(engine.status('flow-1'))).toMatchObject({\n state: 'suspended',\n step: 'settle',\n });\n });\n\n it('waits for the signal it waits for, and refuses any other', async () => {\n const engine = make(flowEngineContractCatalog, succeeding);\n await run(engine.start(slipOf('flow-1', [take, wait, settle]), 'k'));\n\n expect(await state(engine, 'flow-1')).toBe('waiting');\n const wrong = await run(\n Effect.flip(engine.signal('flow-1', 'elsewhere', {})),\n );\n expect(wrong._tag).toBe('FlowSignalRejected');\n\n await run(engine.signal('flow-1', 'await', { delivered: true }));\n expect(await state(engine, 'flow-1')).toBe('completed');\n\n const late = await run(Effect.flip(engine.signal('flow-1', 'await', {})));\n expect(late._tag).toBe('FlowSignalRejected');\n });\n\n it('interrupts a waiting flow', async () => {\n const engine = make(flowEngineContractCatalog, succeeding);\n await run(engine.start(slipOf('flow-1', [take, wait]), 'k'));\n\n await run(engine.interrupt('flow-1'));\n\n expect(await state(engine, 'flow-1')).toBe('interrupted');\n });\n\n it('answers FlowNotFound for a flow it never started', async () => {\n const engine = make(flowEngineContractCatalog, succeeding);\n\n for (const effect of [\n engine.status('nope'),\n engine.signal('nope', 'await', {}),\n engine.interrupt('nope'),\n ])\n expect((await run(Effect.flip(effect)))._tag).toBe('FlowNotFound');\n });\n });\n};\n"],"names":["defineCatalog","defineFragment","fragmentRef","Declined","Effect","Schema","describe","expect","it","contract","input","Unknown","output","failure","fragment","id","kind","version","module","participant","call","method","path","compensation","cardinality","hold","take","settle","wait","flowEngineContractCatalog","stepOf","descriptor","ref","step","replace","slipOf","flowId","steps","slipVersion","recipe","stages","name","map","resolution","composedAt","failing","failAt","fail","reason","succeed","ok","succeeding","describeFlowEngineContract","make","run","effect","runPromise","state","engine","status","slip","first","start","again","toEqual","toBe","toMatchObject","wrong","flip","signal","_tag","delivered","late","interrupt"],"mappings":";AAAA,SACEA,aAAa,EACbC,cAAc,EAGdC,WAAW,QAGN,yBAAyB;AAChC,SAASC,QAAQ,QAAQ,gBA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A2BsB;YAE/C,KAAK,MAAMI,UAAU;gBACnBG,OAAOC,MAAM,CAAC;gBACdD,OAAOW,MAAM,CAAC,QAAQ,SAAS,CAAC;gBAChCX,OAAOe,SAAS,CAAC;aAClB,CACClE,OAAO,AAAC,CAAA,MAAM+C,IAAIlD,OAAOgE,IAAI,CAACb,QAAO,EAAGe,IAAI,EAAEL,IAAI,CAAC;QACvD;IACF;AACF,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../src/contracts/flow-engine.contract.ts"],"sourcesContent":["import {\n defineCatalog,\n defineFragment,\n type FragmentCatalog,\n type FragmentDescriptor,\n fragmentRef,\n type Slip,\n type SlipStep,\n} from '@entifix/business/flow';\nimport { Declined } from '@entifix/core';\nimport type { FlowEngine } from '@entifix/transactions';\nimport { Effect, Schedule, Schema } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\nimport type { FakeParticipant } from '../doubles/flow-engine.js';\n\nconst contract = {\n input: Schema.Unknown,\n output: Schema.Unknown,\n failure: Schema.Unknown,\n};\n\nconst fragment = (\n id: string,\n kind: FragmentDescriptor['kind'],\n): FragmentDescriptor =>\n defineFragment({\n id: `contract.${id}`,\n version: 1,\n module: 'contract',\n kind,\n participant: 'contract',\n call: { method: 'POST', path: `/api/${id}` },\n ...(kind === 'compensatable'\n ? { compensation: { method: 'DELETE', path: `/api/${id}/:id` } as const }\n : {}),\n cardinality: 'one',\n contract,\n });\n\nconst hold = fragment('hold', 'compensatable');\nconst take = fragment('take', 'pivot');\nconst settle = fragment('settle', 'retriable');\nconst wait = fragment('await', 'wait');\n\n/** The catalog every case composes its slips from. */\nexport const flowEngineContractCatalog: FragmentCatalog = defineCatalog([\n hold,\n take,\n settle,\n wait,\n]);\n\nconst stepOf = (descriptor: FragmentDescriptor): SlipStep => ({\n ref: fragmentRef(descriptor),\n step: descriptor.id.replace('contract.', ''),\n cardinality: 'one',\n});\n\nconst slipOf = (\n flowId: string,\n steps: readonly FragmentDescriptor[],\n): Slip => ({\n slipVersion: 1,\n flowId,\n recipe: 'contract',\n stages: [{ name: 'main', steps: steps.map(stepOf) }],\n resolution: [],\n composedAt: '2026-01-01T00:00:00.000Z',\n});\n\nconst failing =\n (failAt: string): FakeParticipant =>\n step =>\n step.step === failAt\n ? Effect.fail(new Declined({ reason: 'refused' }))\n : Effect.succeed({ ok: true });\n\nconst succeeding: FakeParticipant = () => Effect.succeed({ ok: true });\n\n/**\n * What every {@link FlowEngine} must guarantee, whatever runs it: a start is\n * idempotent on its key, a failure before the commit point compensates and one\n * after it suspends, a wait takes the signal it waits for and no other, and an\n * unknown flow is a typed `FlowNotFound`.\n *\n * `make` builds a fresh engine over the contract's catalog and the participant\n * a case supplies.\n */\nexport const describeFlowEngineContract = (\n name: string,\n make: (\n catalog: FragmentCatalog,\n participant: FakeParticipant,\n ) => FlowEngine | Promise<FlowEngine>,\n): void => {\n const run = <A, E>(effect: Effect.Effect<A, E>) => Effect.runPromise(effect);\n /**\n * The flow's status once it has stopped moving. A start answers the flow id,\n * never the outcome — a durable engine runs the slip detached — so a case\n * reads the state the flow comes to rest in, a wait included.\n */\n const settled = (engine: FlowEngine, flowId: string) =>\n run(\n engine.status(flowId).pipe(\n Effect.repeat({\n until: status => status.state !== 'running',\n schedule: Schedule.spaced('10 millis'),\n times: 200,\n }),\n ),\n );\n const state = async (engine: FlowEngine, flowId: string) =>\n (await settled(engine, flowId)).state;\n\n describe(`FlowEngine contract: ${name}`, () => {\n it('answers the slip’s flow id, and the same one for a repeated key', async () => {\n const engine = await make(flowEngineContractCatalog, succeeding);\n const slip = slipOf('flow-1', [hold, take, settle]);\n\n const first = await run(engine.start(slip, 'key-1'));\n const again = await run(engine.start(slipOf('flow-2', [hold]), 'key-1'));\n\n expect(first).toEqual({ flowId: 'flow-1' });\n expect(again).toEqual({ flowId: 'flow-1' });\n });\n\n it('completes a flow whose every step succeeds', async () => {\n const engine = await make(flowEngineContractCatalog, succeeding);\n await run(engine.start(slipOf('flow-1', [hold, take, settle]), 'k'));\n\n expect(await state(engine, 'flow-1')).toBe('completed');\n });\n\n it('compensates a failure before the commit point', async () => {\n const engine = await make(flowEngineContractCatalog, failing('take'));\n await run(engine.start(slipOf('flow-1', [hold, take, settle]), 'k'));\n\n expect(await state(engine, 'flow-1')).toBe('compensated');\n });\n\n it('suspends a failure after the commit point, at that step', async () => {\n const engine = await make(flowEngineContractCatalog, failing('settle'));\n await run(engine.start(slipOf('flow-1', [hold, take, settle]), 'k'));\n\n expect(await settled(engine, 'flow-1')).toMatchObject({\n state: 'suspended',\n step: 'settle',\n });\n });\n\n it('waits for the signal it waits for, and refuses any other', async () => {\n const engine = await make(flowEngineContractCatalog, succeeding);\n await run(engine.start(slipOf('flow-1', [take, wait, settle]), 'k'));\n\n expect(await state(engine, 'flow-1')).toBe('waiting');\n const wrong = await run(\n Effect.flip(engine.signal('flow-1', 'elsewhere', {})),\n );\n expect(wrong._tag).toBe('FlowSignalRejected');\n\n await run(engine.signal('flow-1', 'await', { delivered: true }));\n expect(await state(engine, 'flow-1')).toBe('completed');\n\n const late = await run(Effect.flip(engine.signal('flow-1', 'await', {})));\n expect(late._tag).toBe('FlowSignalRejected');\n });\n\n it('completes a wait by what it is correlated with', async () => {\n const engine = await make(flowEngineContractCatalog, succeeding);\n const slip = slipOf('flow-1', [take, wait, settle]);\n const correlated: Slip = {\n ...slip,\n stages: slip.stages.map(stage => ({\n ...stage,\n steps: stage.steps.map(step =>\n step.step === 'await'\n ? { ...step, parameters: { correlation: 'order-7' } }\n : step,\n ),\n })),\n };\n await run(engine.start(correlated, 'k'));\n expect(await state(engine, 'flow-1')).toBe('waiting');\n\n const stranger = await run(\n Effect.flip(engine.signalCorrelated('order-8', 'await', {})),\n );\n expect(stranger._tag).toBe('FlowNotFound');\n\n await run(\n engine.signalCorrelated('order-7', 'await', { delivered: true }),\n );\n expect(await state(engine, 'flow-1')).toBe('completed');\n });\n\n it('interrupts a waiting flow', async () => {\n const engine = await make(flowEngineContractCatalog, succeeding);\n await run(engine.start(slipOf('flow-1', [take, wait]), 'k'));\n expect(await state(engine, 'flow-1')).toBe('waiting');\n\n await run(engine.interrupt('flow-1'));\n\n expect(await state(engine, 'flow-1')).toBe('interrupted');\n });\n\n it('answers FlowNotFound for a flow it never started', async () => {\n const engine = await make(flowEngineContractCatalog, succeeding);\n\n for (const effect of [\n engine.status('nope'),\n engine.signal('nope', 'await', {}),\n engine.signalCorrelated('nope', 'await', {}),\n engine.interrupt('nope'),\n ])\n expect((await run(Effect.flip(effect)))._tag).toBe('FlowNotFound');\n });\n });\n};\n"],"names":["defineCatalog","defineFragment","fragmentRef","Declined","Effect","Schedule","Schema","describe","expect","it","contract","input","Unknown","output","failure","fragment","id","kind","version","module","participant","call","method","path","compensation","cardinality","hold","take","settle","wait","flowEngineContractCatalog","stepOf","descriptor","ref","step","replace","slipOf","flowId","steps","slipVersion","recipe","stages","name","map","resolution","composedAt","failing","failAt","fail","reason","succeed","ok","succeeding","describeFlowEngineContract","make","run","effect","runPromise","settled","engine","status","pipe","repeat","until","state","schedule","spaced","times","slip","first","start","again","toEqual","toBe","toMatchObject","wrong","flip","signal","_tag","delivered","late","correlated","stage","parameters","correlation","stranger","signalCorrelated","interrupt"],"mappings":";AAAA,SACEA,aAAa,EACbC,cAAc,EAGdC,WAAW,QAGN,yBAAyB;AAChC,SAASC,QAAQ,QAAQ,gBAAgB;AAEzC,SAASC,MAAM,EAAEC,QAAQ,EAAEC,MAAM,QAAQ,SAAS;AAClD,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAI9C,MAAMC,WAAW;IACfC,OAAOL,OAAOM,OAAO;IACrBC,QAAQP,OAAOM,OAAO;IACtBE,SAASR,OAAOM,OAAO;AACzB;AAEA,MAAMG,WAAW,CACfC,IACAC,OAEAhB,eAAe;QACbe,IAAI,CAAC,SAAS,EAAEA,IAAI;QACpBE,SAAS;QACTC,QAAQ;QACRF;QACAG,aAAa;QACbC,MAAM;YAAEC,QAAQ;YAAQC,MAAM,CA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,CAAC;AAChD,cAAc,sBAAsB,CAAC;AACrC,cAAc,0BAA0B,CAAC;AACzC,cAAc,iCAAiC,CAAC;AAChD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/contracts/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,oCAAoC,CAAC;AACnD,cAAc,iCAAiC,CAAC;AAChD,cAAc,uBAAuB,CAAC;AACtC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iCAAiC,CAAC;AAChD,cAAc,sBAAsB,CAAC;AACrC,cAAc,0BAA0B,CAAC;AACzC,cAAc,iCAAiC,CAAC;AAChD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wBAAwB,CAAC"}
|
package/dist/contracts/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/contracts/index.ts"],"sourcesContent":["export * from './entity-facet-counter.contract.js';\nexport * from './entity-repository.contract.js';\nexport * from './failure.contract.js';\nexport * from './flow-engine.contract.js';\nexport * from './idempotency-store.contract.js';\nexport * from './outbox.contract.js';\nexport * from './saga-store.contract.js';\nexport * from './transaction-ports.contract.js';\nexport * from './unit-of-work.contract.js';\nexport * from './variants.contract.js';\n"],"names":[],"mappings":"AAAA,cAAc,qCAAqC;AACnD,cAAc,kCAAkC;AAChD,cAAc,wBAAwB;AACtC,cAAc,4BAA4B;AAC1C,cAAc,kCAAkC;AAChD,cAAc,uBAAuB;AACrC,cAAc,2BAA2B;AACzC,cAAc,kCAAkC;AAChD,cAAc,6BAA6B;AAC3C,cAAc,yBAAyB"}
|
|
1
|
+
{"version":3,"sources":["../../src/contracts/index.ts"],"sourcesContent":["export * from './breaker.contract.js';\nexport * from './entity-facet-counter.contract.js';\nexport * from './entity-repository.contract.js';\nexport * from './failure.contract.js';\nexport * from './flow-engine.contract.js';\nexport * from './idempotency-store.contract.js';\nexport * from './outbox.contract.js';\nexport * from './saga-store.contract.js';\nexport * from './transaction-ports.contract.js';\nexport * from './unit-of-work.contract.js';\nexport * from './variants.contract.js';\n"],"names":[],"mappings":"AAAA,cAAc,wBAAwB;AACtC,cAAc,qCAAqC;AACnD,cAAc,kCAAkC;AAChD,cAAc,wBAAwB;AACtC,cAAc,4BAA4B;AAC1C,cAAc,kCAAkC;AAChD,cAAc,uBAAuB;AACrC,cAAc,2BAA2B;AACzC,cAAc,kCAAkC;AAChD,cAAc,6BAA6B;AAC3C,cAAc,yBAAyB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { EntityRepository } from '@entifix/business';
|
|
2
|
-
import { type
|
|
1
|
+
import type { EntityRepository, RepositoryFailure } from '@entifix/business';
|
|
2
|
+
import { type Entity } from '@entifix/core';
|
|
3
3
|
export interface InMemoryEntityRepository extends EntityRepository {
|
|
4
4
|
/** Everything currently stored, in insertion order. */
|
|
5
5
|
readonly items: Entity[];
|
|
@@ -9,7 +9,7 @@ export interface InMemoryEntityRepository extends EntityRepository {
|
|
|
9
9
|
* Makes the next call to any method fail with `error`, so error branches are
|
|
10
10
|
* reachable without reaching for a mocking library.
|
|
11
11
|
*/
|
|
12
|
-
failNext(error:
|
|
12
|
+
failNext(error: RepositoryFailure): void;
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
15
|
* In-memory {@link EntityRepository}: the default double for anything that
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entity-repository.d.ts","sourceRoot":"","sources":["../../src/doubles/entity-repository.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"entity-repository.d.ts","sourceRoot":"","sources":["../../src/doubles/entity-repository.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC7E,OAAO,EAKL,KAAK,MAAM,EAQZ,MAAM,eAAe,CAAC;AAiCvB,MAAM,WAAW,wBAAyB,SAAQ,gBAAgB;IAChE,uDAAuD;IACvD,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC;IACzB,4DAA4D;IAC5D,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI,CAAC;CAC1C;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,4BAA4B,GACvC,OAAM,MAAM,EAAO,KAClB,wBAqGF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { applyFiltering, applySorting, deserializeSingleEntity,
|
|
1
|
+
import { applyFiltering, applySorting, deserializeSingleEntity, extractMetaAccessors, NotFound, serializeEntity } from '@entifix/core';
|
|
2
2
|
import { Effect } from 'effect';
|
|
3
3
|
/**
|
|
4
4
|
* A copy of `entity` that shares no state with it.
|
|
@@ -54,9 +54,7 @@ import { Effect } from 'effect';
|
|
|
54
54
|
});
|
|
55
55
|
const get = (id)=>guard(()=>{
|
|
56
56
|
const found = items.find((item)=>item.id === id);
|
|
57
|
-
return found === undefined ? Effect.fail(new
|
|
58
|
-
id
|
|
59
|
-
})) : copyOf(found);
|
|
57
|
+
return found === undefined ? Effect.fail(new NotFound({})) : copyOf(found);
|
|
60
58
|
});
|
|
61
59
|
const save = (entity)=>guard(()=>{
|
|
62
60
|
var _entity_id;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/doubles/entity-repository.ts"],"sourcesContent":["import type { EntityRepository } from '@entifix/business';\nimport {\n applyFiltering,\n applySorting,\n deserializeSingleEntity,\n
|
|
1
|
+
{"version":3,"sources":["../../src/doubles/entity-repository.ts"],"sourcesContent":["import type { EntityRepository, RepositoryFailure } from '@entifix/business';\nimport {\n applyFiltering,\n applySorting,\n deserializeSingleEntity,\n type EntifixError,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLoadRequest,\n type EntityPage,\n extractMetaAccessors,\n NotFound,\n serializeEntity,\n} from '@entifix/core';\nimport { Effect } from 'effect';\n\n/**\n * A copy of `entity` that shares no state with it.\n *\n * Through the entity's own mapping — serialize, then deserialize — because that\n * is what a real adapter does to every record on the way in and out: a caller\n * can never hold the instance the store keeps, and a member the mapping drops\n * (`hidden`, `readonly`) does not survive a save here either. A class that\n * declares no accessors has no mapping to go through, so it is copied member by\n * member instead; plain spec fixtures are the case this keeps working.\n */\nconst copyOf = <TEntity extends Entity>(\n entity: TEntity,\n): Effect.Effect<TEntity, EntifixError> => {\n const entityConstructor = entity.constructor as EntityConstructor<TEntity>;\n if (extractMetaAccessors(entityConstructor).length === 0) {\n return Effect.succeed(\n Object.assign(\n Object.create(Object.getPrototypeOf(entity) as object) as TEntity,\n entity,\n ),\n );\n }\n // `undefined` only comes back for `null`/`undefined` input, and\n // `serializeEntity` always hands over an object.\n return deserializeSingleEntity(\n entityConstructor,\n serializeEntity(entityConstructor, entity),\n ) as Effect.Effect<TEntity, EntifixError>;\n};\n\nexport interface InMemoryEntityRepository extends EntityRepository {\n /** Everything currently stored, in insertion order. */\n readonly items: Entity[];\n /** Replaces the contents, discarding whatever was there. */\n seed(items: Entity[]): void;\n /**\n * Makes the next call to any method fail with `error`, so error branches are\n * reachable without reaching for a mocking library.\n */\n failNext(error: RepositoryFailure): void;\n}\n\n/**\n * In-memory {@link EntityRepository}: the default double for anything that\n * depends on persistence.\n *\n * Its semantics deliberately mirror `makeMongoRepository` — the same filtering\n * and sorting rules, which it takes from core's in-memory query evaluation\n * rather than keeping a copy of its own, same 1-based paging with a default page size of 10, same\n * \"entity not found\" failure, same id minting on create — and\n * `describeEntityRepositoryContract` holds both to that shared contract.\n */\nexport const makeInMemoryEntityRepository = (\n seed: Entity[] = [],\n): InMemoryEntityRepository => {\n let items = [...seed];\n let pendingFailure: RepositoryFailure | undefined;\n\n /** Consumes a queued failure, if one was armed. */\n const guard = <TValue>(\n run: () => Effect.Effect<TValue, RepositoryFailure>,\n ): Effect.Effect<TValue, RepositoryFailure> => {\n if (pendingFailure !== undefined) {\n const failure = pendingFailure;\n pendingFailure = undefined;\n return Effect.fail(failure);\n }\n return run();\n };\n\n const load = <TEntity extends Entity>(request: EntityLoadRequest<TEntity>) =>\n guard(() => {\n const matched = applySorting(\n applyFiltering(items as TEntity[], request.filtering),\n request.sorting,\n );\n const page = request.page ?? 1;\n const pageSize = request.pageSize ?? 10;\n const start = (page - 1) * pageSize;\n\n return Effect.forEach(\n matched.slice(start, start + pageSize),\n copyOf,\n ).pipe(\n Effect.map(\n copies =>\n ({\n items: copies,\n total: matched.length,\n request,\n }) satisfies EntityPage<TEntity>,\n ),\n );\n });\n\n const get = <TEntity extends Entity>(id: EntityId) =>\n guard(() => {\n const found = items.find(item => item.id === id);\n return found === undefined\n ? Effect.fail(new NotFound({}))\n : copyOf(found as TEntity);\n });\n\n const save = <TEntity extends Entity>(entity: TEntity) =>\n guard(() => {\n // A create arrives without an id, so the store mints one — same rule the\n // Mongo adapter follows. The Web Crypto global rather than `node:crypto`,\n // because a browser bundle cannot resolve a `node:` import and an example\n // with no backend runs this repository in the page.\n entity.id = entity.id ?? globalThis.crypto.randomUUID();\n // The store keeps its own copy and hands back another, so neither the\n // caller's instance nor the returned one can change the record without a\n // second save — which a real adapter guarantees by construction.\n return copyOf(entity).pipe(\n Effect.tap(stored =>\n Effect.sync(() => {\n const index = items.findIndex(item => item.id === stored.id);\n if (index === -1) {\n items.push(stored);\n } else {\n items[index] = stored;\n }\n }),\n ),\n Effect.flatMap(copyOf),\n );\n });\n\n const remove = <TEntity extends Entity>(entityOrId: EntityId | TEntity) =>\n guard(() => {\n const id =\n entityOrId != null && typeof entityOrId === 'object'\n ? entityOrId.id\n : entityOrId;\n items = items.filter(item => item.id !== id);\n return Effect.succeed(undefined);\n });\n\n return {\n load,\n get,\n save,\n delete: remove,\n get items() {\n return items;\n },\n seed: (next: Entity[]) => {\n items = [...next];\n },\n failNext: (error: RepositoryFailure) => {\n pendingFailure = error;\n },\n // Each method closes over its own state, so nothing is required from the\n // Effect environment; that is assignable to the interface's channel.\n } as unknown as InMemoryEntityRepository;\n};\n"],"names":["applyFiltering","applySorting","deserializeSingleEntity","extractMetaAccessors","NotFound","serializeEntity","Effect","copyOf","entity","entityConstructor","length","succeed","Object","assign","create","getPrototypeOf","makeInMemoryEntityRepository","seed","items","pendingFailure","guard","run","undefined","failure","fail","load","request","matched","filtering","sorting","page","pageSize","start","forEach","slice","pipe","map","copies","total","get","id","found","find","item","save","globalThis","crypto","randomUUID","tap","stored","sync","index","findIndex","push","flatMap","remove","entityOrId","filter","delete","next","failNext","error"],"mappings":"AACA,SACEA,cAAc,EACdC,YAAY,EACZC,uBAAuB,EAOvBC,oBAAoB,EACpBC,QAAQ,EACRC,eAAe,QACV,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAEhC;;;;;;;;;CASC,GACD,MAAMC,SAAS,CACbC;IAEA,MAAMC,oBAAoBD,OAAO,WAAW;IAC5C,IAAIL,qBAAqBM,mBAAmBC,MAAM,KAAK,GAAG;QACxD,OAAOJ,OAAOK,OAAO,CACnBC,OAAOC,MAAM,CACXD,OAAOE,MAAM,CAACF,OAAOG,cAAc,CAACP,UACpCA;IAGN;IACA,gEAAgE;IAChE,iDAAiD;IACjD,OAAON,wBACLO,mBACAJ,gBAAgBI,mBAAmBD;AAEvC;AAcA;;;;;;;;;CASC,GACD,OAAO,MAAMQ,+BAA+B,CAC1CC,OAAiB,EAAE;IAEnB,IAAIC,QAAQ;WAAID;KAAK;IACrB,IAAIE;IAEJ,iDAAiD,GACjD,MAAMC,QAAQ,CACZC;QAEA,IAAIF,mBAAmBG,WAAW;YAChC,MAAMC,UAAUJ;YAChBA,iBAAiBG;YACjB,OAAOhB,OAAOkB,IAAI,CAACD;QACrB;QACA,OAAOF;IACT;IAEA,MAAMI,OAAO,CAAyBC,UACpCN,MAAM;gBAKSM,eACI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GF;oBACjB;gBACF,KAEF3C,OAAOgD,OAAO,CAAC/C;QAEnB;IAEF,MAAMgD,SAAS,CAAyBC,aACtCpC,MAAM;YACJ,MAAMoB,KACJgB,cAAc,QAAQ,OAAOA,eAAe,WACxCA,WAAWhB,EAAE,GACbgB;YACNtC,QAAQA,MAAMuC,MAAM,CAACd,CAAAA,OAAQA,KAAKH,EAAE,KAAKA;YACzC,OAAOlC,OAAOK,OAAO,CAACW;QACxB;IAEF,OAAO;QACLG;QACAc;QACAK;QACAc,QAAQH;QACR,IAAIrC;YACF,OAAOA;QACT;QACAD,MAAM,CAAC0C;YACLzC,QAAQ;mBAAIyC;aAAK;QACnB;QACAC,UAAU,CAACC;YACT1C,iBAAiB0C;QACnB;IAGF;AACF,EAAE"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import type { FragmentCatalog, SlipStep } from '@entifix/business/flow';
|
|
2
|
-
import { type DomainEvent } from '@entifix/core';
|
|
2
|
+
import { type DomainEvent, type EntifixFailure } from '@entifix/core';
|
|
3
3
|
import { type FlowEngine, type FlowEventData } from '@entifix/transactions';
|
|
4
4
|
import { Effect } from 'effect';
|
|
5
5
|
/** What a fake participant does for one step: succeed with an outcome, or fail. */
|
|
6
|
-
export type FakeParticipant = (step: SlipStep) => Effect.Effect<unknown,
|
|
6
|
+
export type FakeParticipant = (step: SlipStep) => Effect.Effect<unknown, EntifixFailure>;
|
|
7
7
|
export interface FakeFlowEngine extends FlowEngine {
|
|
8
8
|
/** Every `flow.*` event the engine announced, in order. */
|
|
9
9
|
readonly events: readonly DomainEvent<FlowEventData>[];
|
|
@@ -1 +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,
|
|
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,EAAE,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;AACtE,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,cAAc,CAAC,CAAC;AAE5C,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,cAsIF,CAAC"}
|
|
@@ -1,15 +1,11 @@
|
|
|
1
1
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
2
|
import { slipSteps } from '@entifix/business/flow';
|
|
3
|
-
import { isFailure } from '@entifix/core';
|
|
4
3
|
import { flowEvent, FlowNotFound, FlowSignalRejected } from '@entifix/transactions';
|
|
5
4
|
import { Effect } from 'effect';
|
|
6
|
-
const failureOf = (error)=>
|
|
5
|
+
const failureOf = (error)=>({
|
|
7
6
|
code: error.code,
|
|
8
7
|
category: error.category
|
|
9
|
-
}
|
|
10
|
-
code: 'internal',
|
|
11
|
-
category: 'internal'
|
|
12
|
-
};
|
|
8
|
+
});
|
|
13
9
|
/**
|
|
14
10
|
* An in-memory {@link FlowEngine} with the semantics a durable one must have
|
|
15
11
|
* ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):
|
|
@@ -85,6 +81,22 @@ const failureOf = (error)=>isFailure(error) ? {
|
|
|
85
81
|
run.step = undefined;
|
|
86
82
|
announce(run, 'flow.completed', 'completed');
|
|
87
83
|
});
|
|
84
|
+
/** What a parked run's wait is correlated with, per its step's parameters. */ const correlationOf = (run)=>{
|
|
85
|
+
if (run.state !== 'waiting') return undefined;
|
|
86
|
+
// A waiting run is parked on the step at `next`.
|
|
87
|
+
const { parameters } = slipSteps(run.slip)[run.next];
|
|
88
|
+
const correlation = parameters == null ? void 0 : parameters['correlation'];
|
|
89
|
+
return typeof correlation === 'string' ? correlation : undefined;
|
|
90
|
+
};
|
|
91
|
+
const signal = (token)=>(run)=>{
|
|
92
|
+
if (run.state !== 'waiting' || run.step !== token) return Effect.fail(new FlowSignalRejected({
|
|
93
|
+
flowId: run.slip.flowId,
|
|
94
|
+
token
|
|
95
|
+
}));
|
|
96
|
+
run.state = 'running';
|
|
97
|
+
run.next += 1;
|
|
98
|
+
return walk(run);
|
|
99
|
+
};
|
|
88
100
|
const find = (flowId)=>{
|
|
89
101
|
const run = runs.get(flowId);
|
|
90
102
|
return run === undefined ? Effect.fail(new FlowNotFound({
|
|
@@ -119,15 +131,14 @@ const failureOf = (error)=>isFailure(error) ? {
|
|
|
119
131
|
}, run.step === undefined ? {} : {
|
|
120
132
|
step: run.step
|
|
121
133
|
})),
|
|
122
|
-
signal: (flowId, token)=>Effect.flatMap(find(flowId), (
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
}),
|
|
134
|
+
signal: (flowId, token)=>Effect.flatMap(find(flowId), signal(token)),
|
|
135
|
+
signalCorrelated: (correlation, token)=>{
|
|
136
|
+
var _ref;
|
|
137
|
+
var _find;
|
|
138
|
+
return Effect.flatMap(find((_ref = (_find = [
|
|
139
|
+
...runs.entries()
|
|
140
|
+
].find(([, run])=>correlationOf(run) === correlation)) == null ? void 0 : _find[0]) != null ? _ref : correlation), signal(token));
|
|
141
|
+
},
|
|
131
142
|
interrupt: (flowId)=>Effect.map(find(flowId), (run)=>{
|
|
132
143
|
if (run.state === 'running' || run.state === 'waiting') run.state = 'interrupted';
|
|
133
144
|
})
|
|
@@ -1 +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;QAAEC,UAAUF,MAAME,QAAQ;IAAC,IAC7C;QAAED,MAAM;QAAYC,UAAU;IAAW;AAE/C;;;;;;;CAOC,GACD,OAAO,MAAMC,qBAAqB,CAChCC,SACAC;IAEA,MAAMC,OAAO,IAAIC;IACjB,MAAMC,QAAQ,IAAID;IAClB,MAAME,SAAuC,EAAE;IAC/C,MAAMC,gBAA0B,EAAE;IAElC,MAAMC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C,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"}
|
|
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, type EntifixFailure } 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, EntifixFailure>;\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: EntifixFailure) => ({\n code: error.code,\n category: error.category,\n});\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 /** What a parked run's wait is correlated with, per its step's parameters. */\n const correlationOf = (run: Run) => {\n if (run.state !== 'waiting') return undefined;\n // A waiting run is parked on the step at `next`.\n const { parameters } = slipSteps(run.slip)[run.next] as SlipStep;\n const correlation = parameters?.['correlation'];\n return typeof correlation === 'string' ? correlation : undefined;\n };\n\n const signal = (token: string) => (run: Run) => {\n if (run.state !== 'waiting' || run.step !== token)\n return Effect.fail(\n new FlowSignalRejected({ flowId: run.slip.flowId, token }),\n );\n run.state = 'running';\n run.next += 1;\n return walk(run);\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) => Effect.flatMap(find(flowId), signal(token)),\n signalCorrelated: (correlation, token) =>\n Effect.flatMap(\n find(\n [...runs.entries()].find(\n ([, run]) => correlationOf(run) === correlation,\n )?.[0] ?? correlation,\n ),\n signal(token),\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","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","correlationOf","parameters","correlation","signal","token","fail","find","succeed","start","idempotencyKey","known","set","status","map","flatMap","signalCorrelated","entries","interrupt"],"mappings":";AACA,SAASA,SAAS,QAAQ,yBAAyB;AAEnD,SAEEC,SAAS,EAETC,YAAY,EACZC,kBAAkB,QAEb,wBAAwB;AAC/B,SAASC,MAAM,QAAQ,SAAS;AAuBhC,MAAMC,YAAY,CAACC,QAA2B,CAAA;QAC5CC,MAAMD,MAAMC,IAAI;QAChBC,UAAUF,MAAME,QAAQ;IAC1B,CAAA;AAEA;;;;;;;CAOC,GACD,OAAO,MAAMC,qBAAqB,CAChCC,SACAC;IAEA,MAAMC,OAAO,IAAIC;IACjB,MAAMC,QAAQ,IAAID;IAClB,MAAME,SAAuC,EAAE;IAC/C,MAAMC,gBAA0B,EAAE;IAElC,MAAMC,SAAS,CAACC;;YAAmBR;wBAAAA,eAAAA,QAAQS,GAAG,CAACD,KAAKE,GAAG,sBAApBV,aAAuBW,IAAI,mBAAI;;IAElE,MAAMC,WAAW,CACfC,KACAC,MACAN,MACAO,QAAgC,CAAC,CAAC;QAElCV,OAAOW,IAAI,CACTzB,UAAU;YACRuB,MAAMA;YACNG,QAAQ;YACRC,IAAI,IAAIC,KAAK,GAAGC,WAAW;YAC3BZ;YACAa,SAAShB,OAAOiB,MAAM;YACtBC,UAAU;gBAAC;oBAAEZ,MAAM;oBAAQa,IAAIX,IAAIY,IAAI,CAACC,MAAM;gBAAC;aAAE;YACjDC,MAAM;gBACJD,QAAQb,IAAIY,IAAI,CAACC,MAAM;gBACvBE,YAAYf,IAAIY,IAAI,CAACI,MAAM;gBAC3BC,aAAajB,I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kB,KAAKlB;gBACZ,OAAO;oBAAEa,QAAQD,KAAKC,MAAM;gBAAC;YAC/B;QACF+B,QAAQ/B,CAAAA,SACNhC,OAAOgE,GAAG,CAACP,KAAKzB,SAASb,CAAAA,MAAQ;oBAC/Ba;oBACAW,OAAOxB,IAAIwB,KAAK;mBACZxB,IAAIL,IAAI,KAAKoC,YAAY,CAAC,IAAI;oBAAEpC,MAAMK,IAAIL,IAAI;gBAAC;QAEvDwC,QAAQ,CAACtB,QAAQuB,QAAUvD,OAAOiE,OAAO,CAACR,KAAKzB,SAASsB,OAAOC;QAC/DW,kBAAkB,CAACb,aAAaE;;gBAG1B;mBAFJvD,OAAOiE,OAAO,CACZR,cACE,QAAA;mBAAIjD,KAAK2D,OAAO;aAAG,CAACV,IAAI,CACtB,CAAC,GAAGtC,IAAI,GAAKgC,cAAchC,SAASkC,iCADtC,KAEG,CAAC,EAAE,mBAAIA,cAEZC,OAAOC;;QAEXa,WAAWpC,CAAAA,SACThC,OAAOgE,GAAG,CAACP,KAAKzB,SAASb,CAAAA;gBACvB,IAAIA,IAAIwB,KAAK,KAAK,aAAaxB,IAAIwB,KAAK,KAAK,WAC3CxB,IAAIwB,KAAK,GAAG;YAChB;IACJ;AACF,EAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"link-resolver.d.ts","sourceRoot":"","sources":["../../src/doubles/link-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"link-resolver.d.ts","sourceRoot":"","sources":["../../src/doubles/link-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,MAAM,EACX,KAAK,iBAAiB,EACtB,KAAK,QAAQ,EACb,KAAK,kBAAkB,EAExB,MAAM,eAAe,CAAC;AAGvB,MAAM,WAAW,0BAA2B,SAAQ,kBAAkB;IACpE,yEAAyE;IACzE,QAAQ,CAAC,SAAS,EAAE,aAAa,CAAC;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,QAAQ,CAAA;KAAE,CAAC,CAAC;CACrE;AAED;;;;;;GAMG;AACH,eAAO,MAAM,8BAA8B,GACzC,SAAS,aAAa,CAAC,SAAS,CAAC,iBAAiB,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,KACrE,0BAwBF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { NotFound } from '@entifix/core';
|
|
2
2
|
import { Effect } from 'effect';
|
|
3
3
|
/**
|
|
4
4
|
* In-memory {@link EntityLinkResolver} over a per-constructor table of targets.
|
|
@@ -20,9 +20,8 @@ import { Effect } from 'effect';
|
|
|
20
20
|
id
|
|
21
21
|
});
|
|
22
22
|
const found = (_tables_get = tables.get(entityConstructor)) == null ? void 0 : _tables_get.find((item)=>item.id === id);
|
|
23
|
-
return found === undefined ? Effect.fail(new
|
|
24
|
-
entity: entityConstructor.name
|
|
25
|
-
id
|
|
23
|
+
return found === undefined ? Effect.fail(new NotFound({
|
|
24
|
+
entity: entityConstructor.name
|
|
26
25
|
})) : Effect.succeed(found);
|
|
27
26
|
}),
|
|
28
27
|
get requested () {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/doubles/link-resolver.ts"],"sourcesContent":["import {\n
|
|
1
|
+
{"version":3,"sources":["../../src/doubles/link-resolver.ts"],"sourcesContent":["import {\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLinkResolver,\n NotFound,\n} from '@entifix/core';\nimport { Effect } from 'effect';\n\nexport interface InMemoryEntityLinkResolver extends EntityLinkResolver {\n /** Every (constructor, id) pair the resolver was asked for, in order. */\n readonly requested: ReadonlyArray<{ entity: string; id: EntityId }>;\n}\n\n/**\n * In-memory {@link EntityLinkResolver} over a per-constructor table of targets.\n *\n * A use-case that follows links yields `EntityLinkResolverTag`, so this is the\n * double that lets link-following be tested without any adapter at all — and\n * `requested` shows whether an already-embedded link was needlessly refetched.\n */\nexport const makeInMemoryEntityLinkResolver = (\n entries: ReadonlyArray<readonly [EntityConstructor<Entity>, Entity[]]>,\n): InMemoryEntityLinkResolver => {\n const tables = new Map<unknown, Entity[]>(\n entries.map(([constructor, items]) => [constructor, items]),\n );\n const requested: Array<{ entity: string; id: EntityId }> = [];\n\n return {\n resolve: <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n id: EntityId,\n ) =>\n Effect.suspend(() => {\n requested.push({ entity: entityConstructor.name, id });\n const found = tables\n .get(entityConstructor)\n ?.find(item => item.id === id);\n return found === undefined\n ? Effect.fail(new NotFound({ entity: entityConstructor.name }))\n : Effect.succeed(found as TEntity);\n }),\n get requested() {\n return requested;\n },\n };\n};\n"],"names":["NotFound","Effect","makeInMemoryEntityLinkResolver","entries","tables","Map","map","constructor","items","requested","resolve","entityConstructor","id","suspend","push","entity","name","found","get","find","item","undefined","fail","succeed"],"mappings":"AAAA,SAKEA,QAAQ,QACH,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAOhC;;;;;;CAMC,GACD,OAAO,MAAMC,iCAAiC,CAC5CC;IAEA,MAAMC,SAAS,IAAIC,IACjBF,QAAQG,GAAG,CAAC,CAAC,CAACC,aAAaC,MAAM,GAAK;YAACD;YAAaC;SAAM;IAE5D,MAAMC,YAAqD,EAAE;IAE7D,OAAO;QACLC,SAAS,CACPC,mBACAC,KAEAX,OAAOY,OAAO,CAAC;oBAECT;gBADdK,UAAUK,IAAI,CAAC;oBAAEC,QAAQJ,kBAAkBK,IAAI;oBAAEJ;gBAAG;gBACpD,MAAMK,SAAQb,cAAAA,OACXc,GAAG,CAACP,uCADOP,YAEVe,IAAI,CAACC,CAAAA,OAAQA,KAAKR,EAAE,KAAKA;gBAC7B,OAAOK,UAAUI,YACbpB,OAAOqB,IAAI,CAAC,IAAItB,SAAS;oBAAEe,QAAQJ,kBAAkBK,IAAI;gBAAC,MAC1Df,OAAOsB,OAAO,CAACN;YACrB;QACF,IAAIR;YACF,OAAOA;QACT;IACF;AACF,EAAE"}
|
|
@@ -88,6 +88,8 @@ export interface FakeAmqpChannel {
|
|
|
88
88
|
deliverRaw(payload: string): Promise<void>;
|
|
89
89
|
/** Simulates the broker cancelling the consumer (amqplib delivers `null`). */
|
|
90
90
|
deliverCancellation(): Promise<void>;
|
|
91
|
+
/** Simulates the channel closing, as amqplib emits `close` on it. */
|
|
92
|
+
close(): void;
|
|
91
93
|
/** Makes every subsequent channel call throw/reject with `error`. */
|
|
92
94
|
failWith(error: unknown): void;
|
|
93
95
|
/** The object to pass where an amqplib `Channel` is expected. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fake-amqp.d.ts","sourceRoot":"","sources":["../../src/drivers/fake-amqp.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AAEH,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,qDAAqD;IACrD,UAAU,CAAC,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC;CACnD;AAED,MAAM,WAAW,eAAe;IAC9B,mDAAmD;IACnD,QAAQ,CAAC,SAAS,EAAE,aAAa,CAAC;QAChC,QAAQ,EAAE,MAAM,CAAC;QACjB,UAAU,EAAE,MAAM,CAAC;QACnB,IAAI,EAAE,OAAO,CAAC;QACd,4EAA4E;QAC5E,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAAC;KAC9C,CAAC,CAAC;IACH;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,EAAE,aAAa,CAAC;QAC/B,KAAK,EAAE,MAAM,CAAC;QACd,QAAQ,EAAE,MAAM,CAAC;QACjB,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC,CAAC;IACH;;;;;OAKG;IACH,QAAQ,CAAC,SAAS,EAAE,aAAa,CAAC;QAChC,QAAQ,EAAE,MAAM,CAAC;QACjB,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,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AC;KAClB,CAAC,CAAC;IACH,iEAAiE;IACjE,QAAQ,CAAC,aAAa,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3C;;;;;;;OAOG;IACH,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC;;;;OAIG;IACH,OAAO,CACL,IAAI,EAAE,OAAO,EACb,UAAU,CAAC,EAAE,MAAM,EACnB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAChC,OAAO,CAAC,IAAI,CAAC,CAAC;IACjB,yDAAyD;IACzD,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3C,8EAA8E;IAC9E,mBAAmB,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACrC,qEAAqE;IACrE,KAAK,IAAI,IAAI,CAAC;IACd,qEAAqE;IACrE,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IAC/B,iEAAiE;IACjE,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC3B;AAsBD,eAAO,MAAM,mBAAmB,QAAO,eAkMtC,CAAC"}
|
|
@@ -25,6 +25,7 @@ export const makeFakeAmqpChannel = ()=>{
|
|
|
25
25
|
const nacked = [];
|
|
26
26
|
let consumer;
|
|
27
27
|
const cancelled = [];
|
|
28
|
+
const closeListeners = [];
|
|
28
29
|
let consumerTags = 0;
|
|
29
30
|
let boundQueue;
|
|
30
31
|
let prefetchCount;
|
|
@@ -33,6 +34,10 @@ export const makeFakeAmqpChannel = ()=>{
|
|
|
33
34
|
if (failure !== undefined) throw failure;
|
|
34
35
|
};
|
|
35
36
|
const channel = {
|
|
37
|
+
once: (event, listener)=>{
|
|
38
|
+
if (event === 'close') closeListeners.push(listener);
|
|
39
|
+
return channel;
|
|
40
|
+
},
|
|
36
41
|
publish: (exchange, routingKey, content, options)=>{
|
|
37
42
|
guard();
|
|
38
43
|
published.push({
|
|
@@ -164,6 +169,9 @@ export const makeFakeAmqpChannel = ()=>{
|
|
|
164
169
|
},
|
|
165
170
|
deliver: (body, routingKey, headers)=>push(JSON.stringify(body), routingKey != null ? routingKey : routingKeyOf(body), headers),
|
|
166
171
|
deliverRaw: (payload)=>push(payload, undefined),
|
|
172
|
+
close: ()=>{
|
|
173
|
+
for (const listener of closeListeners.splice(0))listener();
|
|
174
|
+
},
|
|
167
175
|
deliverCancellation: async ()=>{
|
|
168
176
|
if (consumer === undefined) {
|
|
169
177
|
throw new Error('fake amqp: nothing subscribed yet');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/drivers/fake-amqp.ts"],"sourcesContent":["import { matchesEventPattern } from '@entifix/core';\n\n/**\n * A fake of the amqplib channel, not of the {@link EventBus} port.\n *\n * `makeAmqpEventBus` runs on top of it, so the envelope framing, the\n * `prefetch(1)` the saga tracker depends on, and the ack/nack policy are\n * all exercised for real.\n */\n\nexport interface FakeAmqpMessage {\n content: Buffer;\n /** Present only for a delivery made with headers. */\n properties?: { headers: Record<string, unknown> };\n}\n\nexport interface FakeAmqpChannel {\n /** Everything published, decoded from the wire. */\n readonly published: ReadonlyArray<{\n exchange: string;\n routingKey: string;\n body: unknown;\n /** The headers it was published with — a quarantine's reason rides here. */\n headers: Record<string, unknown> | undefined;\n }>;\n /**\n * Every queue binding the adapter asked for. Recorded because the exchange is\n * a topic now: the pattern a subscriber binds is the whole of its routing, so\n * a fake that swallowed it would let a wrong binding pass every test.\n */\n readonly bindings: ReadonlyArray<{\n queue: string;\n exchange: string;\n pattern: string;\n }>;\n /**\n * Every exchange the adapter declared, with its type. Recorded because the\n * dead-letter exchange is `direct` while the event exchange is `topic`, and a\n * broker will not retype an existing exchange — declaring the wrong type is a\n * failure that only appears against a real broker.\n */\n readonly exchanges: ReadonlyArray<{\n exchange: string;\n type: string;\n options: Record<string, unknown> | undefined;\n }>;\n /**\n * Every queue the adapter declared, with the arguments it declared it with.\n * The arguments *are* the delivery policy — `x-queue-type`,\n * `x-delivery-limit`, `x-dead-letter-exchange` — so a fake that swallowed\n * them would let a queue with no retry ceiling and no dead-letter path pass\n * every test, which is the exact defect a quarantine path exists to close.\n */\n readonly queues: ReadonlyArray<{\n queue: string;\n options: Record<string, unknown> | undefined;\n }>;\n /** Messages acked, so the success policy can be asserted. */\n readonly acked: FakeAmqpMessage[];\n /**\n * Messages nacked, **with their flags**. `requeue` is the whole distinction\n * between a transient failure the broker should retry and a poison message it\n * should quarantine at once, so recording only that a nack happened is how\n * \"dead-letters a failed message\" stayed a passing test for a bus that\n * discarded it.\n */\n readonly nacked: ReadonlyArray<{\n message: FakeAmqpMessage;\n allUpTo: boolean;\n requeue: boolean;\n }>;\n /** The prefetch the adapter asked for — 1, or the fold races. */\n readonly prefetchCount: number | undefined;\n /**\n * The consumer tags cancelled, in order.\n *\n * Recorded rather than merely accepted because a graceful shutdown's first\n * phase *is* the cancel: a connector that dropped the tag on the\n * floor would pass every test while leaving the broker delivering into a\n * process that is closing its connection.\n */\n readonly cancelled: readonly string[];\n /**\n * Pushes a message to the consumers whose binding matches it, as the broker\n * would. The routing key defaults to the envelope's own `meta.event.name`,\n * which is what the adapter publishes with.\n */\n deliver(\n body: unknown,\n routingKey?: string,\n headers?: Record<string, unknown>,\n ): Promise<void>;\n /** Pushes a raw payload, for malformed-message paths. */\n deliverRaw(payload: string): Promise<void>;\n /** Simulates the broker cancelling the consumer (amqplib delivers `null`). */\n deliverCancellation(): Promise<void>;\n /** Makes every subsequent channel call throw/reject with `error`. */\n failWith(error: unknown): void;\n /** The object to pass where an amqplib `Channel` is expected. */\n readonly channel: unknown;\n}\n\n/** The routing key a body would have been published with. */\nconst routingKeyOf = (body: unknown): string => {\n const event = (body as { meta?: { event?: { name?: unknown } } })?.meta\n ?.event;\n return typeof event?.name === 'string' ? event.name : '';\n};\n\n/**\n * The body as JSON, or as the text it is when it is not — a poison message\n * republished to quarantine is exactly the bytes that did not parse.\n */\nconst decode = (content: Buffer): unknown => {\n const text = content.toString();\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return text;\n }\n};\n\nexport const makeFakeAmqpChannel = (): FakeAmqpChannel => {\n const published: Array<{\n exchange: string;\n routingKey: string;\n body: unknown;\n headers: Record<string, unknown> | undefined;\n }> = [];\n const bindings: Array<{ queue: string; exchange: string; pattern: string }> =\n [];\n const exchanges: Array<{\n exchange: string;\n type: string;\n options: Record<string, unknown> | undefined;\n }> = [];\n const queues: Array<{\n queue: string;\n options: Record<string, unknown> | undefined;\n }> = [];\n const acked: FakeAmqpMessage[] = [];\n const nacked: Array<{\n message: FakeAmqpMessage;\n allUpTo: boolean;\n requeue: boolean;\n }> = [];\n let consumer: ((message: FakeAmqpMessage | null) => void) | undefined;\n const cancelled: string[] = [];\n let consumerTags = 0;\n let boundQueue: string | undefined;\n let prefetchCount: number | undefined;\n let failure: unknown;\n\n const guard = () => {\n if (failure !== undefined) throw failure;\n };\n\n const channel = {\n publish: (\n exchange: string,\n routingKey: string,\n content: Buffer,\n options?: { headers?: Record<string, unknown> },\n ) => {\n guard();\n published.push({\n exchange,\n routingKey,\n body: decode(content),\n headers: options?.headers,\n });\n return true;\n },\n prefetch: async (count: number) => {\n guard();\n prefetchCount = count;\n },\n assertExchange: async (\n exchange: string,\n type: string,\n options?: Record<string, unknown>,\n ) => {\n guard();\n exchanges.push({ exchange, type, options });\n return { exchange };\n },\n assertQueue: async (queue: string, options?: Record<string, unknown>) => {\n guard();\n const name = queue === '' ? 'amq.gen-fake' : queue;\n queues.push({ queue: name, options });\n return { queue: name };\n },\n bindQueue: async (queue: string, exchange: string, pattern: string) => {\n guard();\n bindings.push({ queue, exchange, pattern });\n },\n consume: async (\n queue: string,\n handler: (message: FakeAmqpMessage | null) => void,\n ) => {\n guard();\n consumer = handler;\n boundQueue = queue;\n // A fresh tag per `consume`, so a reconnect's re-bind is distinguishable\n // from the binding it replaced — the connector cancels what it currently\n // holds, and a constant tag would hide it cancelling a stale one.\n consumerTags += 1;\n return { consumerTag: `fake-consumer-${consumerTags}` };\n },\n cancel: async (consumerTag: string) => {\n guard();\n cancelled.push(consumerTag);\n consumer = undefined;\n },\n ack: (message: FakeAmqpMessage) => {\n acked.push(message);\n },\n nack: (message: FakeAmqpMessage, allUpTo: boolean, requeue: boolean) => {\n nacked.push({ message, allUpTo, requeue });\n },\n close: async () => {\n guard();\n },\n };\n\n /**\n * The adapter acks/nacks from inside a floating promise chain, so a delivery\n * is only settled once the microtask queue drains.\n */\n const settle = () => new Promise<void>(resolve => setTimeout(resolve, 0));\n\n /**\n * Whether the consumer's queue is bound to a pattern matching `routingKey`.\n * The broker decides this in production, so the fake has to as well — without\n * it every subscriber sees every message and the topic exchange is untested.\n */\n const routes = (routingKey: string) =>\n bindings.some(\n binding =>\n binding.queue === boundQueue &&\n matchesEventPattern(binding.pattern, routingKey),\n );\n\n /**\n * `routingKey === undefined` means \"the broker already routed this\" — used by\n * the malformed-payload path, where the message reached the queue and it is\n * the *content* that is wrong.\n */\n const push = async (\n payload: string,\n routingKey: string | undefined,\n headers?: Record<string, unknown>,\n ) => {\n if (consumer === undefined) {\n throw new Error('fake amqp: nothing subscribed yet');\n }\n if (routingKey !== undefined && !routes(routingKey)) {\n return;\n }\n consumer({\n content: Buffer.from(payload),\n // Only when asked for, so a delivery without headers stays exactly the\n // shape amqplib hands over for a message published with none.\n ...(headers === undefined ? {} : { properties: { headers } }),\n });\n await settle();\n };\n\n return {\n get published() {\n return published;\n },\n get bindings() {\n return bindings;\n },\n get exchanges() {\n return exchanges;\n },\n get queues() {\n return queues;\n },\n get acked() {\n return acked;\n },\n get nacked() {\n return nacked;\n },\n get prefetchCount() {\n return prefetchCount;\n },\n get cancelled() {\n return cancelled;\n },\n deliver: (body, routingKey, headers) =>\n push(JSON.stringify(body), routingKey ?? routingKeyOf(body), headers),\n deliverRaw: payload => push(payload, undefined),\n deliverCancellation: async () => {\n if (consumer === undefined) {\n throw new Error('fake amqp: nothing subscribed yet');\n }\n consumer(null);\n await settle();\n },\n failWith: error => {\n failure = error;\n },\n channel,\n };\n};\n"],"names":["matchesEventPattern","routingKeyOf","body","event","meta","name","decode","content","text","toString","JSON","parse","makeFakeAmqpChannel","published","bindings","exchanges","queues","acked","nacked","consumer","cancelled","consumerTags","boundQueue","prefetchCount","failure","guard","undefined","channel","publish","exchange","routingKey","options","push","headers","prefetch","count","assertExchange","type","assertQueue","queue","bindQueue","pattern","consume","handler","consumerTag","cancel","ack","message","nack","allUpTo","requeue","close","settle","Promise","resolve","setTimeout","routes","some","binding","payload","Error","Buffer","from","properties","deliver","stringify","deliverRaw","deliverCancellation","failWith","error"],"mappings":";AAAA,SAASA,mBAAmB,QAAQ,gBAAgB;AAsGpD,2DAA2D,GAC3D,MAAMC,eAAe,CAACC;QACN;IAAd,MAAMC,QAASD,yBAAD,aAAA,AAACA,KAAoDE,IAAI,qBAAzD,WACVD,KAAK;IACT,OAAO,QAAOA,yBAAAA,MAAOE,IAAI,MAAK,WAAWF,MAAME,IAAI,GAAG;AACxD;AAEA;;;CAGC,GACD,MAAMC,SAAS,CAACC;IACd,MAAMC,OAAOD,QAAQE,QAAQ;IAC7B,IAAI;QACF,OAAOC,KAAKC,KAAK,CAACH;IACpB,EAAE,eAAM;QACN,OAAOA;IACT;AACF;AAEA,OAAO,MAAMI,sBAAsB;IACjC,MAAMC,YAKD,EAAE;IACP,MAAMC,WACJ,EAAE;IACJ,MAAMC,YAID,EAAE;IACP,MAAMC,SAGD,EAAE;IACP,MAAMC,QAA2B,EAAE;IACnC,MAAMC,SAID,EAAE;IACP,IAAIC;IACJ,MAAMC,YAAsB,EAAE;IAC9B,IAAIC,eAAe;IACnB,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IAEJ,MAAMC,QAAQ;QACZ,IAAID,YAAYE,WAAW,MAAMF;IACnC;IAEA,MAAMG,UAAU;QACdC,SAAS,CACPC,UACAC,YACAvB,SACAwB;YAEAN;YACAZ,UAAUmB,IAAI,CAAC;gBACbH;gBACAC;gBACA5B,MAAMI,O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D,MAAME,OAAO,OACX2B,SACA7B,YACAG;QAEA,IAAId,aAAaO,WAAW;YAC1B,MAAM,IAAIkC,MAAM;QAClB;QACA,IAAI9B,eAAeJ,aAAa,CAAC8B,OAAO1B,aAAa;YACnD;QACF;QACAX,SAAS;YACPZ,SAASsD,OAAOC,IAAI,CAACH;WAGjB1B,YAAYP,YAAY,CAAC,IAAI;YAAEqC,YAAY;gBAAE9B;YAAQ;QAAE;QAE7D,MAAMmB;IACR;IAEA,OAAO;QACL,IAAIvC;YACF,OAAOA;QACT;QACA,IAAIC;YACF,OAAOA;QACT;QACA,IAAIC;YACF,OAAOA;QACT;QACA,IAAIC;YACF,OAAOA;QACT;QACA,IAAIC;YACF,OAAOA;QACT;QACA,IAAIC;YACF,OAAOA;QACT;QACA,IAAIK;YACF,OAAOA;QACT;QACA,IAAIH;YACF,OAAOA;QACT;QACA4C,SAAS,CAAC9D,MAAM4B,YAAYG,UAC1BD,KAAKtB,KAAKuD,SAAS,CAAC/D,OAAO4B,qBAAAA,aAAc7B,aAAaC,OAAO+B;QAC/DiC,YAAYP,CAAAA,UAAW3B,KAAK2B,SAASjC;QACrCyC,qBAAqB;YACnB,IAAIhD,aAAaO,WAAW;gBAC1B,MAAM,IAAIkC,MAAM;YAClB;YACAzC,SAAS;YACT,MAAMiC;QACR;QACAgB,UAAUC,CAAAA;YACR7C,UAAU6C;QACZ;QACA1C;IACF;AACF,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../src/drivers/fake-amqp.ts"],"sourcesContent":["import { matchesEventPattern } from '@entifix/core';\n\n/**\n * A fake of the amqplib channel, not of the {@link EventBus} port.\n *\n * `makeAmqpEventBus` runs on top of it, so the envelope framing, the\n * `prefetch(1)` the saga tracker depends on, and the ack/nack policy are\n * all exercised for real.\n */\n\nexport interface FakeAmqpMessage {\n content: Buffer;\n /** Present only for a delivery made with headers. */\n properties?: { headers: Record<string, unknown> };\n}\n\nexport interface FakeAmqpChannel {\n /** Everything published, decoded from the wire. */\n readonly published: ReadonlyArray<{\n exchange: string;\n routingKey: string;\n body: unknown;\n /** The headers it was published with — a quarantine's reason rides here. */\n headers: Record<string, unknown> | undefined;\n }>;\n /**\n * Every queue binding the adapter asked for. Recorded because the exchange is\n * a topic now: the pattern a subscriber binds is the whole of its routing, so\n * a fake that swallowed it would let a wrong binding pass every test.\n */\n readonly bindings: ReadonlyArray<{\n queue: string;\n exchange: string;\n pattern: string;\n }>;\n /**\n * Every exchange the adapter declared, with its type. Recorded because the\n * dead-letter exchange is `direct` while the event exchange is `topic`, and a\n * broker will not retype an existing exchange — declaring the wrong type is a\n * failure that only appears against a real broker.\n */\n readonly exchanges: ReadonlyArray<{\n exchange: string;\n type: string;\n options: Record<string, unknown> | undefined;\n }>;\n /**\n * Every queue the adapter declared, with the arguments it declared it with.\n * The arguments *are* the delivery policy — `x-queue-type`,\n * `x-delivery-limit`, `x-dead-letter-exchange` — so a fake that swallowed\n * them would let a queue with no retry ceiling and no dead-letter path pass\n * every test, which is the exact defect a quarantine path exists to close.\n */\n readonly queues: ReadonlyArray<{\n queue: string;\n options: Record<string, unknown> | undefined;\n }>;\n /** Messages acked, so the success policy can be asserted. */\n readonly acked: FakeAmqpMessage[];\n /**\n * Messages nacked, **with their flags**. `requeue` is the whole distinction\n * between a transient failure the broker should retry and a poison message it\n * should quarantine at once, so recording only that a nack happened is how\n * \"dead-letters a failed message\" stayed a passing test for a bus that\n * discarded it.\n */\n readonly nacked: ReadonlyArray<{\n message: FakeAmqpMessage;\n allUpTo: boolean;\n requeue: boolean;\n }>;\n /** The prefetch the adapter asked for — 1, or the fold races. */\n readonly prefetchCount: number | undefined;\n /**\n * The consumer tags cancelled, in order.\n *\n * Recorded rather than merely accepted because a graceful shutdown's first\n * phase *is* the cancel: a connector that dropped the tag on the\n * floor would pass every test while leaving the broker delivering into a\n * process that is closing its connection.\n */\n readonly cancelled: readonly string[];\n /**\n * Pushes a message to the consumers whose binding matches it, as the broker\n * would. The routing key defaults to the envelope's own `meta.event.name`,\n * which is what the adapter publishes with.\n */\n deliver(\n body: unknown,\n routingKey?: string,\n headers?: Record<string, unknown>,\n ): Promise<void>;\n /** Pushes a raw payload, for malformed-message paths. */\n deliverRaw(payload: string): Promise<void>;\n /** Simulates the broker cancelling the consumer (amqplib delivers `null`). */\n deliverCancellation(): Promise<void>;\n /** Simulates the channel closing, as amqplib emits `close` on it. */\n close(): void;\n /** Makes every subsequent channel call throw/reject with `error`. */\n failWith(error: unknown): void;\n /** The object to pass where an amqplib `Channel` is expected. */\n readonly channel: unknown;\n}\n\n/** The routing key a body would have been published with. */\nconst routingKeyOf = (body: unknown): string => {\n const event = (body as { meta?: { event?: { name?: unknown } } })?.meta\n ?.event;\n return typeof event?.name === 'string' ? event.name : '';\n};\n\n/**\n * The body as JSON, or as the text it is when it is not — a poison message\n * republished to quarantine is exactly the bytes that did not parse.\n */\nconst decode = (content: Buffer): unknown => {\n const text = content.toString();\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return text;\n }\n};\n\nexport const makeFakeAmqpChannel = (): FakeAmqpChannel => {\n const published: Array<{\n exchange: string;\n routingKey: string;\n body: unknown;\n headers: Record<string, unknown> | undefined;\n }> = [];\n const bindings: Array<{ queue: string; exchange: string; pattern: string }> =\n [];\n const exchanges: Array<{\n exchange: string;\n type: string;\n options: Record<string, unknown> | undefined;\n }> = [];\n const queues: Array<{\n queue: string;\n options: Record<string, unknown> | undefined;\n }> = [];\n const acked: FakeAmqpMessage[] = [];\n const nacked: Array<{\n message: FakeAmqpMessage;\n allUpTo: boolean;\n requeue: boolean;\n }> = [];\n let consumer: ((message: FakeAmqpMessage | null) => void) | undefined;\n const cancelled: string[] = [];\n const closeListeners: Array<() => void> = [];\n let consumerTags = 0;\n let boundQueue: string | undefined;\n let prefetchCount: number | undefined;\n let failure: unknown;\n\n const guard = () => {\n if (failure !== undefined) throw failure;\n };\n\n const channel = {\n once: (event: string, listener: () => void) => {\n if (event === 'close') closeListeners.push(listener);\n return channel;\n },\n publish: (\n exchange: string,\n routingKey: string,\n content: Buffer,\n options?: { headers?: Record<string, unknown> },\n ) => {\n guard();\n published.push({\n exchange,\n routingKey,\n body: decode(content),\n headers: options?.headers,\n });\n return true;\n },\n prefetch: async (count: number) => {\n guard();\n prefetchCount = count;\n },\n assertExchange: async (\n exchange: string,\n type: string,\n options?: Record<string, unknown>,\n ) => {\n guard();\n exchanges.push({ exchange, type, options });\n return { exchange };\n },\n assertQueue: async (queue: string, options?: Record<string, unknown>) => {\n guard();\n const name = queue === '' ? 'amq.gen-fake' : queue;\n queues.push({ queue: name, options });\n return { queue: name };\n },\n bindQueue: async (queue: string, exchange: string, pattern: string) => {\n guard();\n bindings.push({ queue, exchange, pattern });\n },\n consume: async (\n queue: string,\n handler: (message: FakeAmqpMessage | null) => void,\n ) => {\n guard();\n consumer = handler;\n boundQueue = queue;\n // A fresh tag per `consume`, so a reconnect's re-bind is distinguishable\n // from the binding it replaced — the connector cancels what it currently\n // holds, and a constant tag would hide it cancelling a stale one.\n consumerTags += 1;\n return { consumerTag: `fake-consumer-${consumerTags}` };\n },\n cancel: async (consumerTag: string) => {\n guard();\n cancelled.push(consumerTag);\n consumer = undefined;\n },\n ack: (message: FakeAmqpMessage) => {\n acked.push(message);\n },\n nack: (message: FakeAmqpMessage, allUpTo: boolean, requeue: boolean) => {\n nacked.push({ message, allUpTo, requeue });\n },\n close: async () => {\n guard();\n },\n };\n\n /**\n * The adapter acks/nacks from inside a floating promise chain, so a delivery\n * is only settled once the microtask queue drains.\n */\n const settle = () => new Promise<void>(resolve => setTimeout(resolve, 0));\n\n /**\n * Whether the consumer's queue is bound to a pattern matching `routingKey`.\n * The broker decides this in production, so the fake has to as well — without\n * it every subscriber sees every message and the topic exchange is untested.\n */\n const routes = (routingKey: string) =>\n bindings.some(\n binding =>\n binding.queue === boundQueue &&\n matchesEventPattern(binding.pattern, routingKey),\n );\n\n /**\n * `routingKey === undefined` means \"the broker already routed this\" — used by\n * the malformed-payload path, where the message reached the queue and it is\n * the *content* that is wrong.\n */\n const push = async (\n payload: string,\n routingKey: string | undefined,\n headers?: Record<string, unknown>,\n ) => {\n if (consumer === undefined) {\n throw new Error('fake amqp: nothing subscribed yet');\n }\n if (routingKey !== undefined && !routes(routingKey)) {\n return;\n }\n consumer({\n content: Buffer.from(payload),\n // Only when asked for, so a delivery without headers stays exactly the\n // shape amqplib hands over for a message published with none.\n ...(headers === undefined ? {} : { properties: { headers } }),\n });\n await settle();\n };\n\n return {\n get published() {\n return published;\n },\n get bindings() {\n return bindings;\n },\n get exchanges() {\n return exchanges;\n },\n get queues() {\n return queues;\n },\n get acked() {\n return acked;\n },\n get nacked() {\n return nacked;\n },\n get prefetchCount() {\n return prefetchCount;\n },\n get cancelled() {\n return cancelled;\n },\n deliver: (body, routingKey, headers) =>\n push(JSON.stringify(body), routingKey ?? routingKeyOf(body), headers),\n deliverRaw: payload => push(payload, undefined),\n close: () => {\n for (const listener of closeListeners.splice(0)) listener();\n },\n deliverCancellation: async () => {\n if (consumer === undefined) {\n throw new Error('fake amqp: nothing subscribed yet');\n }\n consumer(null);\n await settle();\n },\n failWith: error => {\n failure = error;\n },\n channel,\n };\n};\n"],"names":["matchesEventPattern","routingKeyOf","body","event","meta","name","decode","content","text","toString","JSON","parse","makeFakeAmqpChannel","published","bindings","exchanges","queues","acked","nacked","consumer","cancelled","closeListeners","consumerTags","boundQueue","prefetchCount","failure","guard","undefined","channel","once","listener","push","publish","exchange","routingKey","options","headers","prefetch","count","assertExchange","type","assertQueue","queue","bindQueue","pattern","consume","handler","consumerTag","cancel","ack","message","nack","allUpTo","requeue","close","settle","Promise","resolve","setTimeout","routes","some","binding","payload","Error","Buffer","from","properties","deliver","stringify","deliverRaw","splice","deliverCancellation","failWith","error"],"mappings":";AAAA,SAASA,mBAAmB,QAAQ,gBAAgB;AAwGpD,2DAA2D,GAC3D,MAAMC,eAAe,CAACC;QACN;IAAd,MAAMC,QAASD,yBAAD,aAAA,AAACA,KAAoDE,IAAI,qBAAzD,W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AAyE;IACzE,QAAQ,CAAC,UAAU,EAAE,aAAa,CAAC,gBAAgB,CAAC,CAAC;IACrD,4CAA4C;IAC5C,QAAQ,CAAC,aAAa,EAAE,gBAAgB,GAAG,SAAS,CAAC;IACrD;;;;;;OAMG;IACH,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAC1B;AAuBD,gEAAgE;AAChE,eAAO,MAAM,iBAAiB,GAC5B,OAAM,aAAa,CAAC,eAAe,CAAM,KACxC,aA2FF,CAAC"}
|
package/dist/drivers/fake-sql.js
CHANGED
|
@@ -97,7 +97,22 @@ const unsupported = (name)=>{
|
|
|
97
97
|
get lastExecution () {
|
|
98
98
|
return executions[executions.length - 1];
|
|
99
99
|
},
|
|
100
|
-
client: Statement.make(Effect.succeed(connection), pgCompiler, [], undefined)
|
|
100
|
+
client: Object.assign(Statement.make(Effect.succeed(connection), pgCompiler, [], undefined), {
|
|
101
|
+
/**
|
|
102
|
+
* Runs `self` between a recorded `BEGIN` and `COMMIT`, or `ROLLBACK`
|
|
103
|
+
* when it fails — enough for a spec to assert what a unit of work
|
|
104
|
+
* committed and what it rolled back, though nothing is isolated.
|
|
105
|
+
*/ withTransaction: (self)=>Effect.sync(()=>executions.push({
|
|
106
|
+
sql: 'BEGIN',
|
|
107
|
+
params: []
|
|
108
|
+
})).pipe(Effect.andThen(self), Effect.tapError(()=>Effect.sync(()=>executions.push({
|
|
109
|
+
sql: 'ROLLBACK',
|
|
110
|
+
params: []
|
|
111
|
+
}))), Effect.tap(()=>Effect.sync(()=>executions.push({
|
|
112
|
+
sql: 'COMMIT',
|
|
113
|
+
params: []
|
|
114
|
+
}))))
|
|
115
|
+
})
|
|
101
116
|
};
|
|
102
117
|
};
|
|
103
118
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/drivers/fake-sql.ts"],"sourcesContent":["/**\n * A fake of the `@effect/sql` driver, not of the repository port.\n *\n * It sits one level *below* `makeSqlRepository`, so the adapter's own code — the\n * filter translation, the clause assembly, the upsert rule, the error mapping —\n * actually runs and is measured by coverage. A fake at the port level would skip\n * all of it. Same reasoning as {@link makeFakeMongoDb}.\n *\n * What it does **not** do is execute SQL: it hands back canned rows and records\n * the statement each call compiled to, so a spec asserts on the SQL and\n * parameters the adapter produced. Running the shared\n * `describeEntityRepositoryContract` needs a real engine and belongs against real\n * Postgres, the way the driver connection Layers are covered.\n */\n\nimport { Effect } from 'effect';\nimport { SqlError } from 'effect/sql';\nimport { Statement } from 'effect/sql';\n\n/** One statement the adapter executed, already compiled. */\nexport interface FakeSqlExecution {\n /** The compiled SQL text, parameters replaced by `$1`, `$2`, … */\n readonly sql: string;\n readonly params: ReadonlyArray<unknown>;\n}\n\n/** Rows to answer with when a statement's SQL contains `match`. */\nexport interface FakeSqlResponse {\n readonly match: string;\n readonly rows: ReadonlyArray<Record<string, unknown>>;\n}\n\nexport interface FakeSqlClient {\n /**\n * Answers `rows` for any statement whose compiled SQL contains `match`. Later\n * registrations win, so a spec can override a default set up by a helper.\n */\n respondTo(match: string, rows: ReadonlyArray<Record<string, unknown>>): void;\n /**\n * Makes every subsequent execution fail, so the adapter's `EntifixConnError`\n * mapping is reachable.\n */\n failWith(message: string): void;\n /**\n * Makes only the statements containing `match` fail, leaving the rest working\n * — the way a select that succeeds and a count that then fails reaches a\n * distinct error branch.\n */\n failOn(match: string, message: string): void;\n /** Every statement executed, in order, for assertions about what ran. */\n readonly executions: ReadonlyArray<FakeSqlExecution>;\n /** The most recently executed statement. */\n readonly lastExecution: FakeSqlExecution | undefined;\n /**\n * The object to hand to `makeSqlRepository` in place of a real `SqlClient`.\n *\n * Typed `unknown` on purpose — casting at the call site keeps this fake honest\n * that it implements only the constructor surface the adapters use, not the\n * whole `SqlClient` (no transactions, no reactivity, no streaming).\n */\n readonly client: unknown;\n}\n\nconst unsupported = (name: string): never => {\n throw new TypeError(`fake sql: ${name} is not implemented`);\n};\n\n/**\n * The Postgres compiler's configuration, mirrored from `@effect/sql-pg` so the\n * fake emits exactly the dialect production does — `$n` placeholders and\n * double-quoted identifiers — without this package depending on the `pg` driver.\n *\n * `sql.updateValues` and the `PgJson` custom segment are deliberate `TypeError`s\n * rather than approximations: no adapter uses either, and a compiler that\n * half-emitted them would let a spec pass on SQL that real Postgres rejects.\n */\nconst pgCompiler = Statement.makeCompiler({\n dialect: 'pg',\n placeholder: index => `$${index}`,\n onIdentifier: Statement.defaultEscape('\"'),\n onRecordUpdate: () => unsupported('updateValues'),\n onCustom: () => unsupported('custom segments'),\n});\n\n/** Builds an in-memory stand-in for an `@effect/sql` client. */\nexport const makeFakeSqlClient = (\n seed: ReadonlyArray<FakeSqlResponse> = [],\n): FakeSqlClient => {\n const responses: FakeSqlResponse[] = [...seed];\n const executions: FakeSqlExecution[] = [];\n const failuresByMatch: Array<{ match: string; message: string }> = [];\n let failure: string | undefined;\n\n const answer = (sql: string) => {\n // Last registration wins, so an override does not have to remove the\n // default it replaces.\n for (let index = responses.length - 1; index >= 0; index -= 1) {\n const response = responses[index];\n if (response !== undefined && sql.includes(response.match)) {\n return response.rows;\n }\n }\n return [];\n };\n\n const execute = (sql: string, params: ReadonlyArray<unknown>) => {\n executions.push({ sql, params });\n\n const scoped = failuresByMatch.find(entry => sql.includes(entry.match));\n const message = scoped?.message ?? failure;\n if (message !== undefined) {\n return Effect.fail(\n new SqlError.SqlError({\n reason: new SqlError.UnknownError({\n cause: new Error(message),\n message,\n }),\n }),\n );\n }\n return Effect.succeed(answer(sql));\n };\n\n const connection = {\n execute: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeUnprepared: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeRaw: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeValues: () => unsupported('executeValues'),\n executeStream: () => unsupported('executeStream'),\n };\n\n return {\n respondTo: (match, rows) => {\n responses.push({ match, rows });\n },\n failWith: message => {\n failure = message;\n },\n failOn: (match, message) => {\n failuresByMatch.push({ match, message });\n },\n get executions() {\n return executions;\n },\n get lastExecution() {\n return executions[executions.length - 1];\n },\n client: Statement.make(\n
|
|
1
|
+
{"version":3,"sources":["../../src/drivers/fake-sql.ts"],"sourcesContent":["/**\n * A fake of the `@effect/sql` driver, not of the repository port.\n *\n * It sits one level *below* `makeSqlRepository`, so the adapter's own code — the\n * filter translation, the clause assembly, the upsert rule, the error mapping —\n * actually runs and is measured by coverage. A fake at the port level would skip\n * all of it. Same reasoning as {@link makeFakeMongoDb}.\n *\n * What it does **not** do is execute SQL: it hands back canned rows and records\n * the statement each call compiled to, so a spec asserts on the SQL and\n * parameters the adapter produced. Running the shared\n * `describeEntityRepositoryContract` needs a real engine and belongs against real\n * Postgres, the way the driver connection Layers are covered.\n */\n\nimport { Effect } from 'effect';\nimport { SqlError } from 'effect/sql';\nimport { Statement } from 'effect/sql';\n\n/** One statement the adapter executed, already compiled. */\nexport interface FakeSqlExecution {\n /** The compiled SQL text, parameters replaced by `$1`, `$2`, … */\n readonly sql: string;\n readonly params: ReadonlyArray<unknown>;\n}\n\n/** Rows to answer with when a statement's SQL contains `match`. */\nexport interface FakeSqlResponse {\n readonly match: string;\n readonly rows: ReadonlyArray<Record<string, unknown>>;\n}\n\nexport interface FakeSqlClient {\n /**\n * Answers `rows` for any statement whose compiled SQL contains `match`. Later\n * registrations win, so a spec can override a default set up by a helper.\n */\n respondTo(match: string, rows: ReadonlyArray<Record<string, unknown>>): void;\n /**\n * Makes every subsequent execution fail, so the adapter's `EntifixConnError`\n * mapping is reachable.\n */\n failWith(message: string): void;\n /**\n * Makes only the statements containing `match` fail, leaving the rest working\n * — the way a select that succeeds and a count that then fails reaches a\n * distinct error branch.\n */\n failOn(match: string, message: string): void;\n /** Every statement executed, in order, for assertions about what ran. */\n readonly executions: ReadonlyArray<FakeSqlExecution>;\n /** The most recently executed statement. */\n readonly lastExecution: FakeSqlExecution | undefined;\n /**\n * The object to hand to `makeSqlRepository` in place of a real `SqlClient`.\n *\n * Typed `unknown` on purpose — casting at the call site keeps this fake honest\n * that it implements only the constructor surface the adapters use, not the\n * whole `SqlClient` (no transactions, no reactivity, no streaming).\n */\n readonly client: unknown;\n}\n\nconst unsupported = (name: string): never => {\n throw new TypeError(`fake sql: ${name} is not implemented`);\n};\n\n/**\n * The Postgres compiler's configuration, mirrored from `@effect/sql-pg` so the\n * fake emits exactly the dialect production does — `$n` placeholders and\n * double-quoted identifiers — without this package depending on the `pg` driver.\n *\n * `sql.updateValues` and the `PgJson` custom segment are deliberate `TypeError`s\n * rather than approximations: no adapter uses either, and a compiler that\n * half-emitted them would let a spec pass on SQL that real Postgres rejects.\n */\nconst pgCompiler = Statement.makeCompiler({\n dialect: 'pg',\n placeholder: index => `$${index}`,\n onIdentifier: Statement.defaultEscape('\"'),\n onRecordUpdate: () => unsupported('updateValues'),\n onCustom: () => unsupported('custom segments'),\n});\n\n/** Builds an in-memory stand-in for an `@effect/sql` client. */\nexport const makeFakeSqlClient = (\n seed: ReadonlyArray<FakeSqlResponse> = [],\n): FakeSqlClient => {\n const responses: FakeSqlResponse[] = [...seed];\n const executions: FakeSqlExecution[] = [];\n const failuresByMatch: Array<{ match: string; message: string }> = [];\n let failure: string | undefined;\n\n const answer = (sql: string) => {\n // Last registration wins, so an override does not have to remove the\n // default it replaces.\n for (let index = responses.length - 1; index >= 0; index -= 1) {\n const response = responses[index];\n if (response !== undefined && sql.includes(response.match)) {\n return response.rows;\n }\n }\n return [];\n };\n\n const execute = (sql: string, params: ReadonlyArray<unknown>) => {\n executions.push({ sql, params });\n\n const scoped = failuresByMatch.find(entry => sql.includes(entry.match));\n const message = scoped?.message ?? failure;\n if (message !== undefined) {\n return Effect.fail(\n new SqlError.SqlError({\n reason: new SqlError.UnknownError({\n cause: new Error(message),\n message,\n }),\n }),\n );\n }\n return Effect.succeed(answer(sql));\n };\n\n const connection = {\n execute: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeUnprepared: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeRaw: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeValues: () => unsupported('executeValues'),\n executeStream: () => unsupported('executeStream'),\n };\n\n return {\n respondTo: (match, rows) => {\n responses.push({ match, rows });\n },\n failWith: message => {\n failure = message;\n },\n failOn: (match, message) => {\n failuresByMatch.push({ match, message });\n },\n get executions() {\n return executions;\n },\n get lastExecution() {\n return executions[executions.length - 1];\n },\n client: Object.assign(\n Statement.make(\n Effect.succeed(connection) as never,\n pgCompiler,\n [],\n undefined,\n ),\n {\n /**\n * Runs `self` between a recorded `BEGIN` and `COMMIT`, or `ROLLBACK`\n * when it fails — enough for a spec to assert what a unit of work\n * committed and what it rolled back, though nothing is isolated.\n */\n withTransaction: <A, E, R>(self: Effect.Effect<A, E, R>) =>\n Effect.sync(() => executions.push({ sql: 'BEGIN', params: [] })).pipe(\n Effect.andThen(self),\n Effect.tapError(() =>\n Effect.sync(() =>\n executions.push({ sql: 'ROLLBACK', params: [] }),\n ),\n ),\n Effect.tap(() =>\n Effect.sync(() => executions.push({ sql: 'COMMIT', params: [] })),\n ),\n ),\n },\n ),\n };\n};\n"],"names":["Effect","SqlError","Statement","unsupported","name","TypeError","pgCompiler","makeCompiler","dialect","placeholder","index","onIdentifier","defaultEscape","onRecordUpdate","onCustom","makeFakeSqlClient","seed","responses","executions","failuresByMatch","failure","answer","sql","length","response","undefined","includes","match","rows","execute","params","push","scoped","find","entry","message","fail","reason","UnknownError","cause","Error","succeed","connection","executeUnprepared","executeRaw","executeValues","executeStream","respondTo","failWith","failOn","lastExecution","client","Object","assign","make","withTransaction","self","sync","pipe","andThen","tapError","tap"],"mappings":"AAAA;;;;;;;;;;;;;CAaC,GAED,SAASA,MAAM,QAAQ,SAAS;AAChC,SAASC,QAAQ,QAAQ,aAAa;AACtC,SAASC,SAAS,QAAQ,aAAa;AA8CvC,MAAMC,cAAc,CAACC;IACnB,MAAM,IAAIC,UAAU,CAAC,UAAU,EAAED,KAAK,mBAAmB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QACfa,mBAAmB,CAACrB,KAAaQ,SAC/BD,QAAQP,KAAKQ;QACfc,YAAY,CAACtB,KAAaQ,SACxBD,QAAQP,KAAKQ;QACfe,eAAe,IAAM1C,YAAY;QACjC2C,eAAe,IAAM3C,YAAY;IACnC;IAEA,OAAO;QACL4C,WAAW,CAACpB,OAAOC;YACjBX,UAAUc,IAAI,CAAC;gBAAEJ;gBAAOC;YAAK;QAC/B;QACAoB,UAAUb,CAAAA;YACRf,UAAUe;QACZ;QACAc,QAAQ,CAACtB,OAAOQ;YACdhB,gBAAgBY,IAAI,CAAC;gBAAEJ;gBAAOQ;YAAQ;QACxC;QACA,IAAIjB;YACF,OAAOA;QACT;QACA,IAAIgC;YACF,OAAOhC,UAAU,CAACA,WAAWK,MAAM,GAAG,EAAE;QAC1C;QACA4B,QAAQC,OAAOC,MAAM,CACnBnD,UAAUoD,IAAI,CACZtD,OAAOyC,OAAO,CAACC,aACfpC,YACA,EAAE,EACFmB,YAEF;YACE;;;;SAIC,GACD8B,iBAAiB,CAAUC,OACzBxD,OAAOyD,IAAI,CAAC,IAAMvC,WAAWa,IAAI,CAAC;wBAAET,KAAK;wBAASQ,QAAQ,EAAE;oBAAC,IAAI4B,IAAI,CACnE1D,OAAO2D,OAAO,CAACH,OACfxD,OAAO4D,QAAQ,CAAC,IACd5D,OAAOyD,IAAI,CAAC,IACVvC,WAAWa,IAAI,CAAC;4BAAET,KAAK;4BAAYQ,QAAQ,EAAE;wBAAC,MAGlD9B,OAAO6D,GAAG,CAAC,IACT7D,OAAOyD,IAAI,CAAC,IAAMvC,WAAWa,IAAI,CAAC;4BAAET,KAAK;4BAAUQ,QAAQ,EAAE;wBAAC;QAGtE;IAEJ;AACF,EAAE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@entifix/testing-unit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "Test doubles for entifix: in-memory ports, driver fakes for Mongo, Redis, RabbitMQ and SQL, MSW handlers and port contract suites.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -72,9 +72,9 @@
|
|
|
72
72
|
},
|
|
73
73
|
"dependencies": {
|
|
74
74
|
"@swc/helpers": "0.5.23",
|
|
75
|
-
"@entifix/
|
|
76
|
-
"@entifix/
|
|
77
|
-
"@entifix/
|
|
75
|
+
"@entifix/core": "0.12.0",
|
|
76
|
+
"@entifix/transactions": "0.12.0",
|
|
77
|
+
"@entifix/business": "0.12.0"
|
|
78
78
|
},
|
|
79
79
|
"peerDependencies": {
|
|
80
80
|
"@testing-library/react": "*",
|
|
@@ -82,7 +82,7 @@
|
|
|
82
82
|
"msw": ">=3",
|
|
83
83
|
"react": "*",
|
|
84
84
|
"vitest": "*",
|
|
85
|
-
"@entifix/react-controls": "0.
|
|
85
|
+
"@entifix/react-controls": "0.12.0"
|
|
86
86
|
},
|
|
87
87
|
"peerDependenciesMeta": {
|
|
88
88
|
"@entifix/react-controls": {
|