@entifix/mongo 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.
@@ -1,4 +1,16 @@
1
1
  import { type Entity, type EntityFiltering, type EntitySorting } from '@entifix/core';
2
+ /**
3
+ * The field a relevance load computes and sorts by, dropped before the
4
+ * records are read back (ADR 0033).
5
+ */
6
+ export declare const RELEVANCE_FIELD = "__relevance";
7
+ /**
8
+ * How well a record's label answers each word, as an aggregation expression:
9
+ * the prefix, word and elsewhere weights of {@link RELEVANCE_PREFIX} and its
10
+ * siblings, accent-blind through the same folded pattern `like` matches with.
11
+ * No label or no words is `0` for every record.
12
+ */
13
+ export declare function relevanceExpression(labelKey: string | undefined, terms: readonly string[]): unknown;
2
14
  /** A Mongo query document (`{ field: condition, $and: [...], ... }`). */
3
15
  export type MongoFilter = Record<string, unknown>;
4
16
  /** A Mongo sort document (`{ field: 1 | -1 }`). */
@@ -1 +1 @@
1
- {"version":3,"file":"filter-translator.d.ts","sourceRoot":"","sources":["../../src/adapters/filter-translator.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,MAAM,EAEX,KAAK,eAAe,EACpB,KAAK,aAAa,EAGnB,MAAM,eAAe,CAAC;AAEvB,yEAAyE;AACzE,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAClD,mDAAmD;AACnD,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AAsE/C;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,SAAS,MAAM,EACvD,SAAS,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,EAAE,GACrC,WAAW,CAiBb;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,SAAS,MAAM,EACrD,OAAO,CAAC,EAAE,aAAa,CAAC,OAAO,CAAC,EAAE,GACjC,SAAS,CAgBX"}
1
+ {"version":3,"file":"filter-translator.d.ts","sourceRoot":"","sources":["../../src/adapters/filter-translator.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,MAAM,EAEX,KAAK,eAAe,EACpB,KAAK,aAAa,EAOnB,MAAM,eAAe,CAAC;AAEvB;;;GAGG;AACH,eAAO,MAAM,eAAe,gBAAgB,CAAC;AAE7C;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,KAAK,EAAE,SAAS,MAAM,EAAE,GACvB,OAAO,CAuBT;AAED,yEAAyE;AACzE,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAClD,mDAAmD;AACnD,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AAsE/C;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,SAAS,MAAM,EACvD,SAAS,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,EAAE,GACrC,WAAW,CAiBb;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,SAAS,MAAM,EACrD,OAAO,CAAC,EAAE,aAAa,CAAC,OAAO,CAAC,EAAE,GACjC,SAAS,CAkBX"}
@@ -1,4 +1,41 @@
1
- import { foldedPattern } from '@entifix/core';
1
+ import { foldedPattern, isRelevance, RELEVANCE_ELSEWHERE, RELEVANCE_PREFIX, RELEVANCE_WORD } from '@entifix/core';
2
+ /**
3
+ * The field a relevance load computes and sorts by, dropped before the
4
+ * records are read back (ADR 0033).
5
+ */ export const RELEVANCE_FIELD = '__relevance';
6
+ /**
7
+ * How well a record's label answers each word, as an aggregation expression:
8
+ * the prefix, word and elsewhere weights of {@link RELEVANCE_PREFIX} and its
9
+ * siblings, accent-blind through the same folded pattern `like` matches with.
10
+ * No label or no words is `0` for every record.
11
+ */ export function relevanceExpression(labelKey, terms) {
12
+ if (labelKey === undefined || terms.length === 0) return 0;
13
+ const tested = (regex)=>({
14
+ $regexMatch: {
15
+ input: `$${labelKey}`,
16
+ regex,
17
+ options: 'i'
18
+ }
19
+ });
20
+ return {
21
+ $add: terms.map((term)=>{
22
+ const pattern = foldedPattern(term);
23
+ return {
24
+ $cond: [
25
+ tested(`^${pattern}`),
26
+ RELEVANCE_PREFIX,
27
+ {
28
+ $cond: [
29
+ tested(`(^| )${pattern}`),
30
+ RELEVANCE_WORD,
31
+ RELEVANCE_ELSEWHERE
32
+ ]
33
+ }
34
+ ]
35
+ };
36
+ })
37
+ };
38
+ }
2
39
  const BINARY_OPERATORS = {
3
40
  eq: '$eq',
4
41
  ne: '$ne',
@@ -133,7 +170,9 @@ function translateNode(node) {
133
170
  for (const priority of Object.keys(record).map(Number).sort((a, b)=>a - b)){
134
171
  const entry = record[priority];
135
172
  if (entry) {
136
- sort[String(entry.property)] = entry.type === 'desc' ? -1 : 1;
173
+ // Relevance is a computed field, best first, whatever was asked.
174
+ if (isRelevance(entry.property)) sort[RELEVANCE_FIELD] = -1;
175
+ else sort[String(entry.property)] = entry.type === 'desc' ? -1 : 1;
137
176
  }
138
177
  }
139
178
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/adapters/filter-translator.ts"],"sourcesContent":["import {\n type Entity,\n type EntityFilter,\n type EntityFiltering,\n type EntitySorting,\n type FilterGroup,\n foldedPattern,\n} from '@entifix/core';\n\n/** A Mongo query document (`{ field: condition, $and: [...], ... }`). */\nexport type MongoFilter = Record<string, unknown>;\n/** A Mongo sort document (`{ field: 1 | -1 }`). */\nexport type MongoSort = Record<string, 1 | -1>;\n\nconst BINARY_OPERATORS: Record<string, string> = {\n eq: '$eq',\n ne: '$ne',\n gt: '$gt',\n gte: '$gte',\n lt: '$lt',\n lte: '$lte',\n};\n\nfunction isFilterGroup<TEntity extends Entity>(\n node: EntityFilter<TEntity> | FilterGroup<TEntity>,\n): node is FilterGroup<TEntity> {\n // A group carries `values` + a logic operator and, unlike the array filter,\n // has no `property`.\n return (\n !('property' in node) && (node.operator === 'and' || node.operator === 'or')\n );\n}\n\nfunction translateNode<TEntity extends Entity>(\n node: EntityFilter<TEntity> | FilterGroup<TEntity>,\n): MongoFilter {\n if (isFilterGroup(node)) {\n const clause = node.operator === 'or' ? '$or' : '$and';\n return { [clause]: node.values.map(translateNode) };\n }\n\n const field = String(node.property);\n\n switch (node.operator) {\n case 'eq':\n case 'ne':\n case 'gt':\n case 'gte':\n case 'lt':\n case 'lte':\n return { [field]: { [BINARY_OPERATORS[node.operator]]: node.value } };\n case 'in':\n return { [field]: { $in: node.values } };\n case 'nin':\n return { [field]: { $nin: node.values } };\n case 'between':\n return { [field]: { $gte: node.start, $lte: node.end } };\n case 'nbetween':\n return { [field]: { $not: { $gte: node.start, $lte: node.end } } };\n case 'like':\n // A stored value cannot be folded in a `find`, and a collation does not\n // reach `$regex` — so the query is widened instead: each letter becomes\n // the class of its accented forms, both cases listed (`fold.ts`).\n return { [field]: { $regex: foldedPattern(node.value), $options: 'i' } };\n case 'nlike':\n return {\n [field]: {\n $not: { $regex: foldedPattern(node.value), $options: 'i' },\n },\n };\n case 'isNull':\n return { [field]: { $eq: null } };\n case 'isNotNull':\n return { [field]: { $ne: null } };\n default: {\n // Exhaustiveness guard — a new operator must be handled explicitly.\n const _never: never = node;\n return _never;\n }\n }\n}\n\n/**\n * Translates the request's `filtering` (an array of {@link EntityFiltering},\n * each a single filter, an array of filters, or a {@link FilterGroup}) into a\n * single Mongo query document. Every top-level entry is combined with `$and`;\n * an empty/absent filtering yields the match-all `{}`.\n */\nexport function translateFiltering<TEntity extends Entity>(\n filtering?: EntityFiltering<TEntity>[],\n): MongoFilter {\n if (!filtering || filtering.length === 0) {\n return {};\n }\n\n const clauses: MongoFilter[] = [];\n for (const entry of filtering) {\n if (Array.isArray(entry)) {\n clauses.push(...entry.map(translateNode));\n } else {\n clauses.push(translateNode(entry));\n }\n }\n\n if (clauses.length === 0) return {};\n if (clauses.length === 1) return clauses[0];\n return { $and: clauses };\n}\n\n/**\n * Translates the request's `sorting` (an array of {@link EntitySorting} records,\n * each keyed by numeric priority) into a Mongo sort document, preserving the\n * numeric ordering within each record.\n */\nexport function translateSorting<TEntity extends Entity>(\n sorting?: EntitySorting<TEntity>[],\n): MongoSort {\n const sort: MongoSort = {};\n if (!sorting) return sort;\n\n for (const record of sorting) {\n for (const priority of Object.keys(record)\n .map(Number)\n .sort((a, b) => a - b)) {\n const entry = record[priority];\n if (entry) {\n sort[String(entry.property)] = entry.type === 'desc' ? -1 : 1;\n }\n }\n }\n\n return sort;\n}\n"],"names":["foldedPattern","BINARY_OPERATORS","eq","ne","gt","gte","lt","lte","isFilterGroup","node","operator","translateNode","clause","values","map","field","String","property","value","$in","$nin","$gte","start","$lte","end","$not","$regex","$options","$eq","$ne","_never","translateFiltering","filtering","length","clauses","entry","Array","isArray","push","$and","translateSorting","sorting","sort","record","priority","Object","keys","Number","a","b","type"],"mappings":"AAAA,SAMEA,aAAa,QACR,gBAAgB;AAOvB,MAAMC,mBAA2C;IAC/CC,IAAI;IACJC,IAAI;IACJC,IAAI;IACJC,KAAK;IACLC,IAAI;IACJC,KAAK;AACP;AAEA,SAASC,cACPC,IAAkD;IAElD,4EAA4E;IAC5E,qBAAqB;IACrB,OACE,CAAE,CAAA,cAAcA,IAAG,KAAOA,CAAAA,KAAKC,QAAQ,KAAK,SAASD,KAAKC,QAAQ,KAAK,IAAG;AAE9E;AAEA,SAASC,cACPF,IAAkD;IAElD,IAAID,cAAcC,OAAO;QACvB,MAAMG,SAASH,KAAKC,QAAQ,KAAK,OAAO,QAAQ;QAChD,OAAO;YAAE,CAACE,OAAO,EAAEH,KAAKI,MAAM,CAACC,GAAG,CAACH;QAAe;IACpD;IAEA,MAAMI,QAAQC,OAAOP,KAAKQ,QAAQ;IAElC,OAAQR,KAAKC,QAAQ;QACnB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;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,MAAMC,UAAyB,EAAE;IACjC,KAAK,MAAMC,SAASH,UAAW;QAC7B,IAAII,MAAMC,OAAO,CAACF,QAAQ;YACxBD,QAAQI,IAAI,IAAIH,MAAMrB,GAAG,CAACH;QAC5B,OAAO;YACLuB,QAAQI,IAAI,CAAC3B,cAAcwB;QAC7B;IACF;IAEA,IAAID,QAAQD,MAAM,KAAK,GAAG,OAAO,CAAC;IAClC,IAAIC,QAAQD,MAAM,KAAK,GAAG,OAAOC,OAAO,CAAC,EAAE;IAC3C,OAAO;QAAEK,MAAML;IAAQ;AACzB;AAEA;;;;CAIC,GACD,OAAO,SAASM,iBACdC,OAAkC;IAElC,MAAMC,OAAkB,CAAC;IACzB,IAAI,CAACD,SAAS,OAAOC;IAErB,KAAK,MAAMC,UAAUF,QAAS;QAC5B,KAAK,MAAMG,YAAYC,OAAOC,IAAI,CAACH,QAChC7B,GAAG,CAACiC,QACJL,IAAI,CAAC,CAACM,GAAGC,IAAMD,IAAIC,GAAI;YACxB,MAAMd,QAAQQ,MAAM,CAACC,SAAS;YAC9B,IAAIT,OAAO;gBACTO,IAAI,CAAC1B,OAAOmB,MAAMlB,QAAQ,EAAE,GAAGkB,MAAMe,IAAI,KAAK,SAAS,CAAC,IAAI;YAC9D;QACF;IACF;IAEA,OAAOR;AACT"}
1
+ {"version":3,"sources":["../../src/adapters/filter-translator.ts"],"sourcesContent":["import {\n type Entity,\n type EntityFilter,\n type EntityFiltering,\n type EntitySorting,\n type FilterGroup,\n foldedPattern,\n isRelevance,\n RELEVANCE_ELSEWHERE,\n RELEVANCE_PREFIX,\n RELEVANCE_WORD,\n} from '@entifix/core';\n\n/**\n * The field a relevance load computes and sorts by, dropped before the\n * records are read back (ADR 0033).\n */\nexport const RELEVANCE_FIELD = '__relevance';\n\n/**\n * How well a record's label answers each word, as an aggregation expression:\n * the prefix, word and elsewhere weights of {@link RELEVANCE_PREFIX} and its\n * siblings, accent-blind through the same folded pattern `like` matches with.\n * No label or no words is `0` for every record.\n */\nexport function relevanceExpression(\n labelKey: string | undefined,\n terms: readonly string[],\n): unknown {\n if (labelKey === undefined || terms.length === 0) return 0;\n const tested = (regex: string) => ({\n $regexMatch: { input: `$${labelKey}`, regex, options: 'i' },\n });\n return {\n $add: terms.map(term => {\n const pattern = foldedPattern(term);\n return {\n $cond: [\n tested(`^${pattern}`),\n RELEVANCE_PREFIX,\n {\n $cond: [\n tested(`(^| )${pattern}`),\n RELEVANCE_WORD,\n RELEVANCE_ELSEWHERE,\n ],\n },\n ],\n };\n }),\n };\n}\n\n/** A Mongo query document (`{ field: condition, $and: [...], ... }`). */\nexport type MongoFilter = Record<string, unknown>;\n/** A Mongo sort document (`{ field: 1 | -1 }`). */\nexport type MongoSort = Record<string, 1 | -1>;\n\nconst BINARY_OPERATORS: Record<string, string> = {\n eq: '$eq',\n ne: '$ne',\n gt: '$gt',\n gte: '$gte',\n lt: '$lt',\n lte: '$lte',\n};\n\nfunction isFilterGroup<TEntity extends Entity>(\n node: EntityFilter<TEntity> | FilterGroup<TEntity>,\n): node is FilterGroup<TEntity> {\n // A group carries `values` + a logic operator and, unlike the array filter,\n // has no `property`.\n return (\n !('property' in node) && (node.operator === 'and' || node.operator === 'or')\n );\n}\n\nfunction translateNode<TEntity extends Entity>(\n node: EntityFilter<TEntity> | FilterGroup<TEntity>,\n): MongoFilter {\n if (isFilterGroup(node)) {\n const clause = node.operator === 'or' ? '$or' : '$and';\n return { [clause]: node.values.map(translateNode) };\n }\n\n const field = String(node.property);\n\n switch (node.operator) {\n case 'eq':\n case 'ne':\n case 'gt':\n case 'gte':\n case 'lt':\n case 'lte':\n return { [field]: { [BINARY_OPERATORS[node.operator]]: node.value } };\n case 'in':\n return { [field]: { $in: node.values } };\n case 'nin':\n return { [field]: { $nin: node.values } };\n case 'between':\n return { [field]: { $gte: node.start, $lte: node.end } };\n case 'nbetween':\n return { [field]: { $not: { $gte: node.start, $lte: node.end } } };\n case 'like':\n // A stored value cannot be folded in a `find`, and a collation does not\n // reach `$regex` — so the query is widened instead: each letter becomes\n // the class of its accented forms, both cases listed (`fold.ts`).\n return { [field]: { $regex: foldedPattern(node.value), $options: 'i' } };\n case 'nlike':\n return {\n [field]: {\n $not: { $regex: foldedPattern(node.value), $options: 'i' },\n },\n };\n case 'isNull':\n return { [field]: { $eq: null } };\n case 'isNotNull':\n return { [field]: { $ne: null } };\n default: {\n // Exhaustiveness guard — a new operator must be handled explicitly.\n const _never: never = node;\n return _never;\n }\n }\n}\n\n/**\n * Translates the request's `filtering` (an array of {@link EntityFiltering},\n * each a single filter, an array of filters, or a {@link FilterGroup}) into a\n * single Mongo query document. Every top-level entry is combined with `$and`;\n * an empty/absent filtering yields the match-all `{}`.\n */\nexport function translateFiltering<TEntity extends Entity>(\n filtering?: EntityFiltering<TEntity>[],\n): MongoFilter {\n if (!filtering || filtering.length === 0) {\n return {};\n }\n\n const clauses: MongoFilter[] = [];\n for (const entry of filtering) {\n if (Array.isArray(entry)) {\n clauses.push(...entry.map(translateNode));\n } else {\n clauses.push(translateNode(entry));\n }\n }\n\n if (clauses.length === 0) return {};\n if (clauses.length === 1) return clauses[0];\n return { $and: clauses };\n}\n\n/**\n * Translates the request's `sorting` (an array of {@link EntitySorting} records,\n * each keyed by numeric priority) into a Mongo sort document, preserving the\n * numeric ordering within each record.\n */\nexport function translateSorting<TEntity extends Entity>(\n sorting?: EntitySorting<TEntity>[],\n): MongoSort {\n const sort: MongoSort = {};\n if (!sorting) return sort;\n\n for (const record of sorting) {\n for (const priority of Object.keys(record)\n .map(Number)\n .sort((a, b) => a - b)) {\n const entry = record[priority];\n if (entry) {\n // Relevance is a computed field, best first, whatever was asked.\n if (isRelevance(entry.property)) sort[RELEVANCE_FIELD] = -1;\n else sort[String(entry.property)] = entry.type === 'desc' ? -1 : 1;\n }\n }\n }\n\n return sort;\n}\n"],"names":["foldedPattern","isRelevance","RELEVANCE_ELSEWHERE","RELEVANCE_PREFIX","RELEVANCE_WORD","RELEVANCE_FIELD","relevanceExpression","labelKey","terms","undefined","length","tested","regex","$regexMatch","input","options","$add","map","term","pattern","$cond","BINARY_OPERATORS","eq","ne","gt","gte","lt","lte","isFilterGroup","node","operator","translateNode","clause","values","field","String","property","value","$in","$nin","$gte","start","$lte","end","$not","$regex","$options","$eq","$ne","_never","translateFiltering","filtering","clauses","entry","Array","isArray","push","$and","translateSorting","sorting","sort","record","priority","Object","keys","Number","a","b","type"],"mappings":"AAAA,SAMEA,aAAa,EACbC,WAAW,EACXC,mBAAmB,EACnBC,gBAAgB,EAChBC,cAAc,QACT,gBAAgB;AAEvB;;;CAGC,GACD,OAAO,MAAMC,kBAAkB,cAAc;AAE7C;;;;;CAKC,GACD,OAAO,SAASC,oBACdC,QAA4B,EAC5BC,KAAwB;IAExB,IAAID,aAAaE,aAAaD,MAAME,MAAM,KAAK,GAAG,OAAO;IACzD,MAAMC,SAAS,CAACC,QAAmB,CAAA;YACjCC,aAAa;gBAAEC,OAAO,CAAC,CAAC,EAAEP,UAAU;gBAAEK;gBAAOG,SAAS;YAAI;QAC5D,CAAA;IACA,OAAO;QACLC,MAAMR,MAAMS,GAAG,CAACC,CAAAA;YACd,MAAMC,UAAUnB,cAAckB;YAC9B,OAAO;gBACLE,OAAO;oBACLT,OAAO,CAAC,CAAC,EAAEQ,SAAS;oBACpBhB;oBACA;wBACEiB,OAAO;4BACLT,OAAO,CAAC,KAAK,EAAEQ,SAAS;4BACxBf;4BACAF;yBACD;oBACH;iBACD;YACH;QACF;IACF;AACF;AAOA,MAAMmB,mBAA2C;IAC/CC,IAAI;IACJC,IAAI;IACJC,IAAI;IACJC,KAAK;IACLC,IAAI;IACJC,KAAK;AACP;AAEA,SAASC,cACPC,IAAkD;IAElD,4EAA4E;IAC5E,qBAAqB;IACrB,OACE,CAAE,CAAA,cAAcA,IAAG,KAAOA,CAAAA,KAAKC,QAAQ,KAAK,SAASD,KAAKC,QAAQ,KAAK,IAAG;AAE9E;AAEA,SAASC,cACPF,IAAkD;IAElD,IAAID,cAAcC,OA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oot":"","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
+ {"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,EAelB,MAAM,eAAe,CAAC;AAEvB,OAAO,KAAK,EAAE,aAAa,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAajD,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,CAwRlB"}
@@ -1,9 +1,9 @@
1
1
  import { _ as _extends } from "@swc/helpers/_/_extends";
2
2
  import { randomUUID } from 'node:crypto';
3
- import { declaresRevision, deserializeEntityCollection, deserializeSingleEntity, extractMetaEntity, holdsStoredState, NotFound, readRevision, serializeEntity, StaleRevision, storedStateCondition, unavailableInState } from '@entifix/core';
3
+ import { declaresRevision, deserializeEntityCollection, deserializeSingleEntity, extractMetaEntity, holdsStoredState, NotFound, readRevision, relevanceLabelKey, relevanceTerms, serializeEntity, StaleRevision, storedStateCondition, unavailableInState } from '@entifix/core';
4
4
  import { Effect } from 'effect';
5
5
  import { translateMongoError } from '../errors/translate-mongo-error.js';
6
- import { translateFiltering, translateSorting } from './filter-translator.js';
6
+ import { RELEVANCE_FIELD, relevanceExpression, translateFiltering, translateSorting } from './filter-translator.js';
7
7
  /** Projection that drops Mongo's internal `_id` from read results. */ const WITHOUT_MONGO_ID = {
8
8
  projection: {
9
9
  _id: 0
@@ -69,8 +69,35 @@ function toEntityId(entityOrId) {
69
69
  const page = (_request_page = request.page) != null ? _request_page : 1;
70
70
  const pageSize = (_request_pageSize = request.pageSize) != null ? _request_pageSize : 10;
71
71
  const skip = (page - 1) * pageSize;
72
+ // A relevance order is a field computed from the request's own words,
73
+ // which a `find` cannot sort by: the same page through a pipeline
74
+ // (ADR 0033).
72
75
  const docs = yield* Effect.tryPromise({
73
- try: ()=>collection.find(filter, _extends({}, WITHOUT_MONGO_ID, inSession)).sort(sort).skip(skip).limit(pageSize).toArray(),
76
+ try: ()=>RELEVANCE_FIELD in sort ? collection.aggregate([
77
+ {
78
+ $match: filter
79
+ },
80
+ {
81
+ $addFields: {
82
+ [RELEVANCE_FIELD]: relevanceExpression(relevanceLabelKey(entityConstructor), relevanceTerms(request.filtering))
83
+ }
84
+ },
85
+ {
86
+ $sort: sort
87
+ },
88
+ {
89
+ $skip: skip
90
+ },
91
+ {
92
+ $limit: pageSize
93
+ },
94
+ {
95
+ $project: {
96
+ _id: 0,
97
+ [RELEVANCE_FIELD]: 0
98
+ }
99
+ }
100
+ ], inSession).toArray() : collection.find(filter, _extends({}, WITHOUT_MONGO_ID, inSession)).sort(sort).skip(skip).limit(pageSize).toArray(),
74
101
  catch: (error)=>translateMongoError(error)
75
102
  });
76
103
  const total = yield* Effect.tryPromise({
@@ -1 +1 @@
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,gFAAgF,GAChF,OAAO,SAASC,oBACdC,iBAA6C;QAGtCC;IADP,MAAMA,aAAajB,kBAAkBgB;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,IAAIO;QAChDP,iBAAiBQ,GAAG,CAACL,IAAIE;QACzB,IAAIA,QAAQI,GAAG,CAACV,OAAO,OAAOX,OAAOsB,IAAI;QACzC,OAAOtB,OAAOuB,UAAU,CAAC;YACvBC,KAAK,IAAMT,GAAGU,UAAU,CAACd,MAAMe,WA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B,CAAmBxB,SACvC7D,OAAO4C,GAAG,CAAC;gBASEiB;YARX,MAAMF,MAAM/D,gBACVY,mBACAqD;YAEF,uEAAuE;YACvE,sEAAsE;YACtE,8DAA8D;YAC9D,sDAAsD;YACtD,MAAMlC,MAAKkC,aAAAA,OAAOlC,EAAE,YAATkC,aAAazE;YACxB,OAAOY,OAAOuB,UAAU,CAAC;gBACvB,+DAA+D;gBAC/D,uDAAuD;gBACvDC,KAAK,IACHC,WAAWuD,UAAU,CACnB;wBAAErD;oBAAG,GACL,aAAKgC;wBAAKhC;wBACV;wBAAE4D,QAAQ;uBAAS/C;gBAEvBX,OAAOC,CAAAA,QAAS7B,oBAAoB6B;YACtC;YACA+B,OAAOlC,EAAE,GAAGA;YACZ,OAAOkC;QACT;IAEF,MAAM2B,MAAM,CACVpD,YACAE,UAEAtC,OAAO4C,GAAG,CAAC;YACT,MAAMjB,KAAKQ,WAAWC;YACtB,MAAMgC,YAAYH,YAAY3B;YAC9B,MAAMyC,SAAS,OAAO/E,OAAOuB,UAAU,CAAC;gBACtCC,KAAK,IACHC,WAAWgE,SAAS,CAAC;wBAAE9D;uBAAOwC,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
+ {"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 relevanceLabelKey,\n relevanceTerms,\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 {\n RELEVANCE_FIELD,\n relevanceExpression,\n translateFiltering,\n translateSorting,\n} 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 // A relevance order is a field computed from the request's own words,\n // which a `find` cannot sort by: the same page through a pipeline\n // (ADR 0033).\n const docs = yield* Effect.tryPromise({\n try: () =>\n RELEVANCE_FIELD in sort\n ? collection\n .aggregate(\n [\n { $match: filter },\n {\n $addFields: {\n [RELEVANCE_FIELD]: relevanceExpression(\n relevanceLabelKey(entityConstructor),\n relevanceTerms(request.filtering),\n ),\n },\n },\n { $sort: sort },\n { $skip: skip },\n { $limit: pageSize },\n { $project: { _id: 0, [RELEVANCE_FIELD]: 0 } },\n ],\n inSession,\n )\n .toArray()\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","relevanceLabelKey","relevanceTerms","serializeEntity","StaleRevision","storedStateCondition","unavailableInState","Effect","translateMongoError","RELEVANCE_FIELD","relevanceExpression","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","aggregate","$match","$addFields","$sort","$skip","$limit","$project","toArray","find","limit","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,iBAAiB,EACjBC,cAAc,EACdC,eAAe,EACfC,aAAa,EAEbC,oBAAoB,EACpBC,kBAAkB,QACb,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAGhC,SAASC,mBAAmB,QAAQ,qCAAqC;AACzE,SACEC,eAAe,EACfC,mBAAmB,EACnBC,kBAAkB,EAClBC,gBAAgB,QACX,yBAAyB;AAEhC,oEAAoE,GACpE,MAAMC,mBAAmB;IAAEC,YAAY;QAAEC,KAAK;IAAE;AAAE;AAElD,gFAAgF,GAChF,OAAO,SAASC,oBACdC,iBAA6C;QAGtCC;IADP,MAAMA,aAAarB,kBAAkBoB;IACrC,QAAOC,kBAAAA,WAAWC,GAAG,YAAdD,kBAAkBA,WAAWE,IAAI;AAC1C;AAEA;;;;;;CAMC,GACD,MAAMC,mBAAmB,IAAIC;AAE7B,MAAMC,gBAAgB,CAACC,IAAQJ,OAC7Bb,OAAOkB,OAAO,CAAC;YACGJ;QAAhB,MAAMK,WAAUL,wBAAAA,iBAAiBM,GAAG,CAACH,eAArBH,wBAA4B,IAAIO;QAChDP,iBAAiBQ,GAAG,CAACL,IAAIE;QACzB,IAAIA,QAAQI,GAAG,C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AAErE;uBAAO+C,YAAYC,aAAcnC;gBAC1DX,OAAOC,CAAAA,QAAS/B,oBAAoB+B;YACtC;YACA,IAAI6C,cAAcN,aAAaiB,OAAOW,YAAY,GAAG,GAAG;YACxD,qEAAqE;YACrE,0DAA0D;YAC1D,MAAMR,SAAS,OAAOX,SAASnD,IAAIgD;YACnC,IAAIc,WAAW,MAAM;gBACnB,OAAO,OAAO5F,mBAAmBW,mBAAmBmE,WAAWc;YACjE;QACF;IAEF,8EAA8E;IAC9E,6EAA6E;IAC7E,OAAO;QACL/C;QACAxB;QACAyE;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,MA6FxC,CAAC"}
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"}
@@ -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
  };
@@ -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;IAAE;AAAE;AAElD,gFAAgF,GAChF,MAAMC,gBAAgB;AAEtB,MAAMC,iBAAiB,CAACC,QACtB,OAAOA,UAAU,YACjBA,UAAU,QACV,AAACA,MAA6BC,IAAI,KAAKH;AAEzC;;;;;;;CAOC,GACD,OAAO,MAAMI,iBAAiB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AMC,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,oBAAoB,SAAS;AAE1C,iDAAiD,GACjD,MAAMC,mBAAmB;IAAEC,YAAY;QAAEC,KAAK;IAAE;AAAE;AAElD,gFAAgF,GAChF,MAAMC,gBAAgB;AAEtB,MAAMC,iBAAiB,CAACC,QACtB,OAAOA,UAAU,YACjBA,UAAU,QACV,AAACA,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
2
2
  "name": "@entifix/mongo",
3
- "version": "0.23.12",
3
+ "version": "0.23.14",
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.12",
61
- "@entifix/core": "0.23.12"
60
+ "@entifix/core": "0.23.14",
61
+ "@entifix/business": "0.23.14"
62
62
  },
63
63
  "devDependencies": {
64
64
  "effect": "4.0.7",
65
- "@entifix/testing-unit": "0.23.12",
66
- "@entifix/transactions": "0.23.12"
65
+ "@entifix/transactions": "0.23.14",
66
+ "@entifix/testing-unit": "0.23.14"
67
67
  },
68
68
  "peerDependencies": {
69
69
  "effect": "^4.0.7",
70
- "@entifix/transactions": "0.23.12"
70
+ "@entifix/transactions": "0.23.14"
71
71
  },
72
72
  "peerDependenciesMeta": {
73
73
  "@entifix/transactions": {