@entifix/testing-unit 0.23.12 → 0.23.14
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/entity-repository.contract.d.ts.map +1 -1
- package/dist/contracts/entity-repository.contract.js +68 -2
- package/dist/contracts/entity-repository.contract.js.map +1 -1
- 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/entity-repository.d.ts.map +1 -1
- package/dist/doubles/entity-repository.js +2 -1
- package/dist/doubles/entity-repository.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/dist/drivers/fake-mongo.d.ts.map +1 -1
- package/dist/drivers/fake-mongo.js +43 -6
- package/dist/drivers/fake-mongo.js.map +1 -1
- package/package.json +5 -5
|
@@ -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,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;;;;;;;;;;CAUC,GACD,OAAO,MAAMY,6BAA6B,CACxCV,MACAW;IAIA;;;GAGC,GACD,MAAMC,UAAU,CACdC,SACAC,YACAC,QACAC,QAEA1B,OAAO2B,UAAU,CACf3B,OAAO4B,MAAM,CACX5B,OAAO6B,GAAG,CAAC;YACT,MAAMC,OAAO,OAAOT,KAAKE;YACzB,MAAMQ,UAAU,OAAO/B,OAAOgC,SAAS,CACrC9B,OAAO+B,UAAU,CAAC/B,OAAOgC,IAAI,CAACJ,KAAKK,IAAI,CAACX,aAAaE;YAEvD,6DAA6D;YAC7D,OAAO1B,OAAOoC,KAAK,CAAC;YACpB,OAAOpC,OAAOqC,OAAO,CAACZ,QAAQK,KAAKQ,OAAO,EAAE;gBAAEC,SAAS;YAAK;YAC5D,OAAOC,MAAMC,IAAI,CAAC,CAAA,OAAOxC,MAAMyC,IAAI,CAACX,QAAO;QAC7C;IAIN,MAAMY,MAAM,CAACC,WACXA,SAASC,GAAG,CAACC,CAAAA,IAAMA,EAAEC,IAAI,KAAK,UAAUD,EAAExC,KAAK,CAACC,EAAE,GAAG,CAAC,OAAO,EAAEuC,E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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;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BAAW;YAAC,GACtC;gBAACjB,MAAM,MAAM,YAAYU,IAAI;gBAAOV,MAAM,MAAM;aAAY,EAC5D;YAEFF,OAAOsD,IAAIG,MAAMG,OAAO,CAAC;gBAAC;aAAK;QACjC;QAEA3D,GAAG,iEAAiE;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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entity-repository.d.ts","sourceRoot":"","sources":["../../src/doubles/entity-repository.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAEhB,iBAAiB,EAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAML,KAAK,MAAM,EAcZ,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,
|
|
1
|
+
{"version":3,"file":"entity-repository.d.ts","sourceRoot":"","sources":["../../src/doubles/entity-repository.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAEhB,iBAAiB,EAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAML,KAAK,MAAM,EAcZ,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,wBA+LF,CAAC"}
|
|
@@ -43,7 +43,8 @@ import { Effect } from 'effect';
|
|
|
43
43
|
};
|
|
44
44
|
const load = (request)=>guard(()=>{
|
|
45
45
|
var _request_page, _request_pageSize;
|
|
46
|
-
const matched = applySorting(applyFiltering(items, request.filtering), request.sorting
|
|
46
|
+
const matched = applySorting(applyFiltering(items, request.filtering), request.sorting, // Relevance scores against the words the filtering asks for.
|
|
47
|
+
request.filtering);
|
|
47
48
|
const page = (_request_page = request.page) != null ? _request_page : 1;
|
|
48
49
|
const pageSize = (_request_pageSize = request.pageSize) != null ? _request_pageSize : 10;
|
|
49
50
|
const start = (page - 1) * pageSize;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/doubles/entity-repository.ts"],"sourcesContent":["import type {\n EntityRepository,\n EntityWriteOptions,\n RepositoryFailure,\n} from '@entifix/business';\nimport {\n applyFiltering,\n applySorting,\n declaresRevision,\n deserializeSingleEntity,\n type EntifixFailure,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLoadRequest,\n type EntityPage,\n extractMetaAccessors,\n extractMetaEntity,\n isUseCaseAvailable,\n NotFound,\n readRevision,\n serializeEntity,\n StaleRevision,\n UnavailableInState,\n type UseCaseAvailability,\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, EntifixFailure> => {\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, EntifixFailure>;\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 /**\n * The revision rule (ADR 0032): a create never overwrites, an update names\n * the revision it read, and a mismatch writes nothing. The decision and the\n * write share one synchronous step, so two saves cannot both pass at one\n * revision — the property the adapters get from one conditional statement.\n */\n const saveRevised = <TEntity extends Entity>(entity: TEntity) => {\n const key = extractMetaEntity(\n entity.constructor as EntityConstructor<TEntity>,\n ).key;\n entity.id = entity.id ?? globalThis.crypto.randomUUID();\n return copyOf(entity).pipe(\n Effect.flatMap(stored =>\n Effect.suspend(() => {\n const read = readRevision(entity);\n const index = items.findIndex(item => item.id === stored.id);\n if (read === undefined) {\n if (index !== -1) {\n return Effect.fail(new StaleRevision({ entity: key }));\n }\n } else {\n if (index === -1) return Effect.fail(new NotFound({ entity: key }));\n const current = readRevision(items[index]);\n if (current !== read) {\n return Effect.fail(new StaleRevision({ entity: key, current }));\n }\n }\n const next = (read ?? 0) + 1;\n (stored as { revision?: number }).revision = next;\n (entity as { revision?: number }).revision = next;\n if (index === -1) items.push(stored);\n else items[index] = stored;\n return copyOf(stored);\n }),\n ),\n );\n };\n\n /**\n * The state rule of a conditioned write: the stored record must hold one of\n * `expect`'s states. Checked in the same synchronous step as the write, so\n * nothing can move the record between the two.\n */\n const refusal = (\n stored: Entity,\n expect: UseCaseAvailability,\n ): UnavailableInState | undefined => {\n if (isUseCaseAvailable({ availableWhen: expect }, stored)) return undefined;\n const state = (stored as unknown as Record<string, unknown>)[expect.member];\n return new UnavailableInState({\n entity:\n extractMetaEntity(stored.constructor as EntityConstructor<Entity>)\n .key ?? stored.constructor.name,\n member: expect.member,\n ...(typeof state === 'string' ? { state } : {}),\n allowed: [...expect.in],\n });\n };\n\n const save = <TEntity extends Entity>(\n entity: TEntity,\n options?: EntityWriteOptions,\n ) =>\n guard(() => {\n const expect = options?.expect;\n if (expect !== undefined) {\n // A save with `expect` is an update: it never creates.\n const stored = items.find(\n item => entity.id !== undefined && item.id === entity.id,\n );\n if (stored === undefined) return Effect.fail(new NotFound({}));\n const refused = refusal(stored, expect);\n if (refused !== undefined) return Effect.fail(refused);\n }\n return declaresRevision(entity.constructor as EntityConstructor<TEntity>)\n ? saveRevised(entity)\n : storeCopy(entity);\n });\n\n const storeCopy = <TEntity extends Entity>(entity: TEntity) =>\n Effect.suspend(() => {\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>(\n entityOrId: EntityId | TEntity,\n options?: EntityWriteOptions,\n ) =>\n guard(() => {\n const id =\n entityOrId != null && typeof entityOrId === 'object'\n ? entityOrId.id\n : entityOrId;\n const stored = items.find(item => item.id === id);\n const refused =\n stored === undefined || options?.expect === undefined\n ? undefined\n : refusal(stored, options.expect);\n if (refused !== undefined) return Effect.fail(refused);\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","declaresRevision","deserializeSingleEntity","extractMetaAccessors","extractMetaEntity","isUseCaseAvailable","NotFound","readRevision","serializeEntity","StaleRevision","UnavailableInState","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","saveRevised","key","globalThis","crypto","randomUUID","flatMap","stored","suspend","read","index","findIndex","current","next","revision","push","refusal","expect","availableWhen","state","member","name","allowed","in","save","options","ref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AU,CAACC;YACT3D,iBAAiB2D;QACnB;IAGF;AACF,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../src/doubles/entity-repository.ts"],"sourcesContent":["import type {\n EntityRepository,\n EntityWriteOptions,\n RepositoryFailure,\n} from '@entifix/business';\nimport {\n applyFiltering,\n applySorting,\n declaresRevision,\n deserializeSingleEntity,\n type EntifixFailure,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLoadRequest,\n type EntityPage,\n extractMetaAccessors,\n extractMetaEntity,\n isUseCaseAvailable,\n NotFound,\n readRevision,\n serializeEntity,\n StaleRevision,\n UnavailableInState,\n type UseCaseAvailability,\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, EntifixFailure> => {\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, EntifixFailure>;\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 // Relevance scores against the words the filtering asks for.\n request.filtering,\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 /**\n * The revision rule (ADR 0032): a create never overwrites, an update names\n * the revision it read, and a mismatch writes nothing. The decision and the\n * write share one synchronous step, so two saves cannot both pass at one\n * revision — the property the adapters get from one conditional statement.\n */\n const saveRevised = <TEntity extends Entity>(entity: TEntity) => {\n const key = extractMetaEntity(\n entity.constructor as EntityConstructor<TEntity>,\n ).key;\n entity.id = entity.id ?? globalThis.crypto.randomUUID();\n return copyOf(entity).pipe(\n Effect.flatMap(stored =>\n Effect.suspend(() => {\n const read = readRevision(entity);\n const index = items.findIndex(item => item.id === stored.id);\n if (read === undefined) {\n if (index !== -1) {\n return Effect.fail(new StaleRevision({ entity: key }));\n }\n } else {\n if (index === -1) return Effect.fail(new NotFound({ entity: key }));\n const current = readRevision(items[index]);\n if (current !== read) {\n return Effect.fail(new StaleRevision({ entity: key, current }));\n }\n }\n const next = (read ?? 0) + 1;\n (stored as { revision?: number }).revision = next;\n (entity as { revision?: number }).revision = next;\n if (index === -1) items.push(stored);\n else items[index] = stored;\n return copyOf(stored);\n }),\n ),\n );\n };\n\n /**\n * The state rule of a conditioned write: the stored record must hold one of\n * `expect`'s states. Checked in the same synchronous step as the write, so\n * nothing can move the record between the two.\n */\n const refusal = (\n stored: Entity,\n expect: UseCaseAvailability,\n ): UnavailableInState | undefined => {\n if (isUseCaseAvailable({ availableWhen: expect }, stored)) return undefined;\n const state = (stored as unknown as Record<string, unknown>)[expect.member];\n return new UnavailableInState({\n entity:\n extractMetaEntity(stored.constructor as EntityConstructor<Entity>)\n .key ?? stored.constructor.name,\n member: expect.member,\n ...(typeof state === 'string' ? { state } : {}),\n allowed: [...expect.in],\n });\n };\n\n const save = <TEntity extends Entity>(\n entity: TEntity,\n options?: EntityWriteOptions,\n ) =>\n guard(() => {\n const expect = options?.expect;\n if (expect !== undefined) {\n // A save with `expect` is an update: it never creates.\n const stored = items.find(\n item => entity.id !== undefined && item.id === entity.id,\n );\n if (stored === undefined) return Effect.fail(new NotFound({}));\n const refused = refusal(stored, expect);\n if (refused !== undefined) return Effect.fail(refused);\n }\n return declaresRevision(entity.constructor as EntityConstructor<TEntity>)\n ? saveRevised(entity)\n : storeCopy(entity);\n });\n\n const storeCopy = <TEntity extends Entity>(entity: TEntity) =>\n Effect.suspend(() => {\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>(\n entityOrId: EntityId | TEntity,\n options?: EntityWriteOptions,\n ) =>\n guard(() => {\n const id =\n entityOrId != null && typeof entityOrId === 'object'\n ? entityOrId.id\n : entityOrId;\n const stored = items.find(item => item.id === id);\n const refused =\n stored === undefined || options?.expect === undefined\n ? undefined\n : refusal(stored, options.expect);\n if (refused !== undefined) return Effect.fail(refused);\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","declaresRevision","deserializeSingleEntity","extractMetaAccessors","extractMetaEntity","isUseCaseAvailable","NotFound","readRevision","serializeEntity","StaleRevision","UnavailableInState","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","saveRevised","key","globalThis","crypto","randomUUID","flatMap","stored","suspend","read","index","findIndex","current","next","revision","push","refusal","expect","availableWhen","state","member","name","allowed","in","save","options","refused","storeCopy","tap","sync","remove","entityOrId","filter","delete","failNext","error"],"mappings":";AAKA,SACEA,cAAc,EACdC,YAAY,EACZC,gBAAgB,EAChBC,uBAAuB,E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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,M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QAASuC;;AAC/B,EAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fake-mongo.d.ts","sourceRoot":"","sources":["../../src/drivers/fake-mongo.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,KAAK,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"fake-mongo.d.ts","sourceRoot":"","sources":["../../src/drivers/fake-mongo.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,KAAK,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AA4VxC,MAAM,WAAW,mBAAmB;IAClC,uEAAuE;IACvE,QAAQ,CAAC,SAAS,EAAE,QAAQ,EAAE,CAAC;CAChC;AAED,MAAM,WAAW,WAAW;IAC1B,wCAAwC;IACxC,IAAI,CAAC,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;IACtD,6CAA6C;IAC7C,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,QAAQ,EAAE,CAAC;IACrC;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IAC/B;;;OAGG;IACH,MAAM,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IAChD;;;OAGG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IAClD,4EAA4E;IAC5E,QAAQ,CAAC,UAAU,EAAE,aAAa,CAAC;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACvE;;;;OAIG;IACH,YAAY,IAAI;QACd,eAAe,CAAC,IAAI,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;QAChE;;;;;WAKG;QACH,gBAAgB,IAAI,IAAI,CAAC;QACzB,iBAAiB,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;QACnC,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;QAClC,aAAa,IAAI,OAAO,CAAC;QACzB,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;QAC5B,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;KAC5B,CAAC;IACF,2EAA2E;IAC3E,QAAQ,CAAC,EAAE,EAAE,OAAO,CAAC;CACtB;AAED;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,GAC1B,OAAM,MAAM,CAAC,MAAM,EAAE,QAAQ,EAAE,CAAM,KACpC,WA8lBF,CAAC"}
|
|
@@ -85,12 +85,21 @@ const compare = (left, right)=>{
|
|
|
85
85
|
throw new TypeError(`fake mongo: $expr node must have exactly one operator, got ${entries.length}`);
|
|
86
86
|
}
|
|
87
87
|
const [operator, operand] = entries[0];
|
|
88
|
+
// A relevance score (ADR 0033): a regex test on a field, as `$regexMatch`
|
|
89
|
+
// takes it — an object, not a list of operands.
|
|
90
|
+
if (operator === '$regexMatch') {
|
|
91
|
+
const { input, regex, options } = operand;
|
|
92
|
+
const value = evaluateExpression(doc, input);
|
|
93
|
+
return typeof value === 'string' && new RegExp(regex, options != null ? options : '').test(value);
|
|
94
|
+
}
|
|
88
95
|
const operands = operand.map((child)=>evaluateExpression(doc, child));
|
|
89
96
|
switch(operator){
|
|
90
97
|
case '$subtract':
|
|
91
98
|
return operands[0] - operands[1];
|
|
92
99
|
case '$add':
|
|
93
|
-
return operands
|
|
100
|
+
return operands.reduce((sum, value)=>sum + value, 0);
|
|
101
|
+
case '$cond':
|
|
102
|
+
return operands[0] === true ? operands[1] : operands[2];
|
|
94
103
|
case '$gte':
|
|
95
104
|
return compare(operands[0], operands[1]) >= 0;
|
|
96
105
|
case '$gt':
|
|
@@ -219,6 +228,14 @@ const matches = (doc, query)=>Object.entries(query).every(([field, condition])=>
|
|
|
219
228
|
[counted]: count
|
|
220
229
|
}));
|
|
221
230
|
};
|
|
231
|
+
/**
|
|
232
|
+
* Documents in a `{ field: 1 | -1 }` order, the first key deciding, as the
|
|
233
|
+
* server sorts a `find` and a `$sort` stage alike.
|
|
234
|
+
*/ const sortDocuments = (docs, sortSpec)=>Object.entries(sortSpec).reduceRight((items, [field, direction])=>[
|
|
235
|
+
...items
|
|
236
|
+
].sort((left, right)=>// A dotted field sorts by the value it names, as the server does —
|
|
237
|
+
// one locale of a localized member, say.
|
|
238
|
+
compare(valuesAt(left, field)[0], valuesAt(right, field)[0]) * direction), docs);
|
|
222
239
|
const runPipeline = (docs, pipeline)=>pipeline.reduce((current, stage)=>{
|
|
223
240
|
const entries = Object.entries(stage);
|
|
224
241
|
if (entries.length !== 1) {
|
|
@@ -232,6 +249,30 @@ const runPipeline = (docs, pipeline)=>pipeline.reduce((current, stage)=>{
|
|
|
232
249
|
return unwind(current, spec);
|
|
233
250
|
case '$group':
|
|
234
251
|
return group(current, spec);
|
|
252
|
+
// The stages a relevance load sends (ADR 0033): a computed field, the
|
|
253
|
+
// order by it, the page, and the field dropped again.
|
|
254
|
+
case '$addFields':
|
|
255
|
+
return current.map((doc)=>_extends({}, doc, Object.fromEntries(Object.entries(spec).map(([field, expression])=>[
|
|
256
|
+
field,
|
|
257
|
+
evaluateExpression(doc, expression)
|
|
258
|
+
]))));
|
|
259
|
+
case '$sort':
|
|
260
|
+
return sortDocuments(current, spec);
|
|
261
|
+
case '$skip':
|
|
262
|
+
return current.slice(spec);
|
|
263
|
+
case '$limit':
|
|
264
|
+
return current.slice(0, spec);
|
|
265
|
+
case '$project':
|
|
266
|
+
return current.map((doc)=>{
|
|
267
|
+
const kept = _extends({}, doc);
|
|
268
|
+
for (const [field, include] of Object.entries(spec)){
|
|
269
|
+
if (include !== 0) {
|
|
270
|
+
throw new TypeError('fake mongo: $project supports exclusion only');
|
|
271
|
+
}
|
|
272
|
+
delete kept[field];
|
|
273
|
+
}
|
|
274
|
+
return kept;
|
|
275
|
+
});
|
|
235
276
|
case '$facet':
|
|
236
277
|
return [
|
|
237
278
|
Object.fromEntries(Object.entries(spec).map(([output, branch])=>[
|
|
@@ -363,11 +404,7 @@ const runPipeline = (docs, pipeline)=>pipeline.reduce((current, stage)=>{
|
|
|
363
404
|
},
|
|
364
405
|
toArray: ()=>record(name, 'find', ()=>{
|
|
365
406
|
const matched = documentsOf(name).filter((doc)=>matches(doc, query));
|
|
366
|
-
const sorted =
|
|
367
|
-
...items
|
|
368
|
-
].sort((left, right)=>// A dotted field sorts by the value it names, as the
|
|
369
|
-
// server does — one locale of a localized member, say.
|
|
370
|
-
compare(valuesAt(left, field)[0], valuesAt(right, field)[0]) * direction), matched);
|
|
407
|
+
const sorted = sortDocuments(matched, sortSpec);
|
|
371
408
|
return sorted.slice(skipCount, skipCount + limitCount).map((doc)=>project(doc, options));
|
|
372
409
|
})
|
|
373
410
|
};
|