@entifix/testing-unit 0.23.12 → 0.23.13
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/outbox.contract.d.ts +2 -2
- package/dist/contracts/outbox.contract.d.ts.map +1 -1
- package/dist/contracts/outbox.contract.js +31 -7
- package/dist/contracts/outbox.contract.js.map +1 -1
- package/dist/contracts/server-push.contract.d.ts.map +1 -1
- package/dist/contracts/server-push.contract.js +19 -7
- package/dist/contracts/server-push.contract.js.map +1 -1
- package/dist/doubles/outbox.d.ts +4 -3
- package/dist/doubles/outbox.d.ts.map +1 -1
- package/dist/doubles/outbox.js +9 -19
- package/dist/doubles/outbox.js.map +1 -1
- package/package.json +5 -5
|
@@ -11,8 +11,8 @@ export interface OutboxUnderTest {
|
|
|
11
11
|
* ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)):
|
|
12
12
|
* a duplicate enqueue is recognised, each aggregate publishes in version
|
|
13
13
|
* order, a failing aggregate holds back only itself, a poisoned one is
|
|
14
|
-
* quarantined without blocking another,
|
|
15
|
-
* version.
|
|
14
|
+
* quarantined without blocking another, a bus outage spends no attempt, and a
|
|
15
|
+
* consumer discards a stale version.
|
|
16
16
|
*/
|
|
17
17
|
export declare const describeOutboxContract: (name: string, make: () => Effect.Effect<OutboxUnderTest, unknown>) => void;
|
|
18
18
|
//# sourceMappingURL=outbox.contract.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outbox.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/outbox.contract.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"outbox.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/outbox.contract.ts"],"names":[],"mappings":"AAMA,OAAO,EAEL,KAAK,QAAQ,EACb,KAAK,MAAM,EAEZ,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,wFAAwF;AACxF,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,8DAA8D;IAC9D,QAAQ,CAAC,KAAK,EAAE,CACd,GAAG,EAAE,QAAQ,EACb,WAAW,EAAE,MAAM,KAChB,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACrC;AAuCD;;;;;;;GAOG;AACH,eAAO,MAAM,sBAAsB,GACjC,MAAM,MAAM,EACZ,MAAM,MAAM,MAAM,CAAC,MAAM,CAAC,eAAe,EAAE,OAAO,CAAC,KAClD,IA0FF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Unavailable } from '@entifix/core';
|
|
1
|
+
import { ProtocolFailure, Unavailable } from '@entifix/core';
|
|
2
2
|
import { discardIfStale } from '@entifix/transactions';
|
|
3
3
|
import { Effect } from 'effect';
|
|
4
4
|
import { describe, expect, it } from 'vitest';
|
|
@@ -18,12 +18,16 @@ const event = (aggregate, version)=>{
|
|
|
18
18
|
data: {}
|
|
19
19
|
};
|
|
20
20
|
};
|
|
21
|
-
/**
|
|
21
|
+
/**
|
|
22
|
+
* A bus that records what it published and refuses the ids it is told to —
|
|
23
|
+
* by default as an entry it can never publish, which is what the attempts and
|
|
24
|
+
* the quarantine are for.
|
|
25
|
+
*/ const recordingBus = (refuse = new Set(), failure = new ProtocolFailure({
|
|
26
|
+
reason: 'unencodable'
|
|
27
|
+
}))=>{
|
|
22
28
|
const published = [];
|
|
23
29
|
const bus = {
|
|
24
|
-
publish: (published_)=>refuse.has(published_.id) ? Effect.fail(
|
|
25
|
-
dependency: 'contract-bus'
|
|
26
|
-
})) : Effect.sync(()=>{
|
|
30
|
+
publish: (published_)=>refuse.has(published_.id) ? Effect.fail(failure) : Effect.sync(()=>{
|
|
27
31
|
published.push(published_);
|
|
28
32
|
}),
|
|
29
33
|
/* v8 ignore next -- the relay only publishes; the bus port asks for both. */ subscribe: ()=>Effect.void
|
|
@@ -38,8 +42,8 @@ const event = (aggregate, version)=>{
|
|
|
38
42
|
* ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)):
|
|
39
43
|
* a duplicate enqueue is recognised, each aggregate publishes in version
|
|
40
44
|
* order, a failing aggregate holds back only itself, a poisoned one is
|
|
41
|
-
* quarantined without blocking another,
|
|
42
|
-
* version.
|
|
45
|
+
* quarantined without blocking another, a bus outage spends no attempt, and a
|
|
46
|
+
* consumer discards a stale version.
|
|
43
47
|
*/ export const describeOutboxContract = (name, make)=>{
|
|
44
48
|
const run = (effect)=>Effect.runPromise(effect);
|
|
45
49
|
describe(`Outbox contract: ${name}`, ()=>{
|
|
@@ -104,6 +108,26 @@ const event = (aggregate, version)=>{
|
|
|
104
108
|
quarantined: 1
|
|
105
109
|
});
|
|
106
110
|
});
|
|
111
|
+
// entifix #330: an outage is not the entry's fault, however long it lasts.
|
|
112
|
+
it('spends no attempt while the bus is down, and publishes once it is back', async ()=>{
|
|
113
|
+
const { outbox, drain } = await run(make());
|
|
114
|
+
await run(outbox.enqueue(event('a', 1)));
|
|
115
|
+
const down = recordingBus(new Set([
|
|
116
|
+
'a:1'
|
|
117
|
+
]), new Unavailable({
|
|
118
|
+
dependency: 'contract-bus'
|
|
119
|
+
}));
|
|
120
|
+
for(let pass = 0; pass < 3; pass += 1)await run(drain(down.bus, 1));
|
|
121
|
+
expect(await run(outbox.stats())).toMatchObject({
|
|
122
|
+
pending: 1,
|
|
123
|
+
quarantined: 0
|
|
124
|
+
});
|
|
125
|
+
const back = recordingBus();
|
|
126
|
+
expect(await run(drain(back.bus, 1))).toBe(1);
|
|
127
|
+
expect(back.published.map((e)=>e.id)).toEqual([
|
|
128
|
+
'a:1'
|
|
129
|
+
]);
|
|
130
|
+
});
|
|
107
131
|
it('lets a consumer discard a version it already applied', async ()=>{
|
|
108
132
|
const apply = Effect.succeed('applied');
|
|
109
133
|
expect(await run(discardIfStale(Effect.succeed(2), 1, apply))).toBe('stale');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/contracts/outbox.contract.ts"],"sourcesContent":["import { type DomainEvent, Unavailable } from '@entifix/core';\nimport {\n discardIfStale,\n type EventBus,\n type Outbox,\n type OutboxEvent,\n} from '@entifix/transactions';\nimport { Effect } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\n/** What a case needs from an outbox implementation: the port, and its relay's drain. */\nexport interface OutboxUnderTest {\n readonly outbox: Outbox;\n /** One relay pass over `outbox`, publishing through `bus`. */\n readonly drain: (\n bus: EventBus,\n maxAttempts: number,\n ) => Effect.Effect<number, unknown>;\n}\n\nlet clock = 0;\nconst event = (aggregate: string, version: number): OutboxEvent => {\n clock += 1;\n return {\n name: 'contract.changed',\n id: `${aggregate}:${String(version)}`,\n source: 'contract',\n at: new Date(Date.UTC(2026, 0, 1, 0, 0, clock)).toISOString(),\n aggregate: { type: 'contract', id: aggregate },\n version,\n data: {},\n };\n};\n\n/** A bus that records what it published and refuses the ids it is told to. */\nconst recordingBus = (refuse: ReadonlySet<string> = new Set()) => {\n const published: DomainEvent[] = [];\n const bus: EventBus = {\n publish: published_ =>\n refuse.has(published_.id)\n ? Effect.fail(new Unavailable({ dependency: 'contract-bus' }))\n : Effect.sync(() => {\n published.push(published_);\n }),\n /* v8 ignore next -- the relay only publishes; the bus port asks for both. */\n subscribe: () => Effect.void,\n };\n return { bus, published };\n};\n\n/**\n * What every {@link Outbox} and its relay must guarantee\n * ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)):\n * a duplicate enqueue is recognised, each aggregate publishes in version\n * order, a failing aggregate holds back only itself, a poisoned one is\n * quarantined without blocking another, and a consumer discards a stale\n * version.\n */\nexport const describeOutboxContract = (\n name: string,\n make: () => Effect.Effect<OutboxUnderTest, unknown>,\n): void => {\n const run = <A, E>(effect: Effect.Effect<A, E>) => Effect.runPromise(effect);\n\n describe(`Outbox contract: ${name}`, () => {\n it('recognises a duplicate enqueue by event id', async () => {\n const { outbox } = await run(make());\n const first = event('a', 1);\n\n expect(await run(outbox.enqueue(first))).toBe('enqueued');\n expect(await run(outbox.enqueue(first))).toBe('duplicate');\n });\n\n it('publishes each aggregate in version order', async () => {\n const { outbox, drain } = await run(make());\n for (const entry of [event('a', 1), event('b', 1), event('a', 2)])\n await run(outbox.enqueue(entry));\n const { bus, published } = recordingBus();\n\n expect(await run(drain(bus, 3))).toBe(3);\n expect(\n published.filter(e => e.aggregate?.id === 'a').map(e => e.version),\n ).toEqual([1, 2]);\n expect((await run(outbox.stats())).pending).toBe(0);\n });\n\n // The record's point: a failing head holds back its own aggregate only.\n it('holds back only the aggregate whose head failed', async () => {\n const { outbox, drain } = await run(make());\n for (const entry of [event('a', 1), event('a', 2), event('b', 1)])\n await run(outbox.enqueue(entry));\n const { bus, published } = recordingBus(new Set(['a:1']));\n\n await run(drain(bus, 3));\n\n expect(published.map(e => e.id)).toEqual(['b:1']);\n expect((await run(outbox.stats())).pending).toBe(2);\n });\n\n it('quarantines a poisoned aggregate without blocking another', async () => {\n const { outbox, drain } = await run(make());\n for (const entry of [event('a', 1), event('b', 1), event('a', 2)])\n await run(outbox.enqueue(entry));\n const { bus, published } = recordingBus(new Set(['a:1']));\n\n await run(drain(bus, 1));\n\n expect(published.map(e => e.id)).toEqual(['b:1', 'a:2']);\n expect(await run(outbox.stats())).toMatchObject({\n pending: 0,\n quarantined: 1,\n });\n });\n\n it('lets a consumer discard a version it already applied', async () => {\n const apply = Effect.succeed('applied' as const);\n\n expect(await run(discardIfStale(Effect.succeed(2), 1, apply))).toBe(\n 'stale',\n );\n expect(await run(discardIfStale(Effect.succeed(2), 2, apply))).toBe(\n 'stale',\n );\n expect(await run(discardIfStale(Effect.succeed(2), 3, apply))).toBe(\n 'applied',\n );\n expect(\n await run(discardIfStale(Effect.succeed(undefined), 1, apply)),\n ).toBe('applied');\n });\n });\n};\n"],"names":["Unavailable","discardIfStale","Effect","describe","expect","it","clock","event","aggregate","version","name","id","String","source","at","Date","UTC","toISOString","type","data","recordingBus","refuse","Set","published","bus","publish","published_","has","fail","dependency","sync","push","subscribe","void","describeOutboxContract","make","run","effect","runPromise","outbox","first","enqueue","toBe","drain","entry","filter","e","map","toEqual","stats","pending","toMatchObject","quarantined","apply","succeed","undefined"],"mappings":"AAAA,SAA2BA,WAAW,QAAQ,gBAAgB;AAC9D,SACEC,cAAc,QAIT,wBAAwB;AAC/B,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAY9C,IAAIC,QAAQ;AACZ,MAAMC,QAAQ,CAACC,WAAmBC;IAChCH,SAAS;IACT,OAAO;QACLI,MAAM;QACNC,IAAI,GAAGH,UAAU,CAAC,EAAEI,OAAOH,UAAU;QACrCI,QAAQ;QACRC,IAAI,IAAIC,KAAKA,KAAKC,GAAG,CAAC,MAAM,GAAG,GAAG,GAAG,GAAGV,QAAQW,WAAW;QAC3DT,WAAW;YAAEU,MAAM;YAAYP,IAAIH;QAAU;QAC7CC;QACAU,MAAM,CAAC;IACT;AACF;AAEA,4EAA4E,GAC5E,MAAMC,eAAe,CAACC,SAA8B,IAAIC,KAAK;IAC3D,MAAMC,YAA2B,EAAE;IACnC,MAAMC,MAAgB;QACpBC,SAASC,CAAAA,aACPL,OAAOM,GAAG,CAACD,WAAWf,EAAE,IACpBT,OAAO0B,IAAI,CAAC,IAAI5B,YAAY;gBAAE6B,YAAY;YAAe,MACzD3B,OAAO4B,IAAI,CAAC;gBACVP,UAAUQ,IAAI,CAACL;YACjB;QACN,2EAA2E,GAC3EM,WAAW,IAAM9B,OAAO+B,IAAI;IAC9B;IACA,OAAO;QAAET;QAAKD;IAAU;AAC1B;AAEA;;;;;;;CAOC,GACD,OAAO,MAAMW,yBAAyB,CACpCxB,MACAyB;IAEA,MAAMC,MAAM,CAAOC,SAAgCnC,OAAOoC,UAAU,CAACD;IAErElC,SAAS,CAAC,iBAAiB,EAAEO,MAAM,EAA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
+
{"version":3,"sources":["../../src/contracts/outbox.contract.ts"],"sourcesContent":["import {\n type DomainEvent,\n ProtocolFailure,\n type StoreFailure,\n Unavailable,\n} from '@entifix/core';\nimport {\n discardIfStale,\n type EventBus,\n type Outbox,\n type OutboxEvent,\n} from '@entifix/transactions';\nimport { Effect } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\n/** What a case needs from an outbox implementation: the port, and its relay's drain. */\nexport interface OutboxUnderTest {\n readonly outbox: Outbox;\n /** One relay pass over `outbox`, publishing through `bus`. */\n readonly drain: (\n bus: EventBus,\n maxAttempts: number,\n ) => Effect.Effect<number, unknown>;\n}\n\nlet clock = 0;\nconst event = (aggregate: string, version: number): OutboxEvent => {\n clock += 1;\n return {\n name: 'contract.changed',\n id: `${aggregate}:${String(version)}`,\n source: 'contract',\n at: new Date(Date.UTC(2026, 0, 1, 0, 0, clock)).toISOString(),\n aggregate: { type: 'contract', id: aggregate },\n version,\n data: {},\n };\n};\n\n/**\n * A bus that records what it published and refuses the ids it is told to —\n * by default as an entry it can never publish, which is what the attempts and\n * the quarantine are for.\n */\nconst recordingBus = (\n refuse: ReadonlySet<string> = new Set(),\n failure: StoreFailure = new ProtocolFailure({ reason: 'unencodable' }),\n) => {\n const published: DomainEvent[] = [];\n const bus: EventBus = {\n publish: published_ =>\n refuse.has(published_.id)\n ? Effect.fail(failure)\n : Effect.sync(() => {\n published.push(published_);\n }),\n /* v8 ignore next -- the relay only publishes; the bus port asks for both. */\n subscribe: () => Effect.void,\n };\n return { bus, published };\n};\n\n/**\n * What every {@link Outbox} and its relay must guarantee\n * ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)):\n * a duplicate enqueue is recognised, each aggregate publishes in version\n * order, a failing aggregate holds back only itself, a poisoned one is\n * quarantined without blocking another, a bus outage spends no attempt, and a\n * consumer discards a stale version.\n */\nexport const describeOutboxContract = (\n name: string,\n make: () => Effect.Effect<OutboxUnderTest, unknown>,\n): void => {\n const run = <A, E>(effect: Effect.Effect<A, E>) => Effect.runPromise(effect);\n\n describe(`Outbox contract: ${name}`, () => {\n it('recognises a duplicate enqueue by event id', async () => {\n const { outbox } = await run(make());\n const first = event('a', 1);\n\n expect(await run(outbox.enqueue(first))).toBe('enqueued');\n expect(await run(outbox.enqueue(first))).toBe('duplicate');\n });\n\n it('publishes each aggregate in version order', async () => {\n const { outbox, drain } = await run(make());\n for (const entry of [event('a', 1), event('b', 1), event('a', 2)])\n await run(outbox.enqueue(entry));\n const { bus, published } = recordingBus();\n\n expect(await run(drain(bus, 3))).toBe(3);\n expect(\n published.filter(e => e.aggregate?.id === 'a').map(e => e.version),\n ).toEqual([1, 2]);\n expect((await run(outbox.stats())).pending).toBe(0);\n });\n\n // The record's point: a failing head holds back its own aggregate only.\n it('holds back only the aggregate whose head failed', async () => {\n const { outbox, drain } = await run(make());\n for (const entry of [event('a', 1), event('a', 2), event('b', 1)])\n await run(outbox.enqueue(entry));\n const { bus, published } = recordingBus(new Set(['a:1']));\n\n await run(drain(bus, 3));\n\n expect(published.map(e => e.id)).toEqual(['b:1']);\n expect((await run(outbox.stats())).pending).toBe(2);\n });\n\n it('quarantines a poisoned aggregate without blocking another', async () => {\n const { outbox, drain } = await run(make());\n for (const entry of [event('a', 1), event('b', 1), event('a', 2)])\n await run(outbox.enqueue(entry));\n const { bus, published } = recordingBus(new Set(['a:1']));\n\n await run(drain(bus, 1));\n\n expect(published.map(e => e.id)).toEqual(['b:1', 'a:2']);\n expect(await run(outbox.stats())).toMatchObject({\n pending: 0,\n quarantined: 1,\n });\n });\n\n // entifix #330: an outage is not the entry's fault, however long it lasts.\n it('spends no attempt while the bus is down, and publishes once it is back', async () => {\n const { outbox, drain } = await run(make());\n await run(outbox.enqueue(event('a', 1)));\n const down = recordingBus(\n new Set(['a:1']),\n new Unavailable({ dependency: 'contract-bus' }),\n );\n\n for (let pass = 0; pass < 3; pass += 1) await run(drain(down.bus, 1));\n expect(await run(outbox.stats())).toMatchObject({\n pending: 1,\n quarantined: 0,\n });\n\n const back = recordingBus();\n expect(await run(drain(back.bus, 1))).toBe(1);\n expect(back.published.map(e => e.id)).toEqual(['a:1']);\n });\n\n it('lets a consumer discard a version it already applied', async () => {\n const apply = Effect.succeed('applied' as const);\n\n expect(await run(discardIfStale(Effect.succeed(2), 1, apply))).toBe(\n 'stale',\n );\n expect(await run(discardIfStale(Effect.succeed(2), 2, apply))).toBe(\n 'stale',\n );\n expect(await run(discardIfStale(Effect.succeed(2), 3, apply))).toBe(\n 'applied',\n );\n expect(\n await run(discardIfStale(Effect.succeed(undefined), 1, apply)),\n ).toBe('applied');\n });\n });\n};\n"],"names":["ProtocolFailure","Unavailable","discardIfStale","Effect","describe","expect","it","clock","event","aggregate","version","name","id","String","source","at","Date","UTC","toISOString","type","data","recordingBus","refuse","Set","failure","reason","published","bus","publish","published_","has","fail","sync","push","subscribe","void","describeOutboxContract","make","run","effect","runPromise","outbox","first","enqueue","toBe","drain","entry","filter","e","map","toEqual","stats","pending","toMatchObject","quarantined","down","dependency","pass","back","apply","succeed","undefined"],"mappings":"AAAA,SAEEA,eAAe,EAEfC,WAAW,QACN,gBAAgB;AACvB,SACEC,cAAc,QAIT,wBAAwB;AAC/B,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAY9C,IAAIC,QAAQ;AACZ,MAAMC,QAAQ,CAACC,WAAmBC;IAChCH,SAAS;IACT,OAAO;QACLI,MAAM;QACNC,IAAI,GAAGH,UAAU,CAAC,EAAEI,OAAOH,UAAU;QACrCI,QAAQ;QACRC,IAAI,IAAIC,KAAKA,KAAKC,GAAG,CAAC,MAAM,GAAG,GAAG,GAAG,GAAGV,QAAQW,WAAW;QAC3DT,WAAW;YAAEU,MAAM;YAAYP,IAAIH;QAAU;QAC7CC;QACAU,MAAM,CAAC;IACT;AACF;AAEA;;;;CAIC,GACD,MAAMC,eAAe,CACnBC,SAA8B,IAAIC,KAAK,EACv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,CAChB,KAAK,EAAE,WAAW,EAClB,UAAU,EAAE,uBAAuB,KAChC,OAAO,CAAC;IACb,QAAQ,CAAC,MAAM,CAAC,EAAE,CAChB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,SAAS,MAAM,EAAE,KACtB,MAAM,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC;CAC1C;AAyBD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,0BAA0B,GACrC,MAAM,MAAM,EACZ,MAAM,CACJ,OAAO,EAAE,yBAAyB,KAC/B,MAAM,CAAC,MAAM,CAAC,mBAAmB,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,KAC1D,IAyLF,CAAC"}
|
|
@@ -23,6 +23,7 @@ const org = (id)=>[
|
|
|
23
23
|
const topicsOf = (e)=>[
|
|
24
24
|
e.data.topic
|
|
25
25
|
];
|
|
26
|
+
const keyOf = (message)=>message._tag === 'event' ? message.event.id : `resync:${message.topics.join(',')}`;
|
|
26
27
|
/**
|
|
27
28
|
* What every server-push adapter must guarantee
|
|
28
29
|
* ([ADR 0021](../../../../../docs/adr/0021-server-push-and-the-multiplexed-channel.md)):
|
|
@@ -39,15 +40,26 @@ const topicsOf = (e)=>[
|
|
|
39
40
|
* first `count` messages it received.
|
|
40
41
|
*/ const receive = (options, connection, events, count)=>Effect.runPromise(Effect.scoped(Effect.gen(function*() {
|
|
41
42
|
const push = yield* make(options);
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
yield* Effect.
|
|
45
|
-
|
|
43
|
+
// Each message once, however many times its batch went out.
|
|
44
|
+
const seen = new Set();
|
|
45
|
+
const reading = yield* Effect.forkChild(Stream.runCollect(Stream.take(// Kept only when it grows the set: the first sighting.
|
|
46
|
+
Stream.filter(push.open(connection), (message)=>{
|
|
47
|
+
const before = seen.size;
|
|
48
|
+
seen.add(keyOf(message));
|
|
49
|
+
return seen.size > before;
|
|
50
|
+
}), count)));
|
|
51
|
+
// The port says nothing about when an opened stream is subscribed,
|
|
52
|
+
// so the batch goes out again every 10 ms until the reader has what
|
|
53
|
+
// it waits for. A single publish after a fixed sleep raced a loaded
|
|
54
|
+
// CI runner: the events reached nobody and the case timed out. A
|
|
55
|
+
// batch publishes without yielding, so a subscription never lands
|
|
56
|
+
// halfway through one.
|
|
57
|
+
const publishing = Effect.forEach(events, push.publish, {
|
|
46
58
|
discard: true
|
|
47
|
-
});
|
|
48
|
-
return Array.from((yield* Fiber.join(reading)));
|
|
59
|
+
}).pipe(Effect.andThen(Effect.sleep('10 millis')), Effect.forever);
|
|
60
|
+
return Array.from((yield* Effect.raceFirst(Fiber.join(reading), publishing)));
|
|
49
61
|
})));
|
|
50
|
-
const ids = (messages)=>messages.map(
|
|
62
|
+
const ids = (messages)=>messages.map(keyOf);
|
|
51
63
|
describe(`${name} — the server-push contract`, ()=>{
|
|
52
64
|
it('delivers an event in a subscribed topic that its audience admits', async ()=>{
|
|
53
65
|
const got = await receive({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/contracts/server-push.contract.ts"],"sourcesContent":["import type { AudienceRecipient, DomainEvent } from '@entifix/core';\nimport { Effect, Fiber, type Scope, Stream } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\n/**\n * The push port as a case exercises it.\n *\n * Declared here structurally rather than imported, because the service shell\n * that owns the port depends on this package for its own specs; any\n * `ServerPush` satisfies it.\n */\nexport interface PushConnectionUnderTest {\n readonly recipient: AudienceRecipient;\n readonly topics: readonly string[];\n readonly cursor?: string;\n}\n\nexport type PushMessageUnderTest =\n | {\n readonly _tag: 'event';\n readonly event: DomainEvent;\n readonly topics: readonly string[];\n }\n | { readonly _tag: 'resync'; readonly topics: readonly string[] };\n\nexport interface ServerPushUnderTest {\n readonly publish: (event: DomainEvent) => Effect.Effect<void>;\n readonly open: (\n connection: PushConnectionUnderTest,\n ) => Stream.Stream<PushMessageUnderTest>;\n}\n\nexport interface ServerPushContractOptions {\n readonly topicsOf: (event: DomainEvent) => readonly string[];\n readonly admits?: (\n event: DomainEvent,\n connection: PushConnectionUnderTest,\n ) => boolean;\n readonly resume?: (\n cursor: string,\n topics: readonly string[],\n ) => Stream.Stream<PushMessageUnderTest>;\n}\n\nconst event = (\n id: string,\n topic: string,\n audience?: DomainEvent['audience'],\n): DomainEvent => ({\n name: 'thing.changed',\n id,\n source: 'contract',\n at: '2026-11-02T00:00:00.000Z',\n correlationId: id,\n ...(audience === undefined ? {} : { audience }),\n data: { topic },\n});\n\nconst org = (id: string) => [{ kind: 'organization' as const, id }];\n\nconst topicsOf = (e: DomainEvent) => [(e.data as { topic: string }).topic];\n\n/**\n * What every server-push adapter must guarantee\n * ([ADR 0021](../../../../../docs/adr/0021-server-push-and-the-multiplexed-channel.md)):\n * a connection receives only the topics it asked for and only what its\n * audience admits, each event naming which of its topics it matched; an event naming no audience reaches nobody; a flow event\n * reaches only the holder of its capability; a host filter replaces the\n * default; and a reconnect is answered by the resume hook before anything\n * live, or by a resync when the host has none.\n *\n * `make` builds a fresh port with the given options inside the case's scope.\n */\nexport const describeServerPushContract = (\n name: string,\n make: (\n options: ServerPushContractOptions,\n ) => Effect.Effect<ServerPushUnderTest, never, Scope.Scope>,\n): void => {\n /**\n * Opens `connection`, publishes `events` once it is reading, and returns the\n * first `count` messages it received.\n */\n const receive = (\n options: ServerPushContractOptions,\n connection: PushConnectionUnderTest,\n events: readonly DomainEvent[],\n count: number,\n ) =>\n Effect.runPromise(\n Effect.scoped(\n Effect.gen(function* () {\n const push = yield* make(options);\n const reading = yield* Effect.forkChild(\n Stream.runCollect(Stream.take(push.open(connection), count)),\n );\n // Let the connection subscribe before anything is published.\n yield* Effect.sleep('10 millis');\n yield* Effect.forEach(events, push.publish, { discard: true });\n return Array.from(yield* Fiber.join(reading));\n }),\n ),\n );\n\n const ids = (messages: readonly PushMessageUnderTest[]) =>\n messages.map(m => (m._tag === 'event' ? m.event.id : `resync:${m.topics}`));\n\n describe(`${name} — the server-push contract`, () => {\n it('delivers an event in a subscribed topic that its audience admits', async () => {\n const got = await receive(\n { topicsOf },\n { recipient: { organizationId: 'a' }, topics: ['entity:x'] },\n [event('e1', 'entity:x', org('a'))],\n 1,\n );\n expect(ids(got)).toEqual(['e1']);\n });\n\n it('names the topics of the connection an event matched, and only those', async () => {\n const got = await receive(\n { topicsOf: () => ['entity:x', 'record:x:1', 'entity:y'] },\n {\n recipient: { organizationId: 'a' },\n topics: ['record:x:1', 'entity:x'],\n },\n [event('e1', 'entity:x', org('a'))],\n 1,\n );\n expect(got[0]).toMatchObject({\n _tag: 'event',\n topics: ['entity:x', 'record:x:1'],\n });\n });\n\n it('withholds an event in a topic the connection did not ask for', async () => {\n const got = await receive(\n { topicsOf },\n { recipient: { organizationId: 'a' }, topics: ['entity:x'] },\n [event('e1', 'entity:y', org('a')), event('e2', 'entity:x', org('a'))],\n 1,\n );\n expect(ids(got)).toEqual(['e2']);\n });\n\n it('reaches nobody with an event that names no audience', async () => {\n const got = await receive(\n { topicsOf },\n { recipient: { organizationId: 'a' }, topics: ['entity:x'] },\n [\n event('e1', 'entity:x'),\n event('e2', 'entity:x', []),\n event('e3', 'entity:x', org('a')),\n ],\n 1,\n );\n expect(ids(got)).toEqual(['e3']);\n });\n\n it(\"never delivers one organization's event to another\", async () => {\n const got = await receive(\n { topicsOf },\n { recipient: { organizationId: 'b' }, topics: ['entity:x'] },\n [event('e1', 'entity:x', org('a')), event('e2', 'entity:x', org('b'))],\n 1,\n );\n expect(ids(got)).toEqual(['e2']);\n });\n\n it('delivers a flow event only to the holder of its capability digest', async () => {\n const flow = [{ kind: 'flow' as const, id: 'f-1', digest: 'd-1' }];\n const stranger = await receive(\n { topicsOf },\n { recipient: { flowDigests: ['d-2'] }, topics: ['flow:f-1'] },\n [\n event('e1', 'flow:f-1', flow),\n event('e2', 'flow:f-1', [{ kind: 'flow', id: 'f-1', digest: 'd-2' }]),\n ],\n 1,\n );\n expect(ids(stranger)).toEqual(['e2']);\n const holder = await receive(\n { topicsOf },\n { recipient: { flowDigests: ['d-1'] }, topics: ['flow:f-1'] },\n [event('e1', 'flow:f-1', flow)],\n 1,\n );\n expect(ids(holder)).toEqual(['e1']);\n });\n\n it(\"replaces the default with the host's filter\", async () => {\n const got = await receive(\n { topicsOf, admits: e => e.id !== 'e1' },\n { recipient: {}, topics: ['entity:x'] },\n [event('e1', 'entity:x', org('a')), event('e2', 'entity:x')],\n 1,\n );\n expect(ids(got)).toEqual(['e2']);\n });\n\n it('answers a reconnect from the resume hook before anything live', async () => {\n const got = await receive(\n {\n topicsOf,\n resume: (cursor, topics) =>\n Stream.make({ _tag: 'resync', topics: [`${cursor}>${topics}`] }),\n },\n {\n recipient: { organizationId: 'a' },\n topics: ['flow:f'],\n cursor: 'c-9',\n },\n [event('e1', 'flow:f', org('a'))],\n 2,\n );\n expect(ids(got)).toEqual(['resync:c-9>flow:f', 'e1']);\n });\n\n it('asks a reconnect to re-read every topic when the host has no resume hook', async () => {\n const got = await receive(\n { topicsOf },\n {\n recipient: { organizationId: 'a' },\n topics: ['entity:x', 'record:x:1'],\n cursor: 'c-1',\n },\n [],\n 1,\n );\n expect(got).toEqual([\n { _tag: 'resync', topics: ['entity:x', 'record:x:1'] },\n ]);\n });\n\n it('accepts a publish with no connection open', async () => {\n await Effect.runPromise(\n Effect.scoped(\n Effect.flatMap(make({ topicsOf }), push =>\n push.publish(event('e1', 'entity:x', org('a'))),\n ),\n ),\n );\n });\n });\n};\n"],"names":["Effect","Fiber","Stream","describe","expect","it","event","id","topic","audience","name","source","at","correlationId","undefined","data","org","kind","topicsOf","e","describeServerPushContract","make","receive","options","connection","events","count","runPromise","scoped","gen","push","reading","forkChild","runCollect","take","open","sleep","forEach","publish","discard","Array","from","join","ids","messages","map","m","_tag","topics","got","recipient","organizationId","toEqual","toMatchObject","flow","digest","stranger","flowDigests","holder","admits","resume","cursor","flatMap"],"mappings":";AACA,SAASA,MAAM,EAAEC,KAAK,EAAcC,MAAM,QAAQ,SAAS;AAC3D,SAASC,QAAQ,EAAEC,MA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IM,MAAMG,OAAO,CAAC;gBAAC;aAAK;QACjC;QAEA/C,GAAG,iEAAiE;YAClE,MAAM4C,MAAM,MAAM3B,QAChB;gBACEJ;gBACA0C,QAAQ,CAACC,QAAQb,SACf9C,OAAOmB,IAAI,CAAC;wBAAE0B,MAAM;wBAAUC,QAAQ;4BAAC,GAAGa,OAAO,CAAC,EAAEb,QAAQ;yBAAC;oBAAC;YAClE,GACA;gBACEE,WAAW;oBAAEC,gBAAgB;gBAAI;gBACjCH,QAAQ;oBAAC;iBAAS;gBAClBa,QAAQ;YACV,GACA;gBAACvD,MAAM,MAAM,UAAUU,IAAI;aAAM,EACjC;YAEFZ,OAAOuC,IAAIM,MAAMG,OAAO,CAAC;gBAAC;gBAAqB;aAAK;QACtD;QAEA/C,GAAG,4EAA4E;YAC7E,MAAM4C,MAAM,MAAM3B,QAChB;gBAAEJ;YAAS,GACX;gBACEgC,WAAW;oBAAEC,gBAAgB;gBAAI;gBACjCH,QAAQ;oBAAC;oBAAY;iBAAa;gBAClCa,QAAQ;YACV,GACA,EAAE,EACF;YAEFzD,OAAO6C,KAAKG,OAAO,CAAC;gBAClB;oBAAEL,MAAM;oBAAUC,QAAQ;wBAAC;wBAAY;qBAAa;gBAAC;aACtD;QACH;QAEA3C,GAAG,6CAA6C;YAC9C,MAAML,OAAO2B,UAAU,CACrB3B,OAAO4B,MAAM,CACX5B,OAAO8D,OAAO,CAACzC,KAAK;gBAAEH;YAAS,IAAIY,CAAAA,OACjCA,KAAKQ,OAAO,CAAChC,MAAM,MAAM,YAAYU,IAAI;QAIjD;IACF;AACF,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../src/contracts/server-push.contract.ts"],"sourcesContent":["import type { AudienceRecipient, DomainEvent } from '@entifix/core';\nimport { Effect, Fiber, type Scope, Stream } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\n/**\n * The push port as a case exercises it.\n *\n * Declared here structurally rather than imported, because the service shell\n * that owns the port depends on this package for its own specs; any\n * `ServerPush` satisfies it.\n */\nexport interface PushConnectionUnderTest {\n readonly recipient: AudienceRecipient;\n readonly topics: readonly string[];\n readonly cursor?: string;\n}\n\nexport type PushMessageUnderTest =\n | {\n readonly _tag: 'event';\n readonly event: DomainEvent;\n readonly topics: readonly string[];\n }\n | { readonly _tag: 'resync'; readonly topics: readonly string[] };\n\nexport interface ServerPushUnderTest {\n readonly publish: (event: DomainEvent) => Effect.Effect<void>;\n readonly open: (\n connection: PushConnectionUnderTest,\n ) => Stream.Stream<PushMessageUnderTest>;\n}\n\nexport interface ServerPushContractOptions {\n readonly topicsOf: (event: DomainEvent) => readonly string[];\n readonly admits?: (\n event: DomainEvent,\n connection: PushConnectionUnderTest,\n ) => boolean;\n readonly resume?: (\n cursor: string,\n topics: readonly string[],\n ) => Stream.Stream<PushMessageUnderTest>;\n}\n\nconst event = (\n id: string,\n topic: string,\n audience?: DomainEvent['audience'],\n): DomainEvent => ({\n name: 'thing.changed',\n id,\n source: 'contract',\n at: '2026-11-02T00:00:00.000Z',\n correlationId: id,\n ...(audience === undefined ? {} : { audience }),\n data: { topic },\n});\n\nconst org = (id: string) => [{ kind: 'organization' as const, id }];\n\nconst topicsOf = (e: DomainEvent) => [(e.data as { topic: string }).topic];\n\nconst keyOf = (message: PushMessageUnderTest) =>\n message._tag === 'event'\n ? message.event.id\n : `resync:${message.topics.join(',')}`;\n\n/**\n * What every server-push adapter must guarantee\n * ([ADR 0021](../../../../../docs/adr/0021-server-push-and-the-multiplexed-channel.md)):\n * a connection receives only the topics it asked for and only what its\n * audience admits, each event naming which of its topics it matched; an event naming no audience reaches nobody; a flow event\n * reaches only the holder of its capability; a host filter replaces the\n * default; and a reconnect is answered by the resume hook before anything\n * live, or by a resync when the host has none.\n *\n * `make` builds a fresh port with the given options inside the case's scope.\n */\nexport const describeServerPushContract = (\n name: string,\n make: (\n options: ServerPushContractOptions,\n ) => Effect.Effect<ServerPushUnderTest, never, Scope.Scope>,\n): void => {\n /**\n * Opens `connection`, publishes `events` once it is reading, and returns the\n * first `count` messages it received.\n */\n const receive = (\n options: ServerPushContractOptions,\n connection: PushConnectionUnderTest,\n events: readonly DomainEvent[],\n count: number,\n ) =>\n Effect.runPromise(\n Effect.scoped(\n Effect.gen(function* () {\n const push = yield* make(options);\n // Each message once, however many times its batch went out.\n const seen = new Set<string>();\n const reading = yield* Effect.forkChild(\n Stream.runCollect(\n Stream.take(\n // Kept only when it grows the set: the first sighting.\n Stream.filter(push.open(connection), message => {\n const before = seen.size;\n seen.add(keyOf(message));\n return seen.size > before;\n }),\n count,\n ),\n ),\n );\n // The port says nothing about when an opened stream is subscribed,\n // so the batch goes out again every 10 ms until the reader has what\n // it waits for. A single publish after a fixed sleep raced a loaded\n // CI runner: the events reached nobody and the case timed out. A\n // batch publishes without yielding, so a subscription never lands\n // halfway through one.\n const publishing = Effect.forEach(events, push.publish, {\n discard: true,\n }).pipe(Effect.andThen(Effect.sleep('10 millis')), Effect.forever);\n return Array.from(\n yield* Effect.raceFirst(Fiber.join(reading), publishing),\n );\n }),\n ),\n );\n\n const ids = (messages: readonly PushMessageUnderTest[]) =>\n messages.map(keyOf);\n\n describe(`${name} — the server-push contract`, () => {\n it('delivers an event in a subscribed topic that its audience admits', async () => {\n const got = await receive(\n { topicsOf },\n { recipient: { organizationId: 'a' }, topics: ['entity:x'] },\n [event('e1', 'entity:x', org('a'))],\n 1,\n );\n expect(ids(got)).toEqual(['e1']);\n });\n\n it('names the topics of the connection an event matched, and only those', async () => {\n const got = await receive(\n { topicsOf: () => ['entity:x', 'record:x:1', 'entity:y'] },\n {\n recipient: { organizationId: 'a' },\n topics: ['record:x:1', 'entity:x'],\n },\n [event('e1', 'entity:x', org('a'))],\n 1,\n );\n expect(got[0]).toMatchObject({\n _tag: 'event',\n topics: ['entity:x', 'record:x:1'],\n });\n });\n\n it('withholds an event in a topic the connection did not ask for', async () => {\n const got = await receive(\n { topicsOf },\n { recipient: { organizationId: 'a' }, topics: ['entity:x'] },\n [event('e1', 'entity:y', org('a')), event('e2', 'entity:x', org('a'))],\n 1,\n );\n expect(ids(got)).toEqual(['e2']);\n });\n\n it('reaches nobody with an event that names no audience', async () => {\n const got = await receive(\n { topicsOf },\n { recipient: { organizationId: 'a' }, topics: ['entity:x'] },\n [\n event('e1', 'entity:x'),\n event('e2', 'entity:x', []),\n event('e3', 'entity:x', org('a')),\n ],\n 1,\n );\n expect(ids(got)).toEqual(['e3']);\n });\n\n it(\"never delivers one organization's event to another\", async () => {\n const got = await receive(\n { topicsOf },\n { recipient: { organizationId: 'b' }, topics: ['entity:x'] },\n [event('e1', 'entity:x', org('a')), event('e2', 'entity:x', org('b'))],\n 1,\n );\n expect(ids(got)).toEqual(['e2']);\n });\n\n it('delivers a flow event only to the holder of its capability digest', async () => {\n const flow = [{ kind: 'flow' as const, id: 'f-1', digest: 'd-1' }];\n const stranger = await receive(\n { topicsOf },\n { recipient: { flowDigests: ['d-2'] }, topics: ['flow:f-1'] },\n [\n event('e1', 'flow:f-1', flow),\n event('e2', 'flow:f-1', [{ kind: 'flow', id: 'f-1', digest: 'd-2' }]),\n ],\n 1,\n );\n expect(ids(stranger)).toEqual(['e2']);\n const holder = await receive(\n { topicsOf },\n { recipient: { flowDigests: ['d-1'] }, topics: ['flow:f-1'] },\n [event('e1', 'flow:f-1', flow)],\n 1,\n );\n expect(ids(holder)).toEqual(['e1']);\n });\n\n it(\"replaces the default with the host's filter\", async () => {\n const got = await receive(\n { topicsOf, admits: e => e.id !== 'e1' },\n { recipient: {}, topics: ['entity:x'] },\n [event('e1', 'entity:x', org('a')), event('e2', 'entity:x')],\n 1,\n );\n expect(ids(got)).toEqual(['e2']);\n });\n\n it('answers a reconnect from the resume hook before anything live', async () => {\n const got = await receive(\n {\n topicsOf,\n resume: (cursor, topics) =>\n Stream.make({ _tag: 'resync', topics: [`${cursor}>${topics}`] }),\n },\n {\n recipient: { organizationId: 'a' },\n topics: ['flow:f'],\n cursor: 'c-9',\n },\n [event('e1', 'flow:f', org('a'))],\n 2,\n );\n expect(ids(got)).toEqual(['resync:c-9>flow:f', 'e1']);\n });\n\n it('asks a reconnect to re-read every topic when the host has no resume hook', async () => {\n const got = await receive(\n { topicsOf },\n {\n recipient: { organizationId: 'a' },\n topics: ['entity:x', 'record:x:1'],\n cursor: 'c-1',\n },\n [],\n 1,\n );\n expect(got).toEqual([\n { _tag: 'resync', topics: ['entity:x', 'record:x:1'] },\n ]);\n });\n\n it('accepts a publish with no connection open', async () => {\n await Effect.runPromise(\n Effect.scoped(\n Effect.flatMap(make({ topicsOf }), push =>\n push.publish(event('e1', 'entity:x', org('a'))),\n ),\n ),\n );\n });\n });\n};\n"],"names":["Effect","Fiber","Stream","describe","expect","it","event","id","topic","audience","name","source","at","correlationId","undefined","data","org","kind","topicsOf","e","keyOf","message","_tag","topics","join","describeServerPushContract","make","receive","options","connection","events","count","runPromise","scoped","gen","push","seen","Set","reading","forkChild","runCollect","take","filter","open","before","size","add","publishing","forEach","publish","discard","pipe","andThen","sleep","forever","Array","from","raceFirst","ids","messages","map","got","recipient","organizationId","toEqual","toMatchObject","flow","digest","stranger","flowDigests","holder","admits","resume","cursor","flatMap"],"mappings":";AACA,SAASA,MAAM,EAAEC,KAAK,EAAcC,MAAM,QAAQ,SAAS;AAC3D,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AA0C9C,MAAMC,QAAQ,CACZC,IACAC,OACAC,WACiB;QACjBC,MAAM;QACNH;QACAI,QAAQ;QACRC,IAAI;QACJC,eAAeN;OACXE,aAAaK,YAAY,CAAC,IAAI;QAAEL;IAAS;QAC7CM,MAAM;YAAEP;QAAM;;AAGhB,MAAMQ,MAAM,CAACT,KAAe;QAAC;YAAEU,MAAM;YAAyBV;QAAG;KAAE;AAEnE,MAAMW,WAAW,CAACC,IAAmB;QAAEA,EAAEJ,IAAI,CAAuBP,KAAK;KAAC;AAE1E,MAAMY,QAAQ,CAACC,UACbA,QAAQC,IAAI,KAAK,UACbD,QAAQf,KAAK,CAACC,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iE;YAClE,MAAMwD,MAAM,MAAMlC,QAChB;gBACET;gBACAsD,QAAQ,CAACC,QAAQlD,SACfrB,OAAOwB,IAAI,CAAC;wBAAEJ,MAAM;wBAAUC,QAAQ;4BAAC,GAAGkD,OAAO,CAAC,EAAElD,QAAQ;yBAAC;oBAAC;YAClE,GACA;gBACEuC,WAAW;oBAAEC,gBAAgB;gBAAI;gBACjCxC,QAAQ;oBAAC;iBAAS;gBAClBkD,QAAQ;YACV,GACA;gBAACnE,MAAM,MAAM,UAAUU,IAAI;aAAM,EACjC;YAEFZ,OAAOsD,IAAIG,MAAMG,OAAO,CAAC;gBAAC;gBAAqB;aAAK;QACtD;QAEA3D,GAAG,4EAA4E;YAC7E,MAAMwD,MAAM,MAAMlC,QAChB;gBAAET;YAAS,GACX;gBACE4C,WAAW;oBAAEC,gBAAgB;gBAAI;gBACjCxC,QAAQ;oBAAC;oBAAY;iBAAa;gBAClCkD,QAAQ;YACV,GACA,EAAE,EACF;YAEFrE,OAAOyD,KAAKG,OAAO,CAAC;gBAClB;oBAAE1C,MAAM;oBAAUC,QAAQ;wBAAC;wBAAY;qBAAa;gBAAC;aACtD;QACH;QAEAlB,GAAG,6CAA6C;YAC9C,MAAML,OAAOgC,UAAU,CACrBhC,OAAOiC,MAAM,CACXjC,OAAO0E,OAAO,CAAChD,KAAK;gBAAER;YAAS,IAAIiB,CAAAA,OACjCA,KAAKc,OAAO,CAAC3C,MAAM,MAAM,YAAYU,IAAI;QAIjD;IACF;AACF,EAAE"}
|
package/dist/doubles/outbox.d.ts
CHANGED
|
@@ -4,9 +4,10 @@ export interface InMemoryOutbox extends Outbox {
|
|
|
4
4
|
/** Every entry, in enqueue order. */
|
|
5
5
|
readonly entries: readonly OutboxEntry[];
|
|
6
6
|
/**
|
|
7
|
-
* One relay pass
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* One relay pass — the relay's own `drainOutbox`, so the double cannot
|
|
8
|
+
* drift from it: oldest first, in order within each aggregate, a failing
|
|
9
|
+
* head holding back only its own aggregate, no attempt spent while the bus
|
|
10
|
+
* is down, and quarantine at `maxAttempts`.
|
|
10
11
|
*/
|
|
11
12
|
readonly drain: (bus: EventBus, maxAttempts: number) => Effect.Effect<number>;
|
|
12
13
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outbox.d.ts","sourceRoot":"","sources":["../../src/doubles/outbox.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"outbox.d.ts","sourceRoot":"","sources":["../../src/doubles/outbox.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,QAAQ,EACb,KAAK,MAAM,EACX,KAAK,WAAW,EACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,MAAM,WAAW,cAAe,SAAQ,MAAM;IAC5C,qCAAqC;IACrC,QAAQ,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;IACzC;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,EAAE,CAAC,GAAG,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,KAAK,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;CAC/E;AAED,qEAAqE;AACrE,eAAO,MAAM,kBAAkB,QAAO,cAmErC,CAAC"}
|
package/dist/doubles/outbox.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
-
import {
|
|
3
|
-
import { Effect
|
|
2
|
+
import { drainOutbox } from '@entifix/transactions/engine';
|
|
3
|
+
import { Effect } from 'effect';
|
|
4
4
|
/** An {@link Outbox} over an array, for a spec that has no store. */ export const makeInMemoryOutbox = ()=>{
|
|
5
5
|
const entries = [];
|
|
6
6
|
const find = (eventId)=>entries.find((entry)=>entry.eventId === eventId);
|
|
@@ -32,6 +32,10 @@ import { Effect, Result } from 'effect';
|
|
|
32
32
|
stored.lastError = error;
|
|
33
33
|
stored.quarantined = quarantine;
|
|
34
34
|
}),
|
|
35
|
+
hold: (entry, reason)=>Effect.sync(()=>{
|
|
36
|
+
const stored = find(entry.eventId);
|
|
37
|
+
if (stored !== undefined) stored.lastError = reason;
|
|
38
|
+
}),
|
|
35
39
|
stats: ()=>Effect.sync(()=>{
|
|
36
40
|
const pending = pendingOnes();
|
|
37
41
|
const oldest = pending[0];
|
|
@@ -43,23 +47,9 @@ import { Effect, Result } from 'effect';
|
|
|
43
47
|
});
|
|
44
48
|
})
|
|
45
49
|
};
|
|
46
|
-
const drain = (bus, maxAttempts)=>
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
for (const entry of yield* outbox.pending(Number.MAX_SAFE_INTEGER)){
|
|
50
|
-
const key = aggregateKey(entry.aggregate);
|
|
51
|
-
if (held.has(key)) continue;
|
|
52
|
-
const outcome = yield* Effect.result(bus.publish(entry.event));
|
|
53
|
-
if (Result.isFailure(outcome)) {
|
|
54
|
-
const quarantine = entry.attempts + 1 >= maxAttempts;
|
|
55
|
-
yield* outbox.recordFailure(entry, outcome.failure.message, quarantine);
|
|
56
|
-
if (!quarantine) held.add(key);
|
|
57
|
-
continue;
|
|
58
|
-
}
|
|
59
|
-
yield* outbox.markSent(entry);
|
|
60
|
-
sent += 1;
|
|
61
|
-
}
|
|
62
|
-
return sent;
|
|
50
|
+
const drain = (bus, maxAttempts)=>drainOutbox(outbox, bus, {
|
|
51
|
+
maxAttempts,
|
|
52
|
+
database: 'in-memory'
|
|
63
53
|
}).pipe(Effect.orDie);
|
|
64
54
|
return _extends({}, outbox, {
|
|
65
55
|
entries,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/doubles/outbox.ts"],"sourcesContent":["import {\n
|
|
1
|
+
{"version":3,"sources":["../../src/doubles/outbox.ts"],"sourcesContent":["import {\n type EventBus,\n type Outbox,\n type OutboxEntry,\n} from '@entifix/transactions';\nimport { drainOutbox } from '@entifix/transactions/engine';\nimport { Effect } from 'effect';\n\nexport interface InMemoryOutbox extends Outbox {\n /** Every entry, in enqueue order. */\n readonly entries: readonly OutboxEntry[];\n /**\n * One relay pass — the relay's own `drainOutbox`, so the double cannot\n * drift from it: oldest first, in order within each aggregate, a failing\n * head holding back only its own aggregate, no attempt spent while the bus\n * is down, and quarantine at `maxAttempts`.\n */\n readonly drain: (bus: EventBus, maxAttempts: number) => Effect.Effect<number>;\n}\n\n/** An {@link Outbox} over an array, for a spec that has no store. */\nexport const makeInMemoryOutbox = (): InMemoryOutbox => {\n const entries: OutboxEntry[] = [];\n const find = (eventId: string) =>\n entries.find(entry => entry.eventId === eventId);\n const pendingOnes = () =>\n entries\n .filter(entry => !entry.sent && !entry.quarantined)\n .sort(\n (a, b) =>\n a.createdAt.localeCompare(b.createdAt) || a.version - b.version,\n );\n\n const outbox: Outbox = {\n enqueue: event =>\n Effect.sync(() => {\n if (find(event.id) !== undefined) return 'duplicate' as const;\n entries.push({\n eventId: event.id,\n aggregate: event.aggregate,\n version: event.version,\n event,\n sent: false,\n attempts: 0,\n quarantined: false,\n createdAt: event.at,\n });\n return 'enqueued' as const;\n }),\n pending: limit => Effect.sync(() => pendingOnes().slice(0, limit)),\n markSent: entry =>\n Effect.sync(() => {\n const stored = find(entry.eventId);\n if (stored !== undefined) stored.sent = true;\n }),\n recordFailure: (entry, error, quarantine) =>\n Effect.sync(() => {\n const stored = find(entry.eventId);\n if (stored === undefined) return;\n stored.attempts += 1;\n stored.lastError = error;\n stored.quarantined = quarantine;\n }),\n hold: (entry, reason) =>\n Effect.sync(() => {\n const stored = find(entry.eventId);\n if (stored !== undefined) stored.lastError = reason;\n }),\n stats: () =>\n Effect.sync(() => {\n const pending = pendingOnes();\n const oldest = pending[0];\n return {\n pending: pending.length,\n quarantined: entries.filter(entry => entry.quarantined).length,\n ...(oldest === undefined\n ? {}\n : { oldestPendingAt: oldest.createdAt }),\n };\n }),\n };\n\n const drain = (bus: EventBus, maxAttempts: number) =>\n drainOutbox(outbox, bus, { maxAttempts, database: 'in-memory' }).pipe(\n Effect.orDie,\n );\n\n return { ...outbox, entries, drain };\n};\n"],"names":["drainOutbox","Effect","makeInMemoryOutbox","entries","find","eventId","entry","pendingOnes","filter","sent","quarantined","sort","a","b","createdAt","localeCompare","version","outbox","enqueue","event","sync","id","undefined","push","aggregate","attempts","at","pending","limit","slice","markSent","stored","recordFailure","error","quarantine","lastError","hold","reason","stats","oldest","length","oldestPendingAt","drain","bus","maxAttempts","database","pipe","orDie"],"mappings":";AAKA,SAASA,WAAW,QAAQ,+BAA+B;AAC3D,SAASC,MAAM,QAAQ,SAAS;AAchC,mEAAmE,GACnE,OAAO,MAAMC,qBAAqB;IAChC,MAAMC,UAAyB,EAAE;IACjC,MAAMC,OAAO,CAACC,UACZF,QAAQC,IAAI,CAACE,CAAAA,QAASA,MAAMD,OAAO,KAAKA;IAC1C,MAAME,cAAc,IAClBJ,QACGK,MAAM,CAACF,CAAAA,QAAS,CAACA,MAAMG,IAAI,IAAI,CAACH,MAAMI,WAAW,EACjDC,IAAI,CACH,CAACC,GAAGC,IACFD,EAAEE,SAAS,CAACC,aAAa,CAACF,EAAEC,SAAS,KAAKF,EAAEI,OAAO,GAAGH,EAAEG,OAAO;IAGvE,MAAMC,SAAiB;QACrBC,SAASC,CAAAA,QACPlB,OAAOmB,IAAI,CAAC;gBACV,IAAIhB,KAAKe,MAAME,EAAE,MAAMC,WAAW,OAAO;gBACzCnB,QAAQoB,IAAI,CAAC;oBACXlB,SAASc,MAAME,EAAE;oBACjBG,WAAWL,MAAMK,SAAS;oBAC1BR,SAASG,MAAMH,OAAO;oBACtBG;oBACAV,MAAM;oBACNgB,UAAU;oBACVf,aAAa;oBACbI,WAAWK,MAAMO,EAAE;gBACrB;gBACA,OAAO;YACT;QACFC,SAASC,CAAAA,QAAS3B,OAAOmB,IAAI,CAAC,IAAMb,cAAcsB,KAAK,CAAC,GAAGD;QAC3DE,UAAUxB,CAAAA,QACRL,OAAOmB,IAAI,CAAC;gBACV,MAAMW,SAAS3B,KAAKE,MAAMD,OAAO;gBACjC,IAAI0B,WAAWT,WAAWS,OAAOtB,IAAI,GAAG;YAC1C;QACFuB,eAAe,CAAC1B,OAAO2B,OAAOC,aAC5BjC,OAAOmB,IAAI,CAAC;gBACV,MAAMW,SAAS3B,KAAKE,MAAMD,OAAO;gBACjC,IAAI0B,WAAWT,WAAW;gBAC1BS,OAAON,QAAQ,IAAI;gBACnBM,OAAOI,SAAS,GAAGF;gBACnBF,OAAOrB,WAAW,GAAGwB;YACvB;QACFE,MAAM,CAAC9B,OAAO+B,SACZpC,OAAOmB,IAAI,CAAC;gBACV,MAAMW,SAAS3B,KAAKE,MAAMD,OAAO;gBACjC,IAAI0B,WAAWT,WAAWS,OAAOI,SAAS,GAAGE;YAC/C;QACFC,OAAO,IACLrC,OAAOmB,IAAI,CAAC;gBACV,MAAMO,UAAUpB;gBAChB,MAAMgC,SAASZ,OAAO,CAAC,EAAE;gBACzB,OAAO;oBACLA,SAASA,QAAQa,MAAM;oBACvB9B,aAAaP,QAAQK,MAAM,CAACF,CAAAA,QAASA,MAAMI,WAAW,EAAE8B,MAAM;mBAC1DD,WAAWjB,YACX,CAAC,IACD;oBAAEmB,iBAAiBF,OAAOzB,SAAS;gBAAC;YAE5C;IACJ;IAEA,MAAM4B,QAAQ,CAACC,KAAeC,cAC5B5C,YAAYiB,QAAQ0B,KAAK;YAAEC;YAAaC,UAAU;QAAY,GAAGC,IAAI,CACnE7C,OAAO8C,KAAK;IAGhB,OAAO,aAAK9B;QAAQd;QAASuC;;AAC/B,EAAE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@entifix/testing-unit",
|
|
3
|
-
"version": "0.23.
|
|
3
|
+
"version": "0.23.13",
|
|
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/business": "0.23.
|
|
76
|
-
"@entifix/core": "0.23.
|
|
77
|
-
"@entifix/transactions": "0.23.
|
|
75
|
+
"@entifix/business": "0.23.13",
|
|
76
|
+
"@entifix/core": "0.23.13",
|
|
77
|
+
"@entifix/transactions": "0.23.13"
|
|
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.23.
|
|
85
|
+
"@entifix/react-controls": "0.23.13"
|
|
86
86
|
},
|
|
87
87
|
"peerDependenciesMeta": {
|
|
88
88
|
"@entifix/react-controls": {
|