@entifix/mongo 0.23.11 → 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/adapters/make-mongo-repository.d.ts.map +1 -1
- package/dist/adapters/make-mongo-repository.js +79 -23
- package/dist/adapters/make-mongo-repository.js.map +1 -1
- package/dist/outbox/store.d.ts.map +1 -1
- package/dist/outbox/store.js +12 -0
- package/dist/outbox/store.js.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"make-mongo-repository.d.ts","sourceRoot":"","sources":["../../src/adapters/make-mongo-repository.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,
|
|
1
|
+
{"version":3,"file":"make-mongo-repository.d.ts","sourceRoot":"","sources":["../../src/adapters/make-mongo-repository.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAsB,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAIL,MAAM,EACN,iBAAiB,EAalB,MAAM,eAAe,CAAC;AAEvB,OAAO,KAAK,EAAE,aAAa,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAQjD,kFAAkF;AAClF,wBAAgB,mBAAmB,CAAC,OAAO,SAAS,MAAM,EACxD,iBAAiB,EAAE,iBAAiB,CAAC,OAAO,CAAC,GAC5C,MAAM,CAGR;AA4BD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,SAAS,MAAM,EACxD,EAAE,EAAE,EAAE,EACN,iBAAiB,EAAE,iBAAiB,CAAC,OAAO,CAAC,EAC7C,OAAO,CAAC,EAAE;IAAE,QAAQ,CAAC,OAAO,CAAC,EAAE,aAAa,CAAA;CAAE,GAC7C,gBAAgB,CAgQlB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
|
-
import { declaresRevision, deserializeEntityCollection, deserializeSingleEntity, extractMetaEntity, NotFound, readRevision, serializeEntity, StaleRevision } from '@entifix/core';
|
|
3
|
+
import { declaresRevision, deserializeEntityCollection, deserializeSingleEntity, extractMetaEntity, holdsStoredState, NotFound, readRevision, serializeEntity, StaleRevision, storedStateCondition, unavailableInState } from '@entifix/core';
|
|
4
4
|
import { Effect } from 'effect';
|
|
5
5
|
import { translateMongoError } from '../errors/translate-mongo-error.js';
|
|
6
6
|
import { translateFiltering, translateSorting } from './filter-translator.js';
|
|
@@ -100,11 +100,32 @@ function toEntityId(entityOrId) {
|
|
|
100
100
|
return entity;
|
|
101
101
|
});
|
|
102
102
|
const revised = declaresRevision(entityConstructor);
|
|
103
|
+
/** The `expect` of a write, resolved to the field the store holds it under. */ const conditionOf = (options)=>(options == null ? void 0 : options.expect) === undefined ? undefined : storedStateCondition(entityConstructor, options.expect);
|
|
104
|
+
/** The filter clause a condition adds to a write. */ const stateFilter = (condition)=>condition === undefined ? {} : {
|
|
105
|
+
[condition.key]: {
|
|
106
|
+
$in: [
|
|
107
|
+
...condition.in
|
|
108
|
+
]
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
/** What a write that matched nothing reads back, only to name the refusal. */ const readBack = (id, condition)=>Effect.tryPromise({
|
|
112
|
+
try: ()=>collection.findOne({
|
|
113
|
+
id
|
|
114
|
+
}, _extends({
|
|
115
|
+
projection: _extends({
|
|
116
|
+
_id: 0,
|
|
117
|
+
revision: 1
|
|
118
|
+
}, condition === undefined ? {} : {
|
|
119
|
+
[condition.key]: 1
|
|
120
|
+
})
|
|
121
|
+
}, inSession)),
|
|
122
|
+
catch: (error)=>translateMongoError(error)
|
|
123
|
+
});
|
|
103
124
|
/**
|
|
104
125
|
* A save of an entity that declares a revision (ADR 0032): a create that
|
|
105
126
|
* never overwrites, or one conditional write on the revision the caller read.
|
|
106
127
|
* Never a read followed by a write — two saves would both read `n`.
|
|
107
|
-
*/ const saveRevised = (entity)=>Effect.gen(function*() {
|
|
128
|
+
*/ const saveRevised = (entity, condition)=>Effect.gen(function*() {
|
|
108
129
|
var _entity_id;
|
|
109
130
|
const key = extractMetaEntity(entityConstructor).key;
|
|
110
131
|
const doc = serializeEntity(entityConstructor, entity);
|
|
@@ -126,31 +147,27 @@ function toEntityId(entityOrId) {
|
|
|
126
147
|
return entity;
|
|
127
148
|
}
|
|
128
149
|
const result = yield* Effect.tryPromise({
|
|
129
|
-
try: ()=>collection.replaceOne({
|
|
150
|
+
try: ()=>collection.replaceOne(_extends({
|
|
130
151
|
id,
|
|
131
152
|
revision: read
|
|
132
|
-
}, _extends({}, doc, {
|
|
153
|
+
}, stateFilter(condition)), _extends({}, doc, {
|
|
133
154
|
id,
|
|
134
155
|
revision: read + 1
|
|
135
156
|
}), inSession),
|
|
136
157
|
catch: (error)=>translateMongoError(error)
|
|
137
158
|
});
|
|
138
159
|
if (result.matchedCount === 0) {
|
|
139
|
-
// The write already decided; this read only names the refusal.
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
projection: {
|
|
145
|
-
_id: 0,
|
|
146
|
-
revision: 1
|
|
147
|
-
}
|
|
148
|
-
}, inSession)),
|
|
149
|
-
catch: (error)=>translateMongoError(error)
|
|
150
|
-
});
|
|
151
|
-
return yield* stored === null ? Effect.fail(new NotFound({
|
|
160
|
+
// The write already decided; this read only names the refusal. A
|
|
161
|
+
// record in another state is refused for its state before its
|
|
162
|
+
// revision: a fresher read would not make the save legal.
|
|
163
|
+
const stored = yield* readBack(id, condition);
|
|
164
|
+
if (stored === null) return yield* new NotFound({
|
|
152
165
|
entity: key
|
|
153
|
-
})
|
|
166
|
+
});
|
|
167
|
+
if (condition !== undefined && !holdsStoredState(condition, stored)) {
|
|
168
|
+
return yield* unavailableInState(entityConstructor, condition, stored);
|
|
169
|
+
}
|
|
170
|
+
return yield* Effect.fail(new StaleRevision({
|
|
154
171
|
entity: key,
|
|
155
172
|
current: readRevision(stored)
|
|
156
173
|
}));
|
|
@@ -159,7 +176,38 @@ function toEntityId(entityOrId) {
|
|
|
159
176
|
entity.revision = read + 1;
|
|
160
177
|
return entity;
|
|
161
178
|
});
|
|
162
|
-
const save = (entity)=>
|
|
179
|
+
const save = (entity, options)=>{
|
|
180
|
+
const condition = conditionOf(options);
|
|
181
|
+
if (revised) return saveRevised(entity, condition);
|
|
182
|
+
return condition === undefined ? saveUnchecked(entity) : saveConditioned(entity, condition);
|
|
183
|
+
};
|
|
184
|
+
/**
|
|
185
|
+
* An update of a record that declares no revision, on the states it must
|
|
186
|
+
* hold: one `replaceOne` on the id and the state, never an upsert — a save
|
|
187
|
+
* with `expect` is an update of a stored record.
|
|
188
|
+
*/ const saveConditioned = (entity, condition)=>Effect.gen(function*() {
|
|
189
|
+
const key = extractMetaEntity(entityConstructor).key;
|
|
190
|
+
const doc = serializeEntity(entityConstructor, entity);
|
|
191
|
+
const id = entity.id;
|
|
192
|
+
if (id === undefined) return yield* new NotFound({
|
|
193
|
+
entity: key
|
|
194
|
+
});
|
|
195
|
+
const result = yield* Effect.tryPromise({
|
|
196
|
+
try: ()=>collection.replaceOne(_extends({
|
|
197
|
+
id
|
|
198
|
+
}, stateFilter(condition)), _extends({}, doc, {
|
|
199
|
+
id
|
|
200
|
+
}), inSession),
|
|
201
|
+
catch: (error)=>translateMongoError(error)
|
|
202
|
+
});
|
|
203
|
+
if (result.matchedCount === 0) {
|
|
204
|
+
const stored = yield* readBack(id, condition);
|
|
205
|
+
return yield* stored === null ? Effect.fail(new NotFound({
|
|
206
|
+
entity: key
|
|
207
|
+
})) : Effect.fail(unavailableInState(entityConstructor, condition, stored));
|
|
208
|
+
}
|
|
209
|
+
return entity;
|
|
210
|
+
});
|
|
163
211
|
const saveUnchecked = (entity)=>Effect.gen(function*() {
|
|
164
212
|
var _entity_id;
|
|
165
213
|
const doc = serializeEntity(entityConstructor, entity);
|
|
@@ -183,14 +231,22 @@ function toEntityId(entityOrId) {
|
|
|
183
231
|
entity.id = id;
|
|
184
232
|
return entity;
|
|
185
233
|
});
|
|
186
|
-
const del = (entityOrId)=>Effect.gen(function*() {
|
|
234
|
+
const del = (entityOrId, options)=>Effect.gen(function*() {
|
|
187
235
|
const id = toEntityId(entityOrId);
|
|
188
|
-
|
|
189
|
-
|
|
236
|
+
const condition = conditionOf(options);
|
|
237
|
+
const result = yield* Effect.tryPromise({
|
|
238
|
+
try: ()=>collection.deleteOne(_extends({
|
|
190
239
|
id
|
|
191
|
-
}, inSession),
|
|
240
|
+
}, stateFilter(condition)), inSession),
|
|
192
241
|
catch: (error)=>translateMongoError(error)
|
|
193
242
|
});
|
|
243
|
+
if (condition === undefined || result.deletedCount > 0) return;
|
|
244
|
+
// Nothing deleted: either nothing was there, which a delete accepts,
|
|
245
|
+
// or the record is in a state it may not be deleted from.
|
|
246
|
+
const stored = yield* readBack(id, condition);
|
|
247
|
+
if (stored !== null) {
|
|
248
|
+
return yield* unavailableInState(entityConstructor, condition, stored);
|
|
249
|
+
}
|
|
194
250
|
});
|
|
195
251
|
// Cast through the interface to keep its generic signatures: each method here
|
|
196
252
|
// is written against this entity's type, the interface against any entity's.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/make-mongo-repository.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { EntityRepository } from '@entifix/business';\nimport {\n declaresRevision,\n deserializeEntityCollection,\n deserializeSingleEntity,\n Entity,\n EntityConstructor,\n EntityId,\n EntityLoadRequest,\n EntityPage,\n extractMetaEntity,\n NotFound,\n readRevision,\n serializeEntity,\n StaleRevision,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport type { ClientSession, Db } from 'mongodb';\n\nimport { translateMongoError } from '../errors/translate-mongo-error.js';\nimport { translateFiltering, translateSorting } from './filter-translator.js';\n\n/** Projection that drops Mongo's internal `_id` from read results. */\nconst WITHOUT_MONGO_ID = { projection: { _id: 0 } } as const;\n\n/** The collection an entity's records live in: its `key`, else its class name. */\nexport function mongoCollectionName<TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n): string {\n const metaEntity = extractMetaEntity(entityConstructor);\n return metaEntity.key ?? metaEntity.name;\n}\n\n/**\n * The collections whose unique index on `id` is known to exist, per database.\n * A create is atomic only against that index: two concurrent creates of one\n * client-minted id would otherwise both insert. Keyed on the `Db` so a fake or\n * a reset database starts clean, and a rejected attempt is forgotten so the\n * next create tries again.\n */\nconst ensuredIdIndexes = new WeakMap<Db, Set<string>>();\n\nconst ensureIdIndex = (db: Db, name: string) =>\n Effect.suspend(() => {\n const ensured = ensuredIdIndexes.get(db) ?? new Set<string>();\n ensuredIdIndexes.set(db, ensured);\n if (ensured.has(name)) return Effect.void;\n return Effect.tryPromise({\n try: () => db.collection(name).createIndex({ id: 1 }, { unique: true }),\n catch: error => translateMongoError(error),\n }).pipe(Effect.tap(() => Effect.sync(() => ensured.add(name))));\n });\n\nfunction toEntityId(entityOrId: EntityId | Entity): EntityId {\n return entityOrId != null && typeof entityOrId === 'object'\n ? (entityOrId as Entity).id\n : (entityOrId as EntityId);\n}\n\n/**\n * Builds an {@link EntityRepository} for a single entity type, backed by a live\n * mongodb {@link Db}. The `db` and `entityConstructor` are captured in closures,\n * so every method's Effect has no outstanding requirements (`R = never`), which\n * is exactly what the interface asks.\n *\n * Collection name = the entity's `key` (falling back to its class name). Reads\n * reuse the shared entifix deserializer (rebuilding links from embedded objects\n * or scalar FKs); writes reuse the shared serializer. Mongo failures surface as\n * categorised failures — `NotFound`, `DuplicateKey`, `Unavailable` and the\n * rest — through `translateMongoError`.\n *\n * This is the Mongo mirror of the REST `buildEntityRestAdapter*` builders.\n *\n * Pass `session` to make the repository part of a transaction — a unit of\n * work's handle — so its writes commit with the unit and its reads see what the\n * unit has already written.\n */\nexport function makeMongoRepository<TEntity extends Entity>(\n db: Db,\n entityConstructor: EntityConstructor<TEntity>,\n options?: { readonly session?: ClientSession },\n): EntityRepository {\n const collectionName = mongoCollectionName(entityConstructor);\n const collection = db.collection(collectionName);\n // Spread into every call, so a repository with no session passes none.\n const inSession = options?.session ? { session: options.session } : {};\n\n const load = <T extends Entity>(request: EntityLoadRequest<T>) =>\n Effect.gen(function* () {\n const filter = translateFiltering(request.filtering);\n const sort = translateSorting(request.sorting);\n const page = request.page ?? 1;\n const pageSize = request.pageSize ?? 10;\n const skip = (page - 1) * pageSize;\n\n const docs = yield* Effect.tryPromise({\n try: () =>\n collection\n .find(filter, { ...WITHOUT_MONGO_ID, ...inSession })\n .sort(sort)\n .skip(skip)\n .limit(pageSize)\n .toArray(),\n catch: error => translateMongoError(error),\n });\n const total = yield* Effect.tryPromise({\n try: () => collection.countDocuments(filter, inSession),\n catch: error => translateMongoError(error),\n });\n\n const items = yield* deserializeEntityCollection(entityConstructor, docs);\n\n return {\n items: items as unknown as T[],\n total,\n request,\n } satisfies EntityPage<T>;\n });\n\n const get = <T extends Entity>(id: EntityId) =>\n Effect.gen(function* () {\n const doc = yield* Effect.tryPromise({\n try: () =>\n collection.findOne({ id }, { ...WITHOUT_MONGO_ID, ...inSession }),\n catch: error => translateMongoError(error),\n });\n const entity = yield* deserializeSingleEntity(entityConstructor, doc);\n if (entity === undefined) {\n return yield* Effect.fail(\n new NotFound({ entity: extractMetaEntity(entityConstructor).key }),\n );\n }\n return entity as unknown as T;\n });\n\n const revised = declaresRevision(entityConstructor);\n\n /**\n * A save of an entity that declares a revision (ADR 0032): a create that\n * never overwrites, or one conditional write on the revision the caller read.\n * Never a read followed by a write — two saves would both read `n`.\n */\n const saveRevised = <T extends Entity>(entity: T) =>\n Effect.gen(function* () {\n const key = extractMetaEntity(entityConstructor).key;\n const doc = serializeEntity(\n entityConstructor,\n entity as unknown as TEntity,\n );\n const read = readRevision(entity);\n const id = entity.id ?? randomUUID();\n if (read === undefined) {\n yield* ensureIdIndex(db, collectionName);\n yield* Effect.tryPromise({\n try: () =>\n collection.insertOne({ ...doc, id, revision: 1 }, inSession),\n catch: error => translateMongoError(error),\n }).pipe(\n Effect.mapError(failure =>\n failure._tag === 'DuplicateKey'\n ? new StaleRevision({ entity: key })\n : failure,\n ),\n );\n entity.id = id;\n (entity as { revision?: number }).revision = 1;\n return entity;\n }\n const result = yield* Effect.tryPromise({\n try: () =>\n collection.replaceOne(\n { id, revision: read },\n { ...doc, id, revision: read + 1 },\n inSession,\n ),\n catch: error => translateMongoError(error),\n });\n if (result.matchedCount === 0) {\n // The write already decided; this read only names the refusal.\n const stored = yield* Effect.tryPromise({\n try: () =>\n collection.findOne(\n { id },\n { projection: { _id: 0, revision: 1 }, ...inSession },\n ),\n catch: error => translateMongoError(error),\n });\n return yield* stored === null\n ? Effect.fail(new NotFound({ entity: key }))\n : Effect.fail(\n new StaleRevision({\n entity: key,\n current: readRevision(stored),\n }),\n );\n }\n entity.id = id;\n (entity as { revision?: number }).revision = read + 1;\n return entity;\n });\n\n const save = <T extends Entity>(entity: T) =>\n revised ? saveRevised(entity) : saveUnchecked(entity);\n\n const saveUnchecked = <T extends Entity>(entity: T) =>\n Effect.gen(function* () {\n const doc = serializeEntity(\n entityConstructor,\n entity as unknown as TEntity,\n );\n // A create arrives without an id, so the store mints one. Entities are\n // addressed by their own `id` field (never Mongo's `_id`, which reads\n // project away), so an inserted document without one would be\n // unreachable by `get` and by any later `replaceOne`.\n const id = entity.id ?? randomUUID();\n yield* Effect.tryPromise({\n // `doc` omits `id` when it was undefined (the serializer drops\n // undefined), hence spreading the resolved id back in.\n try: () =>\n collection.replaceOne(\n { id },\n { ...doc, id },\n { upsert: true, ...inSession },\n ),\n catch: error => translateMongoError(error),\n });\n entity.id = id;\n return entity;\n });\n\n const del = <T extends Entity>(entityOrId: EntityId | T) =>\n Effect.gen(function* () {\n const id = toEntityId(entityOrId);\n yield* Effect.tryPromise({\n try: () => collection.deleteOne({ id }, inSession),\n catch: error => translateMongoError(error),\n });\n });\n\n // Cast through the interface to keep its generic signatures: each method here\n // is written against this entity's type, the interface against any entity's.\n return {\n load,\n get,\n save,\n delete: del,\n } as unknown as EntityRepository;\n}\n"],"names":["randomUUID","declaresRevision","deserializeEntityCollection","deserializeSingleEntity","extractMetaEntity","NotFound","readRevision","serializeEntity","StaleRevision","Effect","translateMongoError","translateFiltering","translateSorting","WITHOUT_MONGO_ID","projection","_id","mongoCollectionName","entityConstructor","metaEntity","key","name","ensuredIdIndexes","WeakMap","ensureIdIndex","db","suspend","ensured","get","Set","set","has","void","tryPromise","try","collection","createIndex","id","unique","catch","error","pipe","tap","sync","add","toEntityId","entityOrId","makeMongoRepository","options","collectionName","inSession","session","load","request","gen","filter","filtering","sort","sorting","page","pageSize","skip","docs","find","limit","toArray","total","countDocuments","items","doc","findOne","entity","undefined","fail","revised","saveRevised","read","insertOne","revision","mapError","failure","_tag","result","replaceOne","matchedCount","stored","current","save","saveUnchecked","upsert","del","deleteOne","delete"],"mappings":";AAAA,SAASA,UAAU,QAAQ,cAAc;AAGzC,SACEC,gBAAgB,EAChBC,2BAA2B,EAC3BC,uBAAuB,EAMvBC,iBAAiB,EACjBC,QAAQ,EACRC,YAAY,EACZC,eAAe,EACfC,aAAa,QACR,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAGhC,SAASC,mBAAmB,QAAQ,qCAAqC;AACzE,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,yBAAyB;AAE9E,oEAAoE,GACpE,MAAMC,mBAAmB;IAAEC,YAAY;QAAEC,KAAK;IAAE;AAAE;AAElD,gFAAgF,GAChF,OAAO,SAASC,oBACdC,iBAA6C;QAGtCC;IADP,MAAMA,aAAad,kBAAkBa;IACrC,QAAOC,kBAAAA,WAAWC,GAAG,YAAdD,kBAAkBA,WAAWE,IAAI;AAC1C;AAEA;;;;;;CAMC,GACD,MAAMC,mBAAmB,IAAIC;AAE7B,MAAMC,gBAAgB,CAACC,IAAQJ,OAC7BX,OAAOgB,OAAO,CAAC;YACGJ;QAAhB,MAAMK,WAAUL,wBAAAA,iBAAiBM,GAAG,CAACH,eAArBH,wBAA4B,IAAI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iB;YARX,MAAMF,MAAM7D,gBACVU,mBACAqD;YAEF,uEAAuE;YACvE,sEAAsE;YACtE,8DAA8D;YAC9D,sDAAsD;YACtD,MAAMlC,MAAKkC,aAAAA,OAAOlC,EAAE,YAATkC,aAAatE;YACxB,OAAOS,OAAOuB,UAAU,CAAC;gBACvB,+DAA+D;gBAC/D,uDAAuD;gBACvDC,KAAK,IACHC,WAAWgD,UAAU,CACnB;wBAAE9C;oBAAG,GACL,aAAKgC;wBAAKhC;wBACV;wBAAEoD,QAAQ;uBAASvC;gBAEvBX,OAAOC,CAAAA,QAAS7B,oBAAoB6B;YACtC;YACA+B,OAAOlC,EAAE,GAAGA;YACZ,OAAOkC;QACT;IAEF,MAAMmB,MAAM,CAAmB5C,aAC7BpC,OAAO4C,GAAG,CAAC;YACT,MAAMjB,KAAKQ,WAAWC;YACtB,OAAOpC,OAAOuB,UAAU,CAAC;gBACvBC,KAAK,IAAMC,WAAWwD,SAAS,CAAC;wBAAEtD;oBAAG,GAAGa;gBACxCX,OAAOC,CAAAA,QAAS7B,oBAAoB6B;YACtC;QACF;IAEF,8EAA8E;IAC9E,6EAA6E;IAC7E,OAAO;QACLY;QACAxB;QACA2D;QACAK,QAAQF;IACV;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/make-mongo-repository.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { EntityRepository, EntityWriteOptions } from '@entifix/business';\nimport {\n declaresRevision,\n deserializeEntityCollection,\n deserializeSingleEntity,\n Entity,\n EntityConstructor,\n EntityId,\n EntityLoadRequest,\n EntityPage,\n extractMetaEntity,\n holdsStoredState,\n NotFound,\n readRevision,\n serializeEntity,\n StaleRevision,\n type StoredStateCondition,\n storedStateCondition,\n unavailableInState,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport type { ClientSession, Db } from 'mongodb';\n\nimport { translateMongoError } from '../errors/translate-mongo-error.js';\nimport { translateFiltering, translateSorting } from './filter-translator.js';\n\n/** Projection that drops Mongo's internal `_id` from read results. */\nconst WITHOUT_MONGO_ID = { projection: { _id: 0 } } as const;\n\n/** The collection an entity's records live in: its `key`, else its class name. */\nexport function mongoCollectionName<TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n): string {\n const metaEntity = extractMetaEntity(entityConstructor);\n return metaEntity.key ?? metaEntity.name;\n}\n\n/**\n * The collections whose unique index on `id` is known to exist, per database.\n * A create is atomic only against that index: two concurrent creates of one\n * client-minted id would otherwise both insert. Keyed on the `Db` so a fake or\n * a reset database starts clean, and a rejected attempt is forgotten so the\n * next create tries again.\n */\nconst ensuredIdIndexes = new WeakMap<Db, Set<string>>();\n\nconst ensureIdIndex = (db: Db, name: string) =>\n Effect.suspend(() => {\n const ensured = ensuredIdIndexes.get(db) ?? new Set<string>();\n ensuredIdIndexes.set(db, ensured);\n if (ensured.has(name)) return Effect.void;\n return Effect.tryPromise({\n try: () => db.collection(name).createIndex({ id: 1 }, { unique: true }),\n catch: error => translateMongoError(error),\n }).pipe(Effect.tap(() => Effect.sync(() => ensured.add(name))));\n });\n\nfunction toEntityId(entityOrId: EntityId | Entity): EntityId {\n return entityOrId != null && typeof entityOrId === 'object'\n ? (entityOrId as Entity).id\n : (entityOrId as EntityId);\n}\n\n/**\n * Builds an {@link EntityRepository} for a single entity type, backed by a live\n * mongodb {@link Db}. The `db` and `entityConstructor` are captured in closures,\n * so every method's Effect has no outstanding requirements (`R = never`), which\n * is exactly what the interface asks.\n *\n * Collection name = the entity's `key` (falling back to its class name). Reads\n * reuse the shared entifix deserializer (rebuilding links from embedded objects\n * or scalar FKs); writes reuse the shared serializer. Mongo failures surface as\n * categorised failures — `NotFound`, `DuplicateKey`, `Unavailable` and the\n * rest — through `translateMongoError`.\n *\n * This is the Mongo mirror of the REST `buildEntityRestAdapter*` builders.\n *\n * Pass `session` to make the repository part of a transaction — a unit of\n * work's handle — so its writes commit with the unit and its reads see what the\n * unit has already written.\n */\nexport function makeMongoRepository<TEntity extends Entity>(\n db: Db,\n entityConstructor: EntityConstructor<TEntity>,\n options?: { readonly session?: ClientSession },\n): EntityRepository {\n const collectionName = mongoCollectionName(entityConstructor);\n const collection = db.collection(collectionName);\n // Spread into every call, so a repository with no session passes none.\n const inSession = options?.session ? { session: options.session } : {};\n\n const load = <T extends Entity>(request: EntityLoadRequest<T>) =>\n Effect.gen(function* () {\n const filter = translateFiltering(request.filtering);\n const sort = translateSorting(request.sorting);\n const page = request.page ?? 1;\n const pageSize = request.pageSize ?? 10;\n const skip = (page - 1) * pageSize;\n\n const docs = yield* Effect.tryPromise({\n try: () =>\n collection\n .find(filter, { ...WITHOUT_MONGO_ID, ...inSession })\n .sort(sort)\n .skip(skip)\n .limit(pageSize)\n .toArray(),\n catch: error => translateMongoError(error),\n });\n const total = yield* Effect.tryPromise({\n try: () => collection.countDocuments(filter, inSession),\n catch: error => translateMongoError(error),\n });\n\n const items = yield* deserializeEntityCollection(entityConstructor, docs);\n\n return {\n items: items as unknown as T[],\n total,\n request,\n } satisfies EntityPage<T>;\n });\n\n const get = <T extends Entity>(id: EntityId) =>\n Effect.gen(function* () {\n const doc = yield* Effect.tryPromise({\n try: () =>\n collection.findOne({ id }, { ...WITHOUT_MONGO_ID, ...inSession }),\n catch: error => translateMongoError(error),\n });\n const entity = yield* deserializeSingleEntity(entityConstructor, doc);\n if (entity === undefined) {\n return yield* Effect.fail(\n new NotFound({ entity: extractMetaEntity(entityConstructor).key }),\n );\n }\n return entity as unknown as T;\n });\n\n const revised = declaresRevision(entityConstructor);\n\n /** The `expect` of a write, resolved to the field the store holds it under. */\n const conditionOf = (\n options: EntityWriteOptions | undefined,\n ): StoredStateCondition | undefined =>\n options?.expect === undefined\n ? undefined\n : storedStateCondition(entityConstructor, options.expect);\n\n /** The filter clause a condition adds to a write. */\n const stateFilter = (condition: StoredStateCondition | undefined) =>\n condition === undefined\n ? {}\n : { [condition.key]: { $in: [...condition.in] } };\n\n /** What a write that matched nothing reads back, only to name the refusal. */\n const readBack = (id: EntityId, condition?: StoredStateCondition) =>\n Effect.tryPromise({\n try: () =>\n collection.findOne(\n { id },\n {\n projection: {\n _id: 0,\n revision: 1,\n ...(condition === undefined ? {} : { [condition.key]: 1 }),\n },\n ...inSession,\n },\n ),\n catch: error => translateMongoError(error),\n });\n\n /**\n * A save of an entity that declares a revision (ADR 0032): a create that\n * never overwrites, or one conditional write on the revision the caller read.\n * Never a read followed by a write — two saves would both read `n`.\n */\n const saveRevised = <T extends Entity>(\n entity: T,\n condition: StoredStateCondition | undefined,\n ) =>\n Effect.gen(function* () {\n const key = extractMetaEntity(entityConstructor).key;\n const doc = serializeEntity(\n entityConstructor,\n entity as unknown as TEntity,\n );\n const read = readRevision(entity);\n const id = entity.id ?? randomUUID();\n if (read === undefined) {\n yield* ensureIdIndex(db, collectionName);\n yield* Effect.tryPromise({\n try: () =>\n collection.insertOne({ ...doc, id, revision: 1 }, inSession),\n catch: error => translateMongoError(error),\n }).pipe(\n Effect.mapError(failure =>\n failure._tag === 'DuplicateKey'\n ? new StaleRevision({ entity: key })\n : failure,\n ),\n );\n entity.id = id;\n (entity as { revision?: number }).revision = 1;\n return entity;\n }\n const result = yield* Effect.tryPromise({\n try: () =>\n collection.replaceOne(\n { id, revision: read, ...stateFilter(condition) },\n { ...doc, id, revision: read + 1 },\n inSession,\n ),\n catch: error => translateMongoError(error),\n });\n if (result.matchedCount === 0) {\n // The write already decided; this read only names the refusal. A\n // record in another state is refused for its state before its\n // revision: a fresher read would not make the save legal.\n const stored = yield* readBack(id, condition);\n if (stored === null) return yield* new NotFound({ entity: key });\n if (condition !== undefined && !holdsStoredState(condition, stored)) {\n return yield* unavailableInState(\n entityConstructor,\n condition,\n stored,\n );\n }\n return yield* Effect.fail(\n new StaleRevision({\n entity: key,\n current: readRevision(stored),\n }),\n );\n }\n entity.id = id;\n (entity as { revision?: number }).revision = read + 1;\n return entity;\n });\n\n const save = <T extends Entity>(entity: T, options?: EntityWriteOptions) => {\n const condition = conditionOf(options);\n if (revised) return saveRevised(entity, condition);\n return condition === undefined\n ? saveUnchecked(entity)\n : saveConditioned(entity, condition);\n };\n\n /**\n * An update of a record that declares no revision, on the states it must\n * hold: one `replaceOne` on the id and the state, never an upsert — a save\n * with `expect` is an update of a stored record.\n */\n const saveConditioned = <T extends Entity>(\n entity: T,\n condition: StoredStateCondition,\n ) =>\n Effect.gen(function* () {\n const key = extractMetaEntity(entityConstructor).key;\n const doc = serializeEntity(\n entityConstructor,\n entity as unknown as TEntity,\n );\n const id = entity.id;\n if (id === undefined) return yield* new NotFound({ entity: key });\n const result = yield* Effect.tryPromise({\n try: () =>\n collection.replaceOne(\n { id, ...stateFilter(condition) },\n { ...doc, id },\n inSession,\n ),\n catch: error => translateMongoError(error),\n });\n if (result.matchedCount === 0) {\n const stored = yield* readBack(id, condition);\n return yield* stored === null\n ? Effect.fail(new NotFound({ entity: key }))\n : Effect.fail(\n unavailableInState(entityConstructor, condition, stored),\n );\n }\n return entity;\n });\n\n const saveUnchecked = <T extends Entity>(entity: T) =>\n Effect.gen(function* () {\n const doc = serializeEntity(\n entityConstructor,\n entity as unknown as TEntity,\n );\n // A create arrives without an id, so the store mints one. Entities are\n // addressed by their own `id` field (never Mongo's `_id`, which reads\n // project away), so an inserted document without one would be\n // unreachable by `get` and by any later `replaceOne`.\n const id = entity.id ?? randomUUID();\n yield* Effect.tryPromise({\n // `doc` omits `id` when it was undefined (the serializer drops\n // undefined), hence spreading the resolved id back in.\n try: () =>\n collection.replaceOne(\n { id },\n { ...doc, id },\n { upsert: true, ...inSession },\n ),\n catch: error => translateMongoError(error),\n });\n entity.id = id;\n return entity;\n });\n\n const del = <T extends Entity>(\n entityOrId: EntityId | T,\n options?: EntityWriteOptions,\n ) =>\n Effect.gen(function* () {\n const id = toEntityId(entityOrId);\n const condition = conditionOf(options);\n const result = yield* Effect.tryPromise({\n try: () =>\n collection.deleteOne({ id, ...stateFilter(condition) }, inSession),\n catch: error => translateMongoError(error),\n });\n if (condition === undefined || result.deletedCount > 0) return;\n // Nothing deleted: either nothing was there, which a delete accepts,\n // or the record is in a state it may not be deleted from.\n const stored = yield* readBack(id, condition);\n if (stored !== null) {\n return yield* unavailableInState(entityConstructor, condition, stored);\n }\n });\n\n // Cast through the interface to keep its generic signatures: each method here\n // is written against this entity's type, the interface against any entity's.\n return {\n load,\n get,\n save,\n delete: del,\n } as unknown as EntityRepository;\n}\n"],"names":["randomUUID","declaresRevision","deserializeEntityCollection","deserializeSingleEntity","extractMetaEntity","holdsStoredState","NotFound","readRevision","serializeEntity","StaleRevision","storedStateCondition","unavailableInState","Effect","translateMongoError","translateFiltering","translateSorting","WITHOUT_MONGO_ID","projection","_id","mongoCollectionName","entityConstructor","metaEntity","key","name","ensuredIdIndexes","WeakMap","ensureIdIndex","db","suspend","ensured","get","Set","set","has","void","tryPromise","try","collection","createIndex","id","unique","catch","error","pipe","tap","sync","add","toEntityId","entityOrId","makeMongoRepository","options","collectionName","inSession","session","load","request","gen","filter","filtering","sort","sorting","page","pageSize","skip","docs","find","limit","toArray","total","countDocuments","items","doc","findOne","entity","undefined","fail","revised","conditionOf","expect","stateFilter","condition","$in","in","readBack","revision","saveRevised","read","insertOne","mapError","failure","_tag","result","replaceOne","matchedCount","stored","current","save","saveUnchecked","saveConditioned","upsert","del","deleteOne","deletedCount","delete"],"mappings":";AAAA,SAASA,UAAU,QAAQ,cAAc;AAGzC,SACEC,gBAAgB,EAChBC,2BAA2B,EAC3BC,uBAAuB,EAMvBC,iBAAiB,EACjBC,gBAAgB,EAChBC,QAAQ,EACRC,YAAY,EACZC,eAAe,EACfC,aAAa,EAEbC,oBAAoB,EACpBC,kBAAkB,QACb,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAGhC,SAASC,mBAAmB,QAAQ,qCAAqC;AACzE,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,yBAAyB;AAE9E,oEAAoE,GACpE,MAAMC,mBAAmB;IAAEC,YAAY;QAAEC,KAAK;IAAE;AAAE;AAElD,gFAA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C,YAAYC,aAAc5B;gBAC1DX,OAAOC,CAAAA,QAAS7B,oBAAoB6B;YACtC;YACA,IAAIsC,cAAcN,aAAaiB,OAAOW,YAAY,GAAG,GAAG;YACxD,qEAAqE;YACrE,0DAA0D;YAC1D,MAAMR,SAAS,OAAOX,SAAS5C,IAAIyC;YACnC,IAAIc,WAAW,MAAM;gBACnB,OAAO,OAAOnF,mBAAmBS,mBAAmB4D,WAAWc;YACjE;QACF;IAEF,8EAA8E;IAC9E,6EAA6E;IAC7E,OAAO;QACLxC;QACAxB;QACAkE;QACAO,QAAQH;IACV;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/outbox/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAC9E,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAIlC;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,iBAAiB,WAAW,CAAC;AAa1C;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,WAAW,KAAG,WAalD,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,iBAAiB,GAAI,IAAI,EAAE,EAAE,SAAS,MAAM,wEAiBrD,CAAC;AAEL;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,mBAAmB,GAAI,IAAI,EAAE,qEAkBtC,CAAC;AAEL;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,GAAI,IAAI,EAAE,KAAG,
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/outbox/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAC9E,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAIlC;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,iBAAiB,WAAW,CAAC;AAa1C;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,WAAW,KAAG,WAalD,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,iBAAiB,GAAI,IAAI,EAAE,EAAE,SAAS,MAAM,wEAiBrD,CAAC;AAEL;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,mBAAmB,GAAI,IAAI,EAAE,qEAkBtC,CAAC;AAEL;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,GAAI,IAAI,EAAE,KAAG,MAwGxC,CAAC"}
|
package/dist/outbox/store.js
CHANGED
|
@@ -231,6 +231,18 @@ const isDuplicateKey = (error)=>typeof error === 'object' && error !== null && e
|
|
|
231
231
|
}
|
|
232
232
|
}),
|
|
233
233
|
catch: (cause)=>translateMongoError(cause)
|
|
234
|
+
}).pipe(Effect.asVoid),
|
|
235
|
+
// No lease to give back here: `pending` reads without claiming, so the
|
|
236
|
+
// next pass sees the entry again by itself.
|
|
237
|
+
hold: (entry, reason)=>Effect.tryPromise({
|
|
238
|
+
try: ()=>collection.updateOne({
|
|
239
|
+
eventId: entry.eventId
|
|
240
|
+
}, {
|
|
241
|
+
$set: {
|
|
242
|
+
lastError: reason
|
|
243
|
+
}
|
|
244
|
+
}),
|
|
245
|
+
catch: (cause)=>translateMongoError(cause)
|
|
234
246
|
}).pipe(Effect.asVoid)
|
|
235
247
|
};
|
|
236
248
|
};
|
package/dist/outbox/store.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/outbox/store.ts"],"sourcesContent":["import type { Outbox, OutboxEntry, OutboxEvent } from '@entifix/transactions';\nimport { Effect } from 'effect';\nimport type { Db } from 'mongodb';\n\nimport { translateMongoError } from '../errors/translate-mongo-error.js';\n\n/**\n * The outbox collection, and it lives in the **same database as the entity it\n * describes** — never in a shared control-plane store.\n *\n * Two reasons, and the second only shows up later. Same database means the\n * entity write and its event are one single-database transaction, which stays a\n * single-*shard* transaction if this ever shards; a control-plane outbox would\n * be cross-database from the first commit. And an outbox holds event payloads:\n * a `TransactionEvent` carries no tenant data, but `catalog.published` carries a\n * whole offering and `order.placed` a whole receipt, and neither may land in the\n * control plane on its way to the bus.\n *\n * That rule is why this lives here rather than in one service. It applies\n * identically to a per-organization `tenant_<id>` and to a single platform-plane\n * database, and the second publisher is what turned a copy into a seam.\n */\nexport const OUTBOX_COLLECTION = 'outbox';\n\n/** Drop Mongo's internal `_id` from every read. */\nconst WITHOUT_MONGO_ID = { projection: { _id: 0 } } as const;\n\n/** Mongo's duplicate-key error, which is how a replayed command is recognised. */\nconst DUPLICATE_KEY = 11000;\n\nconst isDuplicateKey = (error: unknown): boolean =>\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === DUPLICATE_KEY;\n\n/**\n * The stored shape of an outbox entry.\n *\n * Exported because the `completed` entry is **not** written through the port:\n * it has to join the entity write's session to be atomic with it, and a session\n * cannot live in a framework-free contract. The handler inserts this document\n * itself; everything else goes through {@link makeMongoOutbox}.\n */\nexport const outboxDocument = (event: OutboxEvent): OutboxEntry => ({\n eventId: event.id,\n aggregate: event.aggregate,\n version: event.version,\n event,\n sent: false,\n // Defaulted here rather than at each write site because there are two of\n // them: the relay's `enqueue`, and the transaction handler's own insert\n // inside the entity's Mongo session. An entry missing `attempts` would sort\n // into `pending` and then fail `attempts + 1` arithmetic on a `undefined`.\n attempts: 0,\n quarantined: false,\n createdAt: event.at,\n});\n\n/**\n * Puts a **quarantined** entry back in the queue, and touches nothing else.\n *\n * A rebuild walk's repair for the one failure measured on a live lab: with the\n * broker down long enough, the relay spends `outbox.maxAttempts` on an\n * announcement and quarantines it (the deliberate skip-so-the-head-moves),\n * after which the tenant store reads one thing and the storefront shows another\n * with nothing reporting it. Re-emitting cannot help on its own — the event id is\n * `<offeringId>:<publishedAt>` and the unique index answers `duplicate`.\n *\n * ⚠️ **`quarantined: true` is in the filter, not the update.** An entry that is\n * merely pending keeps its `attempts`, and one already `sent` is never re-sent —\n * which is what keeps this from quietly becoming \"re-announce everything\", a\n * walk that would re-publish the whole fleet on every boot and un-quarantine\n * genuine poison each time.\n *\n * Not an `Outbox` method: the port is framework-free and shared by\n * every publisher, and this is a repair specific to the rebuild. `outboxDocument`\n * is exported beside it for the same class of reason.\n *\n * Answers whether an entry was actually revived.\n */\nexport const reviveQuarantined = (db: Db, eventId: string) =>\n Effect.tryPromise({\n try: async () => {\n const result = await db\n .collection<OutboxEntry>(OUTBOX_COLLECTION)\n .updateOne(\n { eventId, quarantined: true },\n {\n $set: { sent: false, quarantined: false, attempts: 0 },\n // The failure that put it here is spent; leaving it would make the\n // next quarantine's log name an error from a different outage.\n $unset: { lastError: '' },\n },\n );\n return result.modifiedCount === 1;\n },\n catch: error => translateMongoError(error),\n });\n\n/**\n * Ensures the three indexes the outbox depends on.\n *\n * The unique one is load-bearing rather than defensive: it *is* the idempotency\n * check behind the client-generated transaction id, so a replayed command is\n * rejected by the storage engine rather than by a read-then-write race. It is on\n * `eventId` — `<transactionId>:<step>` for a transaction — so the claim and the\n * bus's deduplication key are one value rather than two that can drift. The\n * partial one keeps the relay's `pending` query cheap once the collection fills\n * with sent entries; it filters on `quarantined` too, so an entry past its\n * ceiling leaves the index rather than being read and skipped forever.\n *\n * Mongo rejects a `createIndex` that reuses a key pattern with a different\n * `partialFilterExpression` (`IndexOptionsConflict`), and this runs on every\n * sweep and every create. A database that predates the `quarantined` filter\n * therefore fails here on every pass — which is loud only because the sweep now\n * logs what it catches. The fix is `pnpm run <app>:dev:reset`; nothing runs in\n * production, so there is no migration to write.\n */\nexport const ensureOutboxIndexes = (db: Db) =>\n Effect.tryPromise({\n try: async () => {\n const collection = db.collection(OUTBOX_COLLECTION);\n await collection.createIndex({ eventId: 1 }, { unique: true });\n await collection.createIndex(\n { createdAt: 1 },\n { partialFilterExpression: { sent: false, quarantined: false } },\n );\n // What the per-aggregate order reads, and what a rebuild finds an\n // aggregate's latest announced version by.\n await collection.createIndex({\n 'aggregate.type': 1,\n 'aggregate.id': 1,\n version: 1,\n });\n },\n catch: error => translateMongoError(error),\n });\n\n/**\n * Mongo-backed {@link Outbox} over one database.\n *\n * `db` is closed over, so every method's Effect has `R = never` — the same\n * technique `makeMongoRepository` uses. There is no publishing here: the relay\n * composes these methods with the event bus, which is what lets the relay be\n * tested without a broker.\n */\nexport const makeMongoOutbox = (db: Db): Outbox => {\n const collection = db.collection<OutboxEntry>(OUTBOX_COLLECTION);\n\n return {\n enqueue: event =>\n Effect.tryPromise({\n try: async () => {\n try {\n await collection.insertOne(outboxDocument(event));\n return 'enqueued' as const;\n } catch (error) {\n // Not a failure: the unique index rejected a second claim for this\n // message id, which is precisely how a retry is identified.\n if (isDuplicateKey(error)) {\n return 'duplicate' as const;\n }\n throw error;\n }\n },\n catch: error => translateMongoError(error),\n }),\n\n pending: limit =>\n Effect.tryPromise({\n // Oldest first, then by version: the relay publishes in this order\n // within each aggregate, so `accepted` reaches the bus before the\n // terminal event of the same transaction.\n try: () =>\n collection\n .find({ sent: false, quarantined: false }, WITHOUT_MONGO_ID)\n .sort({ createdAt: 1, version: 1 })\n .limit(limit)\n .toArray(),\n catch: error => translateMongoError(error),\n }),\n\n markSent: entry =>\n Effect.tryPromise({\n try: () =>\n collection.updateOne(\n { eventId: entry.eventId },\n { $set: { sent: true } },\n ),\n catch: error => translateMongoError(error),\n }).pipe(Effect.asVoid),\n\n stats: () =>\n Effect.tryPromise({\n // Two counts and one `findOne`, rather than reading the entries: the\n // pending set can be arbitrarily large when the relay is stuck, which\n // is exactly the moment this must stay cheap. Both queries ride the\n // partial index on `{ createdAt: 1 }` filtered to the same predicate.\n try: async () => {\n const pendingFilter = { sent: false, quarantined: false };\n const [pending, quarantined, oldest] = await Promise.all([\n collection.countDocuments(pendingFilter),\n collection.countDocuments({ quarantined: true }),\n collection.findOne(pendingFilter, {\n sort: { createdAt: 1 },\n projection: { _id: 0, createdAt: 1 },\n }),\n ]);\n\n return {\n pending,\n quarantined,\n // Absent rather than zero when the outbox is empty: an age of zero\n // and \"nothing is waiting\" are opposite conditions, and a gauge\n // that reports 0 for both is indistinguishable from a healthy relay\n // at exactly the moment it is not one.\n ...(oldest === null ? {} : { oldestPendingAt: oldest.createdAt }),\n };\n },\n catch: error => translateMongoError(error),\n }),\n\n recordFailure: (entry, error, quarantine) =>\n Effect.tryPromise({\n // `$inc` rather than a read-modify-write: two relays can be draining the\n // same tenant (the request's inline drain and the daemon sweep), and an\n // absolute write would let one of them lose the other's attempt and\n // stretch the ceiling indefinitely.\n try: () =>\n collection.updateOne(\n { eventId: entry.eventId },\n {\n $inc: { attempts: 1 },\n $set: { lastError: error, quarantined: quarantine },\n },\n ),\n catch: cause => translateMongoError(cause),\n }).pipe(Effect.asVoid),\n };\n};\n"],"names":["Effect","translateMongoError","OUTBOX_COLLECTION","WITHOUT_MONGO_ID","projection","_id","DUPLICATE_KEY","isDuplicateKey","error","code","outboxDocument","event","eventId","id","aggregate","version","sent","attempts","quarantined","createdAt","at","reviveQuarantined","db","tryPromise","try","result","collection","updateOne","$set","$unset","lastError","modifiedCount","catch","ensureOutboxIndexes","createIndex","unique","partialFilterExpression","makeMongoOutbox","enqueue","insertOne","pending","limit","find","sort","toArray","markSent","entry","pipe","asVoid","stats","pendingFilter","oldest","Promise","all","countDocuments","findOne","oldestPendingAt","recordFailure","quarantine","$inc","cause"],"mappings":";AACA,SAASA,MAAM,QAAQ,SAAS;AAGhC,SAASC,mBAAmB,QAAQ,qCAAqC;AAEzE;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,oBAAoB,SAAS;AAE1C,iDAAiD,GACjD,MAAMC,mBAAmB;IAAEC,YAAY;QAAEC,KAAK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C;gBAChB,qEAAqE;gBACrE,sEAAsE;gBACtE,oEAAoE;gBACpE,sEAAsE;gBACtEC,KAAK;oBACH,MAAM0B,gBAAgB;wBAAElC,MAAM;wBAAOE,aAAa;oBAAM;oBACxD,MAAM,CAACsB,SAAStB,aAAaiC,OAAO,GAAG,MAAMC,QAAQC,GAAG,CAAC;wBACvD3B,WAAW4B,cAAc,CAACJ;wBAC1BxB,WAAW4B,cAAc,CAAC;4BAAEpC,aAAa;wBAAK;wBAC9CQ,WAAW6B,OAAO,CAACL,eAAe;4BAChCP,MAAM;gCAAExB,WAAW;4BAAE;4BACrBf,YAAY;gCAAEC,KAAK;gCAAGc,WAAW;4BAAE;wBACrC;qBACD;oBAED,OAAO;wBACLqB;wBACAtB;uBAKIiC,WAAW,OAAO,CAAC,IAAI;wBAAEK,iBAAiBL,OAAOhC,SAAS;oBAAC;gBAEnE;gBACAa,OAAOxB,CAAAA,QAASP,oBAAoBO;YACtC;QAEFiD,eAAe,CAACX,OAAOtC,OAAOkD,aAC5B1D,OAAOuB,UAAU,CAAC;gBAChB,yEAAyE;gBACzE,wEAAwE;gBACxE,oEAAoE;gBACpE,oCAAoC;gBACpCC,KAAK,IACHE,WAAWC,SAAS,CAClB;wBAAEf,SAASkC,MAAMlC,OAAO;oBAAC,GACzB;wBACE+C,MAAM;4BAAE1C,UAAU;wBAAE;wBACpBW,MAAM;4BAAEE,WAAWtB;4BAAOU,aAAawC;wBAAW;oBACpD;gBAEJ1B,OAAO4B,CAAAA,QAAS3D,oBAAoB2D;YACtC,GAAGb,IAAI,CAAC/C,OAAOgD,MAAM;IACzB;AACF,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../src/outbox/store.ts"],"sourcesContent":["import type { Outbox, OutboxEntry, OutboxEvent } from '@entifix/transactions';\nimport { Effect } from 'effect';\nimport type { Db } from 'mongodb';\n\nimport { translateMongoError } from '../errors/translate-mongo-error.js';\n\n/**\n * The outbox collection, and it lives in the **same database as the entity it\n * describes** — never in a shared control-plane store.\n *\n * Two reasons, and the second only shows up later. Same database means the\n * entity write and its event are one single-database transaction, which stays a\n * single-*shard* transaction if this ever shards; a control-plane outbox would\n * be cross-database from the first commit. And an outbox holds event payloads:\n * a `TransactionEvent` carries no tenant data, but `catalog.published` carries a\n * whole offering and `order.placed` a whole receipt, and neither may land in the\n * control plane on its way to the bus.\n *\n * That rule is why this lives here rather than in one service. It applies\n * identically to a per-organization `tenant_<id>` and to a single platform-plane\n * database, and the second publisher is what turned a copy into a seam.\n */\nexport const OUTBOX_COLLECTION = 'outbox';\n\n/** Drop Mongo's internal `_id` from every read. */\nconst WITHOUT_MONGO_ID = { projection: { _id: 0 } } as const;\n\n/** Mongo's duplicate-key error, which is how a replayed command is recognised. */\nconst DUPLICATE_KEY = 11000;\n\nconst isDuplicateKey = (error: unknown): boolean =>\n typeof error === 'object' &&\n error !== null &&\n (error as { code?: unknown }).code === DUPLICATE_KEY;\n\n/**\n * The stored shape of an outbox entry.\n *\n * Exported because the `completed` entry is **not** written through the port:\n * it has to join the entity write's session to be atomic with it, and a session\n * cannot live in a framework-free contract. The handler inserts this document\n * itself; everything else goes through {@link makeMongoOutbox}.\n */\nexport const outboxDocument = (event: OutboxEvent): OutboxEntry => ({\n eventId: event.id,\n aggregate: event.aggregate,\n version: event.version,\n event,\n sent: false,\n // Defaulted here rather than at each write site because there are two of\n // them: the relay's `enqueue`, and the transaction handler's own insert\n // inside the entity's Mongo session. An entry missing `attempts` would sort\n // into `pending` and then fail `attempts + 1` arithmetic on a `undefined`.\n attempts: 0,\n quarantined: false,\n createdAt: event.at,\n});\n\n/**\n * Puts a **quarantined** entry back in the queue, and touches nothing else.\n *\n * A rebuild walk's repair for the one failure measured on a live lab: with the\n * broker down long enough, the relay spends `outbox.maxAttempts` on an\n * announcement and quarantines it (the deliberate skip-so-the-head-moves),\n * after which the tenant store reads one thing and the storefront shows another\n * with nothing reporting it. Re-emitting cannot help on its own — the event id is\n * `<offeringId>:<publishedAt>` and the unique index answers `duplicate`.\n *\n * ⚠️ **`quarantined: true` is in the filter, not the update.** An entry that is\n * merely pending keeps its `attempts`, and one already `sent` is never re-sent —\n * which is what keeps this from quietly becoming \"re-announce everything\", a\n * walk that would re-publish the whole fleet on every boot and un-quarantine\n * genuine poison each time.\n *\n * Not an `Outbox` method: the port is framework-free and shared by\n * every publisher, and this is a repair specific to the rebuild. `outboxDocument`\n * is exported beside it for the same class of reason.\n *\n * Answers whether an entry was actually revived.\n */\nexport const reviveQuarantined = (db: Db, eventId: string) =>\n Effect.tryPromise({\n try: async () => {\n const result = await db\n .collection<OutboxEntry>(OUTBOX_COLLECTION)\n .updateOne(\n { eventId, quarantined: true },\n {\n $set: { sent: false, quarantined: false, attempts: 0 },\n // The failure that put it here is spent; leaving it would make the\n // next quarantine's log name an error from a different outage.\n $unset: { lastError: '' },\n },\n );\n return result.modifiedCount === 1;\n },\n catch: error => translateMongoError(error),\n });\n\n/**\n * Ensures the three indexes the outbox depends on.\n *\n * The unique one is load-bearing rather than defensive: it *is* the idempotency\n * check behind the client-generated transaction id, so a replayed command is\n * rejected by the storage engine rather than by a read-then-write race. It is on\n * `eventId` — `<transactionId>:<step>` for a transaction — so the claim and the\n * bus's deduplication key are one value rather than two that can drift. The\n * partial one keeps the relay's `pending` query cheap once the collection fills\n * with sent entries; it filters on `quarantined` too, so an entry past its\n * ceiling leaves the index rather than being read and skipped forever.\n *\n * Mongo rejects a `createIndex` that reuses a key pattern with a different\n * `partialFilterExpression` (`IndexOptionsConflict`), and this runs on every\n * sweep and every create. A database that predates the `quarantined` filter\n * therefore fails here on every pass — which is loud only because the sweep now\n * logs what it catches. The fix is `pnpm run <app>:dev:reset`; nothing runs in\n * production, so there is no migration to write.\n */\nexport const ensureOutboxIndexes = (db: Db) =>\n Effect.tryPromise({\n try: async () => {\n const collection = db.collection(OUTBOX_COLLECTION);\n await collection.createIndex({ eventId: 1 }, { unique: true });\n await collection.createIndex(\n { createdAt: 1 },\n { partialFilterExpression: { sent: false, quarantined: false } },\n );\n // What the per-aggregate order reads, and what a rebuild finds an\n // aggregate's latest announced version by.\n await collection.createIndex({\n 'aggregate.type': 1,\n 'aggregate.id': 1,\n version: 1,\n });\n },\n catch: error => translateMongoError(error),\n });\n\n/**\n * Mongo-backed {@link Outbox} over one database.\n *\n * `db` is closed over, so every method's Effect has `R = never` — the same\n * technique `makeMongoRepository` uses. There is no publishing here: the relay\n * composes these methods with the event bus, which is what lets the relay be\n * tested without a broker.\n */\nexport const makeMongoOutbox = (db: Db): Outbox => {\n const collection = db.collection<OutboxEntry>(OUTBOX_COLLECTION);\n\n return {\n enqueue: event =>\n Effect.tryPromise({\n try: async () => {\n try {\n await collection.insertOne(outboxDocument(event));\n return 'enqueued' as const;\n } catch (error) {\n // Not a failure: the unique index rejected a second claim for this\n // message id, which is precisely how a retry is identified.\n if (isDuplicateKey(error)) {\n return 'duplicate' as const;\n }\n throw error;\n }\n },\n catch: error => translateMongoError(error),\n }),\n\n pending: limit =>\n Effect.tryPromise({\n // Oldest first, then by version: the relay publishes in this order\n // within each aggregate, so `accepted` reaches the bus before the\n // terminal event of the same transaction.\n try: () =>\n collection\n .find({ sent: false, quarantined: false }, WITHOUT_MONGO_ID)\n .sort({ createdAt: 1, version: 1 })\n .limit(limit)\n .toArray(),\n catch: error => translateMongoError(error),\n }),\n\n markSent: entry =>\n Effect.tryPromise({\n try: () =>\n collection.updateOne(\n { eventId: entry.eventId },\n { $set: { sent: true } },\n ),\n catch: error => translateMongoError(error),\n }).pipe(Effect.asVoid),\n\n stats: () =>\n Effect.tryPromise({\n // Two counts and one `findOne`, rather than reading the entries: the\n // pending set can be arbitrarily large when the relay is stuck, which\n // is exactly the moment this must stay cheap. Both queries ride the\n // partial index on `{ createdAt: 1 }` filtered to the same predicate.\n try: async () => {\n const pendingFilter = { sent: false, quarantined: false };\n const [pending, quarantined, oldest] = await Promise.all([\n collection.countDocuments(pendingFilter),\n collection.countDocuments({ quarantined: true }),\n collection.findOne(pendingFilter, {\n sort: { createdAt: 1 },\n projection: { _id: 0, createdAt: 1 },\n }),\n ]);\n\n return {\n pending,\n quarantined,\n // Absent rather than zero when the outbox is empty: an age of zero\n // and \"nothing is waiting\" are opposite conditions, and a gauge\n // that reports 0 for both is indistinguishable from a healthy relay\n // at exactly the moment it is not one.\n ...(oldest === null ? {} : { oldestPendingAt: oldest.createdAt }),\n };\n },\n catch: error => translateMongoError(error),\n }),\n\n recordFailure: (entry, error, quarantine) =>\n Effect.tryPromise({\n // `$inc` rather than a read-modify-write: two relays can be draining the\n // same tenant (the request's inline drain and the daemon sweep), and an\n // absolute write would let one of them lose the other's attempt and\n // stretch the ceiling indefinitely.\n try: () =>\n collection.updateOne(\n { eventId: entry.eventId },\n {\n $inc: { attempts: 1 },\n $set: { lastError: error, quarantined: quarantine },\n },\n ),\n catch: cause => translateMongoError(cause),\n }).pipe(Effect.asVoid),\n // No lease to give back here: `pending` reads without claiming, so the\n // next pass sees the entry again by itself.\n hold: (entry, reason) =>\n Effect.tryPromise({\n try: () =>\n collection.updateOne(\n { eventId: entry.eventId },\n { $set: { lastError: reason } },\n ),\n catch: cause => translateMongoError(cause),\n }).pipe(Effect.asVoid),\n };\n};\n"],"names":["Effect","translateMongoError","OUTBOX_COLLECTION","WITHOUT_MONGO_ID","projection","_id","DUPLICATE_KEY","isDuplicateKey","error","code","outboxDocument","event","eventId","id","aggregate","version","sent","attempts","quarantined","createdAt","at","reviveQuarantined","db","tryPromise","try","result","collection","updateOne","$set","$unset","lastError","modifiedCount","catch","ensureOutboxIndexes","createIndex","unique","partialFilterExpression","makeMongoOutbox","enqueue","insertOne","pending","limit","find","sort","toArray","markSent","entry","pipe","asVoid","stats","pendingFilter","oldest","Promise","all","countDocuments","findOne","oldestPendingAt","recordFailure","quarantine","$inc","cause","hold","reason"],"mappings":";AACA,SAASA,MAAM,QAAQ,SAAS;AAGhC,SAASC,mBAAmB,QAAQ,qCAAqC;AAEzE;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,oB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zB;wBAAEgB,MAAM;4BAAEE,WAAWgC;wBAAO;oBAAE;gBAElC9B,OAAO4B,CAAAA,QAAS3D,oBAAoB2D;YACtC,GAAGb,IAAI,CAAC/C,OAAOgD,MAAM;IACzB;AACF,EAAE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@entifix/mongo",
|
|
3
|
-
"version": "0.23.
|
|
3
|
+
"version": "0.23.13",
|
|
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.9.0",
|
|
60
|
-
"@entifix/business": "0.23.
|
|
61
|
-
"@entifix/core": "0.23.
|
|
60
|
+
"@entifix/business": "0.23.13",
|
|
61
|
+
"@entifix/core": "0.23.13"
|
|
62
62
|
},
|
|
63
63
|
"devDependencies": {
|
|
64
64
|
"effect": "4.0.7",
|
|
65
|
-
"@entifix/testing-unit": "0.23.
|
|
66
|
-
"@entifix/transactions": "0.23.
|
|
65
|
+
"@entifix/testing-unit": "0.23.13",
|
|
66
|
+
"@entifix/transactions": "0.23.13"
|
|
67
67
|
},
|
|
68
68
|
"peerDependencies": {
|
|
69
69
|
"effect": "^4.0.7",
|
|
70
|
-
"@entifix/transactions": "0.23.
|
|
70
|
+
"@entifix/transactions": "0.23.13"
|
|
71
71
|
},
|
|
72
72
|
"peerDependenciesMeta": {
|
|
73
73
|
"@entifix/transactions": {
|