@entifix/mongo 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"make-mongo-link-resolver.d.ts","sourceRoot":"","sources":["../../src/adapters/make-mongo-link-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EACL,MAAM,EACN,iBAAiB,EAIlB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAU,MAAM,QAAQ,CAAC;AACzC,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAIlC;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,EAAE,EAAE,EAAE,EACN,aAAa,EAAE,aAAa,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC,GACtD,OAAO,CAAC,OAAO,CAAC,qBAAqB,CAAC,CA2BxC"}
1
+ {"version":3,"file":"make-mongo-link-resolver.d.ts","sourceRoot":"","sources":["../../src/adapters/make-mongo-link-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAEL,MAAM,EACN,iBAAiB,EAGlB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAU,MAAM,QAAQ,CAAC;AACzC,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAIlC;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,EAAE,EAAE,EAAE,EACN,aAAa,EAAE,aAAa,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC,GACtD,OAAO,CAAC,OAAO,CAAC,qBAAqB,CAAC,CA2BxC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/adapters/make-mongo-link-resolver.ts"],"sourcesContent":["import { EntityLinkResolverTag } from '@entifix/business';\nimport {\n Entity,\n EntityConstructor,\n EntityLinkResolver,\n Internal,\n type TransitionalFailure,\n} from '@entifix/core';\nimport { Context, Effect } from 'effect';\nimport type { Db } from 'mongodb';\n\nimport { makeMongoRepository } from './make-mongo-repository.js';\n\n/**\n * Builds an {@link EntityLinkResolverTag} context backed by Mongo repositories,\n * so a load use-case can materialize not-yet-loaded {@link EntityLink}s on the\n * backend. Mirrors the REST `createEntityLinkResolver`, but each Mongo `get`\n * already has no outstanding requirements, so nothing needs to be provided.\n *\n * `registrations` lists the link-target constructors this resolver can fetch.\n */\nexport function makeMongoLinkResolver(\n db: Db,\n registrations: ReadonlyArray<EntityConstructor<Entity>>,\n): Context.Context<EntityLinkResolverTag> {\n const repositoryByConstructor = new Map(\n registrations.map(\n entityConstructor =>\n [\n entityConstructor,\n makeMongoRepository(db, entityConstructor),\n ] as const,\n ),\n );\n\n const resolver: EntityLinkResolver = {\n resolve(entityConstructor, id) {\n const repository = repositoryByConstructor.get(\n entityConstructor as EntityConstructor<Entity>,\n );\n if (!repository) {\n return Effect.fail(new Internal());\n }\n return repository.get(id) as unknown as Effect.Effect<\n never,\n TransitionalFailure\n >;\n },\n };\n\n return Context.make(EntityLinkResolverTag, resolver);\n}\n"],"names":["EntityLinkResolverTag","Internal","Context","Effect","makeMongoRepository","makeMongoLinkResolver","db","registrations","repositoryByConstructor","Map","map","entityConstructor","resolver","resolve","id","repository","get","fail","make"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAoB;AAC1D,SAIEC,QAAQ,QAEH,gBAAgB;AACvB,SAASC,OAAO,EAAEC,MAAM,QAAQ,SAAS;AAGzC,SAASC,mBAAmB,QAAQ,6BAA6B;AAEjE;;;;;;;CAOC,GACD,OAAO,SAASC,sBACdC,EAAM,EACNC,aAAuD;IAEvD,MAAMC,0BAA0B,IAAIC,IAClCF,cAAcG,GAAG,CACfC,CAAAA,oBACE;YACEA;YACAP,oBAAoBE,IAAIK;SACzB;IAIP,MAAMC,WAA+B;QACnCC,SAAQF,iBAAiB,EAAEG,EAAE;YAC3B,MAAMC,aAAaP,wBAAwBQ,GAAG,CAC5CL;YAEF,IAAI,CAACI,YAAY;gBACf,OAAOZ,OAAOc,IAAI,CAAC,IAAIhB;YACzB;YACA,OAAOc,WAAWC,GAAG,CAACF;QAIxB;IACF;IAEA,OAAOZ,QAAQgB,IAAI,CAAClB,uBAAuBY;AAC7C"}
1
+ {"version":3,"sources":["../../src/adapters/make-mongo-link-resolver.ts"],"sourcesContent":["import { EntityLinkResolverTag } from '@entifix/business';\nimport {\n type EntifixFailure,\n Entity,\n EntityConstructor,\n EntityLinkResolver,\n Internal,\n} from '@entifix/core';\nimport { Context, Effect } from 'effect';\nimport type { Db } from 'mongodb';\n\nimport { makeMongoRepository } from './make-mongo-repository.js';\n\n/**\n * Builds an {@link EntityLinkResolverTag} context backed by Mongo repositories,\n * so a load use-case can materialize not-yet-loaded {@link EntityLink}s on the\n * backend. Mirrors the REST `createEntityLinkResolver`, but each Mongo `get`\n * already has no outstanding requirements, so nothing needs to be provided.\n *\n * `registrations` lists the link-target constructors this resolver can fetch.\n */\nexport function makeMongoLinkResolver(\n db: Db,\n registrations: ReadonlyArray<EntityConstructor<Entity>>,\n): Context.Context<EntityLinkResolverTag> {\n const repositoryByConstructor = new Map(\n registrations.map(\n entityConstructor =>\n [\n entityConstructor,\n makeMongoRepository(db, entityConstructor),\n ] as const,\n ),\n );\n\n const resolver: EntityLinkResolver = {\n resolve(entityConstructor, id) {\n const repository = repositoryByConstructor.get(\n entityConstructor as EntityConstructor<Entity>,\n );\n if (!repository) {\n return Effect.fail(new Internal());\n }\n return repository.get(id) as unknown as Effect.Effect<\n never,\n EntifixFailure\n >;\n },\n };\n\n return Context.make(EntityLinkResolverTag, resolver);\n}\n"],"names":["EntityLinkResolverTag","Internal","Context","Effect","makeMongoRepository","makeMongoLinkResolver","db","registrations","repositoryByConstructor","Map","map","entityConstructor","resolver","resolve","id","repository","get","fail","make"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAoB;AAC1D,SAKEC,QAAQ,QACH,gBAAgB;AACvB,SAASC,OAAO,EAAEC,MAAM,QAAQ,SAAS;AAGzC,SAASC,mBAAmB,QAAQ,6BAA6B;AAEjE;;;;;;;CAOC,GACD,OAAO,SAASC,sBACdC,EAAM,EACNC,aAAuD;IAEvD,MAAMC,0BAA0B,IAAIC,IAClCF,cAAcG,GAAG,CACfC,CAAAA,oBACE;YACEA;YACAP,oBAAoBE,IAAIK;SACzB;IAIP,MAAMC,WAA+B;QACnCC,SAAQF,iBAAiB,EAAEG,EAAE;YAC3B,MAAMC,aAAaP,wBAAwBQ,GAAG,CAC5CL;YAEF,IAAI,CAACI,YAAY;gBACf,OAAOZ,OAAOc,IAAI,CAAC,IAAIhB;YACzB;YACA,OAAOc,WAAWC,GAAG,CAACF;QAIxB;IACF;IAEA,OAAOZ,QAAQgB,IAAI,CAAClB,uBAAuBY;AAC7C"}
@@ -13,7 +13,6 @@ export * from '../idempotency/store.js';
13
13
  export * from '../inbox/store.js';
14
14
  export * from '../outbox/relay.js';
15
15
  export * from '../outbox/store.js';
16
- export * from '../saga/store.js';
17
16
  export * from '../unit-of-work/command-inbox.js';
18
17
  export * from '../unit-of-work/mongo-unit-of-work.js';
19
18
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/transactions/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,cAAc,yBAAyB,CAAC;AACxC,cAAc,mBAAmB,CAAC;AAClC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,kCAAkC,CAAC;AACjD,cAAc,uCAAuC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/transactions/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,cAAc,yBAAyB,CAAC;AACxC,cAAc,mBAAmB,CAAC;AAClC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kCAAkC,CAAC;AACjD,cAAc,uCAAuC,CAAC"}
@@ -12,7 +12,6 @@
12
12
  export * from '../inbox/store.js';
13
13
  export * from '../outbox/relay.js';
14
14
  export * from '../outbox/store.js';
15
- export * from '../saga/store.js';
16
15
  export * from '../unit-of-work/command-inbox.js';
17
16
  export * from '../unit-of-work/mongo-unit-of-work.js';
18
17
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/transactions/index.ts"],"sourcesContent":["/**\n * The half of this package that needs `@entifix/transactions`: the\n * transactional outbox written inside the entity's own Mongo\n * transaction, and the inbox that makes a redelivered command idempotent.\n *\n * Behind a subpath so entity CRUD over Mongo does not arrive with the saga\n * engine attached. Package-level dependencies are not per-subpath, so what\n * actually keeps it optional is the `peerDependenciesMeta.optional` entry in\n * the manifest — importing this module without that peer installed is the\n * error, and it is the adopter's to make deliberately.\n */\nexport * from '../idempotency/store.js';\nexport * from '../inbox/store.js';\nexport * from '../outbox/relay.js';\nexport * from '../outbox/store.js';\nexport * from '../saga/store.js';\nexport * from '../unit-of-work/command-inbox.js';\nexport * from '../unit-of-work/mongo-unit-of-work.js';\n"],"names":[],"mappings":"AAAA;;;;;;;;;;CAUC,GACD,cAAc,0BAA0B;AACxC,cAAc,oBAAoB;AAClC,cAAc,qBAAqB;AACnC,cAAc,qBAAqB;AACnC,cAAc,mBAAmB;AACjC,cAAc,mCAAmC;AACjD,cAAc,wCAAwC"}
1
+ {"version":3,"sources":["../../src/transactions/index.ts"],"sourcesContent":["/**\n * The half of this package that needs `@entifix/transactions`: the\n * transactional outbox written inside the entity's own Mongo\n * transaction, and the inbox that makes a redelivered command idempotent.\n *\n * Behind a subpath so entity CRUD over Mongo does not arrive with the saga\n * engine attached. Package-level dependencies are not per-subpath, so what\n * actually keeps it optional is the `peerDependenciesMeta.optional` entry in\n * the manifest — importing this module without that peer installed is the\n * error, and it is the adopter's to make deliberately.\n */\nexport * from '../idempotency/store.js';\nexport * from '../inbox/store.js';\nexport * from '../outbox/relay.js';\nexport * from '../outbox/store.js';\nexport * from '../unit-of-work/command-inbox.js';\nexport * from '../unit-of-work/mongo-unit-of-work.js';\n"],"names":[],"mappings":"AAAA;;;;;;;;;;CAUC,GACD,cAAc,0BAA0B;AACxC,cAAc,oBAAoB;AAClC,cAAc,qBAAqB;AACnC,cAAc,qBAAqB;AACnC,cAAc,mCAAmC;AACjD,cAAc,wCAAwC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/mongo",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "MongoDB adapter: an entity repository, RSQL-to-Mongo query translation, per-tenant databases, and an optional transactional outbox.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -57,17 +57,17 @@
57
57
  "dependencies": {
58
58
  "@swc/helpers": "0.5.23",
59
59
  "mongodb": "7.8.0",
60
- "@entifix/business": "0.13.0",
61
- "@entifix/core": "0.13.0"
60
+ "@entifix/business": "0.15.0",
61
+ "@entifix/core": "0.15.0"
62
62
  },
63
63
  "devDependencies": {
64
- "effect": "4.0.6",
65
- "@entifix/transactions": "0.13.0",
66
- "@entifix/testing-unit": "0.13.0"
64
+ "effect": "4.0.7",
65
+ "@entifix/testing-unit": "0.15.0",
66
+ "@entifix/transactions": "0.15.0"
67
67
  },
68
68
  "peerDependencies": {
69
- "effect": "^4.0.6",
70
- "@entifix/transactions": "0.13.0"
69
+ "effect": "^4.0.7",
70
+ "@entifix/transactions": "0.15.0"
71
71
  },
72
72
  "peerDependenciesMeta": {
73
73
  "@entifix/transactions": {
@@ -1,35 +0,0 @@
1
- import { type SagaStore, SagaStoreTag } from '@entifix/transactions';
2
- import { Effect, Layer } from 'effect';
3
- import type { Db } from 'mongodb';
4
- import { MongoClientTag, MongoDatabaseTag } from '../mongo-database/mongo-database.js';
5
- /**
6
- * Saga instances: one document per flow, the durable record a coordinator
7
- * resumes from, so where to resume is derived from the outcomes rather than
8
- * stored beside them.
9
- */
10
- export declare const SAGA_COLLECTION = "saga_instances";
11
- /**
12
- * A unique index on `sagaId`, so a resumed coordinator can never create a
13
- * second instance for one flow, and `{ state, updatedAt }` for the sweep —
14
- * without it every pass is a scan of every saga ever run, on a schedule.
15
- */
16
- export declare const ensureSagaIndexes: (db: Db) => Effect.Effect<void, import("@entifix/core").StoreFailure, never>;
17
- /** {@link SagaStore} over one Mongo database. */
18
- export declare const makeMongoSagaStore: (db: Db) => SagaStore;
19
- /**
20
- * Provides {@link SagaStoreTag} from the service's own database, creating the
21
- * indexes first.
22
- */
23
- export declare const MongoSagaStoreLayer: Layer.Layer<SagaStoreTag, import("@entifix/core").StoreFailure, MongoDatabaseTag>;
24
- /**
25
- * Provides {@link SagaStoreTag} from a database the host **names**, resolved on
26
- * the shared client — for a process whose saga store is one of several stores
27
- * it holds, rather than the one database {@link MongoDatabaseTag} carries.
28
- *
29
- * Same pool, same indexes, same store; only where the handle comes from
30
- * differs.
31
- */
32
- export declare const mongoSagaStoreLayer: (options: {
33
- readonly database: string;
34
- }) => Layer.Layer<SagaStoreTag, import("@entifix/core").StoreFailure, MongoClientTag>;
35
- //# sourceMappingURL=store.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/saga/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,SAAS,EACd,YAAY,EACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAGlC,OAAO,EACL,cAAc,EACd,gBAAgB,EACjB,MAAM,qCAAqC,CAAC;AAE7C;;;;GAIG;AACH,eAAO,MAAM,eAAe,mBAAmB,CAAC;AAUhD;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,GAAI,IAAI,EAAE,qEAOpC,CAAC;AAEL,iDAAiD;AACjD,eAAO,MAAM,kBAAkB,GAAI,IAAI,EAAE,KAAG,SAoI3C,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,mBAAmB,mFAO/B,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,mBAAmB,GAAI,SAAS;IAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,oFASvE,CAAC"}
@@ -1,219 +0,0 @@
1
- import { _ as _extends } from "@swc/helpers/_/_extends";
2
- import { SagaStoreTag } from '@entifix/transactions';
3
- import { Effect, Layer } from 'effect';
4
- import { translateMongoError } from '../errors/translate-mongo-error.js';
5
- import { MongoClientTag, MongoDatabaseTag } from '../mongo-database/mongo-database.js';
6
- /**
7
- * Saga instances: one document per flow, the durable record a coordinator
8
- * resumes from, so where to resume is derived from the outcomes rather than
9
- * stored beside them.
10
- */ export const SAGA_COLLECTION = 'saga_instances';
11
- /** The two states a sweep treats as unfinished. */ const UNFINISHED = [
12
- 'RUNNING',
13
- 'COMPENSATING'
14
- ];
15
- const sagaCollection = (db)=>db.collection(SAGA_COLLECTION);
16
- const deadline = (olderThanMs)=>new Date(Date.now() - olderThanMs).toISOString();
17
- /**
18
- * A unique index on `sagaId`, so a resumed coordinator can never create a
19
- * second instance for one flow, and `{ state, updatedAt }` for the sweep —
20
- * without it every pass is a scan of every saga ever run, on a schedule.
21
- */ export const ensureSagaIndexes = (db)=>Effect.tryPromise({
22
- try: async ()=>{
23
- await sagaCollection(db).createIndex({
24
- sagaId: 1
25
- }, {
26
- unique: true
27
- });
28
- await sagaCollection(db).createIndex({
29
- state: 1,
30
- updatedAt: 1
31
- });
32
- },
33
- catch: (error)=>translateMongoError(error)
34
- });
35
- /** {@link SagaStore} over one Mongo database. */ export const makeMongoSagaStore = (db)=>{
36
- const collection = sagaCollection(db);
37
- const stamp = ()=>new Date().toISOString();
38
- return {
39
- start: (instance)=>Effect.tryPromise({
40
- try: async ()=>{
41
- // `$setOnInsert` with an upsert rather than `insertOne`: a coordinator
42
- // restarted mid-flight re-enters with an id it already wrote, and
43
- // refusing that would turn a recoverable resume into a hard failure.
44
- await collection.updateOne({
45
- sagaId: instance.sagaId
46
- }, {
47
- $setOnInsert: _extends({}, instance, {
48
- updatedAt: stamp()
49
- })
50
- }, {
51
- upsert: true
52
- });
53
- },
54
- catch: (error)=>translateMongoError(error)
55
- }),
56
- beginStep: (sagaId, stepIndex)=>Effect.tryPromise({
57
- try: async ()=>{
58
- await collection.updateOne({
59
- sagaId
60
- }, {
61
- $set: {
62
- stepIndex,
63
- updatedAt: stamp()
64
- }
65
- });
66
- },
67
- catch: (error)=>translateMongoError(error)
68
- }),
69
- recordOutcome: (sagaId, outcome)=>Effect.tryPromise({
70
- try: async ()=>{
71
- await collection.updateOne({
72
- sagaId
73
- }, // `$push`, never a read-modify-write of the array: two outcomes
74
- // recorded from one process would otherwise lose one another, and a
75
- // lost outcome is a compensation that cannot address what it undoes.
76
- {
77
- $push: {
78
- outcomes: outcome
79
- },
80
- $set: {
81
- updatedAt: stamp()
82
- }
83
- });
84
- },
85
- catch: (error)=>translateMongoError(error)
86
- }),
87
- settle: (sagaId, state, error)=>Effect.tryPromise({
88
- try: async ()=>{
89
- await collection.updateOne({
90
- sagaId
91
- }, {
92
- $set: {
93
- state,
94
- error,
95
- updatedAt: stamp()
96
- }
97
- });
98
- },
99
- catch: (error)=>translateMongoError(error)
100
- }),
101
- /**
102
- * Take ownership of a stale instance, or answer `undefined`.
103
- *
104
- * ⚠️ **One conditional write, not a read and then a write.** The filter
105
- * repeats `findStale`'s predicate, so two sweepers racing the same instance
106
- * produce one winner: the loser's filter no longer matches because the
107
- * winner re-stamped `updatedAt`. That stamp is also what stops the next tick
108
- * finding the instance this sweep is still working on.
109
- */ claimForResume: (sagaId, olderThanMs)=>Effect.tryPromise({
110
- try: async ()=>{
111
- const claimed = await collection.findOneAndUpdate({
112
- sagaId,
113
- state: {
114
- $in: [
115
- ...UNFINISHED
116
- ]
117
- },
118
- updatedAt: {
119
- $lt: deadline(olderThanMs)
120
- }
121
- }, {
122
- $inc: {
123
- resumeAttempts: 1
124
- },
125
- $set: {
126
- updatedAt: stamp()
127
- }
128
- }, {
129
- returnDocument: 'after',
130
- projection: {
131
- _id: 0
132
- }
133
- });
134
- return claimed != null ? claimed : undefined;
135
- },
136
- catch: (error)=>translateMongoError(error)
137
- }),
138
- /**
139
- * Flag one step's calls as given back, addressing the outcome by its step
140
- * id: outcomes are `$push`ed, so an index is a fact about arrival order and
141
- * a resumed walk must not depend on one.
142
- */ markCompensated: (sagaId, stepId)=>Effect.tryPromise({
143
- try: async ()=>{
144
- await collection.updateOne({
145
- sagaId
146
- }, {
147
- $set: {
148
- 'outcomes.$[entry].compensated': true,
149
- updatedAt: stamp()
150
- }
151
- }, {
152
- arrayFilters: [
153
- {
154
- 'entry.stepId': stepId
155
- }
156
- ]
157
- });
158
- },
159
- catch: (error)=>translateMongoError(error)
160
- }),
161
- get: (sagaId)=>Effect.tryPromise({
162
- try: async ()=>{
163
- var _ref;
164
- return (_ref = await collection.findOne({
165
- sagaId
166
- }, {
167
- projection: {
168
- _id: 0
169
- }
170
- })) != null ? _ref : undefined;
171
- },
172
- catch: (error)=>translateMongoError(error)
173
- }),
174
- /**
175
- * Instances stuck mid-flight past a deadline. ⚠️ `COMPENSATING` counts: a
176
- * coordinator that died while unwinding is the state that leaves holds in
177
- * place, and the one an operator most needs to find.
178
- */ findStale: (olderThanMs)=>Effect.tryPromise({
179
- try: async ()=>await collection.find({
180
- state: {
181
- $in: [
182
- ...UNFINISHED
183
- ]
184
- },
185
- updatedAt: {
186
- $lt: deadline(olderThanMs)
187
- }
188
- }, {
189
- projection: {
190
- _id: 0
191
- }
192
- }).toArray(),
193
- catch: (error)=>translateMongoError(error)
194
- })
195
- };
196
- };
197
- /**
198
- * Provides {@link SagaStoreTag} from the service's own database, creating the
199
- * indexes first.
200
- */ export const MongoSagaStoreLayer = Layer.effect(SagaStoreTag, Effect.gen(function*() {
201
- const db = yield* MongoDatabaseTag;
202
- yield* ensureSagaIndexes(db);
203
- return makeMongoSagaStore(db);
204
- }));
205
- /**
206
- * Provides {@link SagaStoreTag} from a database the host **names**, resolved on
207
- * the shared client — for a process whose saga store is one of several stores
208
- * it holds, rather than the one database {@link MongoDatabaseTag} carries.
209
- *
210
- * Same pool, same indexes, same store; only where the handle comes from
211
- * differs.
212
- */ export const mongoSagaStoreLayer = (options)=>Layer.effect(SagaStoreTag, Effect.gen(function*() {
213
- const client = yield* MongoClientTag;
214
- const db = client.db(options.database);
215
- yield* ensureSagaIndexes(db);
216
- return makeMongoSagaStore(db);
217
- }));
218
-
219
- //# sourceMappingURL=store.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/saga/store.ts"],"sourcesContent":["import {\n type SagaInstance,\n type SagaState,\n type SagaStepOutcome,\n type SagaStore,\n SagaStoreTag,\n} from '@entifix/transactions';\nimport { Effect, Layer } from 'effect';\nimport type { Db } from 'mongodb';\n\nimport { translateMongoError } from '../errors/translate-mongo-error.js';\nimport {\n MongoClientTag,\n MongoDatabaseTag,\n} from '../mongo-database/mongo-database.js';\n\n/**\n * Saga instances: one document per flow, the durable record a coordinator\n * resumes from, so where to resume is derived from the outcomes rather than\n * stored beside them.\n */\nexport const SAGA_COLLECTION = 'saga_instances';\n\n/** The two states a sweep treats as unfinished. */\nconst UNFINISHED: readonly SagaState[] = ['RUNNING', 'COMPENSATING'];\n\nconst sagaCollection = (db: Db) => db.collection<SagaInstance>(SAGA_COLLECTION);\n\nconst deadline = (olderThanMs: number) =>\n new Date(Date.now() - olderThanMs).toISOString();\n\n/**\n * A unique index on `sagaId`, so a resumed coordinator can never create a\n * second instance for one flow, and `{ state, updatedAt }` for the sweep —\n * without it every pass is a scan of every saga ever run, on a schedule.\n */\nexport const ensureSagaIndexes = (db: Db) =>\n Effect.tryPromise({\n try: async () => {\n await sagaCollection(db).createIndex({ sagaId: 1 }, { unique: true });\n await sagaCollection(db).createIndex({ state: 1, updatedAt: 1 });\n },\n catch: error => translateMongoError(error),\n });\n\n/** {@link SagaStore} over one Mongo database. */\nexport const makeMongoSagaStore = (db: Db): SagaStore => {\n const collection = sagaCollection(db);\n const stamp = () => new Date().toISOString();\n\n return {\n start: instance =>\n Effect.tryPromise({\n try: async () => {\n // `$setOnInsert` with an upsert rather than `insertOne`: a coordinator\n // restarted mid-flight re-enters with an id it already wrote, and\n // refusing that would turn a recoverable resume into a hard failure.\n await collection.updateOne(\n { sagaId: instance.sagaId },\n { $setOnInsert: { ...instance, updatedAt: stamp() } },\n { upsert: true },\n );\n },\n catch: error => translateMongoError(error),\n }),\n\n beginStep: (sagaId, stepIndex) =>\n Effect.tryPromise({\n try: async () => {\n await collection.updateOne(\n { sagaId },\n { $set: { stepIndex, updatedAt: stamp() } },\n );\n },\n catch: error => translateMongoError(error),\n }),\n\n recordOutcome: (sagaId, outcome: SagaStepOutcome) =>\n Effect.tryPromise({\n try: async () => {\n await collection.updateOne(\n { sagaId },\n // `$push`, never a read-modify-write of the array: two outcomes\n // recorded from one process would otherwise lose one another, and a\n // lost outcome is a compensation that cannot address what it undoes.\n { $push: { outcomes: outcome }, $set: { updatedAt: stamp() } },\n );\n },\n catch: error => translateMongoError(error),\n }),\n\n settle: (sagaId, state, error) =>\n Effect.tryPromise({\n try: async () => {\n await collection.updateOne(\n { sagaId },\n { $set: { state, error, updatedAt: stamp() } },\n );\n },\n catch: error => translateMongoError(error),\n }),\n\n /**\n * Take ownership of a stale instance, or answer `undefined`.\n *\n * ⚠️ **One conditional write, not a read and then a write.** The filter\n * repeats `findStale`'s predicate, so two sweepers racing the same instance\n * produce one winner: the loser's filter no longer matches because the\n * winner re-stamped `updatedAt`. That stamp is also what stops the next tick\n * finding the instance this sweep is still working on.\n */\n claimForResume: (sagaId, olderThanMs) =>\n Effect.tryPromise({\n try: async () => {\n const claimed = await collection.findOneAndUpdate(\n {\n sagaId,\n state: { $in: [...UNFINISHED] },\n updatedAt: { $lt: deadline(olderThanMs) },\n },\n { $inc: { resumeAttempts: 1 }, $set: { updatedAt: stamp() } },\n { returnDocument: 'after', projection: { _id: 0 } },\n );\n return (claimed ?? undefined) as SagaInstance | undefined;\n },\n catch: error => translateMongoError(error),\n }),\n\n /**\n * Flag one step's calls as given back, addressing the outcome by its step\n * id: outcomes are `$push`ed, so an index is a fact about arrival order and\n * a resumed walk must not depend on one.\n */\n markCompensated: (sagaId, stepId) =>\n Effect.tryPromise({\n try: async () => {\n await collection.updateOne(\n { sagaId },\n {\n $set: {\n 'outcomes.$[entry].compensated': true,\n updatedAt: stamp(),\n },\n },\n { arrayFilters: [{ 'entry.stepId': stepId }] },\n );\n },\n catch: error => translateMongoError(error),\n }),\n\n get: sagaId =>\n Effect.tryPromise({\n try: async () =>\n ((await collection.findOne({ sagaId }, { projection: { _id: 0 } })) ??\n undefined) as SagaInstance | undefined,\n catch: error => translateMongoError(error),\n }),\n\n /**\n * Instances stuck mid-flight past a deadline. ⚠️ `COMPENSATING` counts: a\n * coordinator that died while unwinding is the state that leaves holds in\n * place, and the one an operator most needs to find.\n */\n findStale: olderThanMs =>\n Effect.tryPromise({\n try: async () =>\n (await collection\n .find(\n {\n state: { $in: [...UNFINISHED] },\n updatedAt: { $lt: deadline(olderThanMs) },\n },\n { projection: { _id: 0 } },\n )\n .toArray()) as SagaInstance[],\n catch: error => translateMongoError(error),\n }),\n };\n};\n\n/**\n * Provides {@link SagaStoreTag} from the service's own database, creating the\n * indexes first.\n */\nexport const MongoSagaStoreLayer = Layer.effect(\n SagaStoreTag,\n Effect.gen(function* () {\n const db = yield* MongoDatabaseTag;\n yield* ensureSagaIndexes(db);\n return makeMongoSagaStore(db);\n }),\n);\n\n/**\n * Provides {@link SagaStoreTag} from a database the host **names**, resolved on\n * the shared client — for a process whose saga store is one of several stores\n * it holds, rather than the one database {@link MongoDatabaseTag} carries.\n *\n * Same pool, same indexes, same store; only where the handle comes from\n * differs.\n */\nexport const mongoSagaStoreLayer = (options: { readonly database: string }) =>\n Layer.effect(\n SagaStoreTag,\n Effect.gen(function* () {\n const client = yield* MongoClientTag;\n const db = client.db(options.database);\n yield* ensureSagaIndexes(db);\n return makeMongoSagaStore(db);\n }),\n );\n"],"names":["SagaStoreTag","Effect","Layer","translateMongoError","MongoClientTag","MongoDatabaseTag","SAGA_COLLECTION","UNFINISHED","sagaCollection","db","collection","deadline","olderThanMs","Date","now","toISOString","ensureSagaIndexes","tryPromise","try","createIndex","sagaId","unique","state","updatedAt","catch","error","makeMongoSagaStore","stamp","start","instance","updateOne","$setOnInsert","upsert","beginStep","stepIndex","$set","recordOutcome","outcome","$push","outcomes","settle","claimForResume","claimed","findOneAndUpdate","$in","$lt","$inc","resumeAttempts","returnDocument","projection","_id","undefined","markCompensated","stepId","arrayFilters","get","findOne","findStale","find","toArray","MongoSagaStoreLayer","effect","gen","mongoSagaStoreLayer","options","client","database"],"mappings":";AAAA,SAKEA,YAAY,QACP,wBAAwB;AAC/B,SAASC,MAAM,EAAEC,KAAK,QAAQ,SAAS;AAGvC,SAASC,mBAAmB,QAAQ,qCAAqC;AACzE,SACEC,cAAc,EACdC,gBAAgB,QACX,sCAAsC;AAE7C;;;;CAIC,GACD,OAAO,MAAMC,kBAAkB,iBAAiB;AAEhD,iDAAiD,GACjD,MAAMC,aAAmC;IAAC;IAAW;CAAe;AAEpE,MAAMC,iBAAiB,CAACC,KAAWA,GAAGC,UAAU,CAAeJ;AAE/D,MAAMK,WAAW,CAACC,cAChB,IAAIC,KAAKA,KAAKC,GAAG,KAAKF,aAAaG,WAAW;AAEhD;;;;CAIC,GACD,OAAO,MAAMC,oBAAoB,CAACP,KAChCR,OAAOgB,UAAU,CAAC;QAChBC,KAAK;YACH,MAAMV,eAAeC,IAAIU,WAAW,CAAC;gBAAEC,QAAQ;YAAE,GAAG;gBAAEC,QAAQ;YAAK;YACnE,MAAMb,eAAeC,IAAIU,WAAW,CAAC;gBAAEG,OAAO;gBAAGC,WAAW;YAAE;QAChE;QACAC,OAAOC,CAAAA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