@htilabs/platform-common-models 0.29.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,194 @@
1
+ /**
2
+ * An in-memory MongoDB double for the points-of-contact writer tests. It
3
+ * ENFORCES the unique indexes the store declares, partial filters included
4
+ * (a dotted path through an array is treated as multikey, as Mongo does; the
5
+ * in-app pending index is a scalar `identity_key` key), the way the platform's
6
+ * own store test does (platform `test/lib/points-of-contact/repository.test.ts`),
7
+ * and throws the driver's E11000 shape (`code: 11000`, `keyPattern`, the index
8
+ * name in the message). `indexes()` on a collection that was never created
9
+ * throws NamespaceNotFound (26), as `listIndexes` does; reads never create
10
+ * one. Each operation is atomic and the interleaving is the event loop's, so
11
+ * a parallel test here shows a rule holds for THESE interleavings only, not
12
+ * that it is race-safe on a server (the real-MongoDB suite is that check).
13
+ * Not a test file itself (no `.test.ts`).
14
+ */
15
+ import mongoose from "mongoose";
16
+
17
+ const { ObjectId } = mongoose.mongo;
18
+
19
+ export type Doc = Record<string, unknown>;
20
+ export interface Index {
21
+ key: Record<string, number>;
22
+ name?: string;
23
+ unique?: boolean;
24
+ partialFilterExpression?: Doc;
25
+ }
26
+
27
+ function same(a: unknown, b: unknown): boolean {
28
+ if (a instanceof ObjectId || b instanceof ObjectId) return String(a) === String(b);
29
+ if ((a === null || a === undefined) && (b === null || b === undefined)) return true;
30
+ return a === b;
31
+ }
32
+
33
+ function fieldMatches(v: unknown, cond: unknown): boolean {
34
+ if (cond && typeof cond === "object" && !(cond instanceof ObjectId) && !Array.isArray(cond)) {
35
+ const c = cond as Doc;
36
+ if ("$in" in c) {
37
+ return (c.$in as unknown[]).some((x) =>
38
+ Array.isArray(v) ? v.some((y) => same(x, y)) : same(x, v),
39
+ );
40
+ }
41
+ if ("$ne" in c) return !same(v, c.$ne);
42
+ }
43
+ if (Array.isArray(v)) return v.some((x) => same(x, cond));
44
+ return same(v, cond);
45
+ }
46
+
47
+ /** A field, or a dotted path through an array of sub-documents (every value it reaches). */
48
+ function valueAt(d: Doc, k: string): unknown {
49
+ if (!k.includes(".")) return d[k];
50
+ const [head, ...rest] = k.split(".");
51
+ const v = d[head];
52
+ if (Array.isArray(v)) {
53
+ return v.flatMap((x) => (x && typeof x === "object" ? [valueAt(x as Doc, rest.join("."))] : []));
54
+ }
55
+ return v && typeof v === "object" ? valueAt(v as Doc, rest.join(".")) : undefined;
56
+ }
57
+
58
+ export function matches(d: Doc, f: Doc): boolean {
59
+ return Object.entries(f).every(([k, c]) =>
60
+ k === "$or" ? (c as Doc[]).some((alt) => matches(d, alt)) : fieldMatches(valueAt(d, k), c),
61
+ );
62
+ }
63
+
64
+ export function mongoDouble() {
65
+ const store = new Map<string, Doc[]>();
66
+ const indexes = new Map<string, Index[]>();
67
+ const writes: { op: string; collection: string }[] = [];
68
+ let failNextInsert: { error: unknown } | null = null;
69
+
70
+ function uniqueViolation(name: string, docs: Doc[], candidate: Doc): Index | null {
71
+ for (const ix of indexes.get(name) ?? []) {
72
+ if (!ix.unique) continue;
73
+ if (ix.partialFilterExpression && !matches(candidate, ix.partialFilterExpression)) continue;
74
+ // Each key field's indexed values: a dotted path through an array is multikey, so two
75
+ // rows clash when every field shares at least one value (Mongo's rule).
76
+ const valuesOf = (d: Doc, k: string): string[] => {
77
+ const v = valueAt(d, k);
78
+ const list = Array.isArray(v) ? v : [v];
79
+ return (list.length ? list : [null]).map((x) => JSON.stringify(x ?? null));
80
+ };
81
+ const clashes = (d: Doc) =>
82
+ Object.keys(ix.key).every((k) =>
83
+ valuesOf(d, k).some((x) => valuesOf(candidate, k).includes(x)),
84
+ );
85
+ const clash = docs.some(
86
+ (d) =>
87
+ (!ix.partialFilterExpression || matches(d, ix.partialFilterExpression)) && clashes(d),
88
+ );
89
+ if (clash) return ix;
90
+ }
91
+ return null;
92
+ }
93
+
94
+ function collection(name: string) {
95
+ const docs = () => store.get(name) ?? [];
96
+ const created = () => store.get(name) ?? (store.set(name, []), store.get(name)!);
97
+ return {
98
+ find(f: Doc = {}) {
99
+ let order: Record<string, number> | null = null;
100
+ let cap = 0;
101
+ const cursor = {
102
+ sort: (o: Record<string, number>) => ((order = o), cursor),
103
+ limit: (n: number) => ((cap = n), cursor),
104
+ toArray: async () => {
105
+ await Promise.resolve();
106
+ let out = docs().filter((d) => matches(d, f));
107
+ if (order) {
108
+ const keys = Object.entries(order);
109
+ out = [...out].sort((a, b) => {
110
+ for (const [k, dir] of keys) {
111
+ const x = String(a[k] ?? "");
112
+ const y = String(b[k] ?? "");
113
+ if (x !== y) return (x < y ? -1 : 1) * dir;
114
+ }
115
+ return 0;
116
+ });
117
+ }
118
+ return (cap ? out.slice(0, cap) : out).map((d) => ({ ...d }));
119
+ },
120
+ };
121
+ return cursor;
122
+ },
123
+ async findOne(f: Doc) {
124
+ await Promise.resolve();
125
+ const d = docs().find((x) => matches(x, f));
126
+ return d ? { ...d } : null;
127
+ },
128
+ async countDocuments(f: Doc) {
129
+ await Promise.resolve();
130
+ return docs().filter((d) => matches(d, f)).length;
131
+ },
132
+ async insertOne(d: Doc) {
133
+ writes.push({ op: "insertOne", collection: name });
134
+ if (failNextInsert) {
135
+ const { error } = failNextInsert;
136
+ failNextInsert = null;
137
+ throw error;
138
+ }
139
+ const ix = uniqueViolation(name, docs(), d);
140
+ if (ix) {
141
+ throw Object.assign(
142
+ new Error(`E11000 duplicate key error collection: platform.${name} index: ${ix.name} dup key`),
143
+ { code: 11000, keyPattern: ix.key },
144
+ );
145
+ }
146
+ created().push({ ...d });
147
+ return { acknowledged: true as const };
148
+ },
149
+ async deleteOne(f: Doc) {
150
+ writes.push({ op: "deleteOne", collection: name });
151
+ const i = docs().findIndex((x) => matches(x, f));
152
+ if (i >= 0) docs().splice(i, 1);
153
+ return { deletedCount: i >= 0 ? 1 : 0 };
154
+ },
155
+ async createIndex(key: Record<string, number>, opts: Omit<Index, "key"> = {}) {
156
+ const list = indexes.get(name) ?? (indexes.set(name, []), indexes.get(name)!);
157
+ const same = list.find((x) => x.name === opts.name);
158
+ if (same && JSON.stringify(same.key) !== JSON.stringify(key)) {
159
+ throw Object.assign(new Error(`An existing index has the same name as the requested index`), {
160
+ code: 86,
161
+ });
162
+ }
163
+ if (!same) list.push({ key, ...opts });
164
+ return opts.name ?? "ix";
165
+ },
166
+ async indexes() {
167
+ if (!store.has(name) && !indexes.has(name)) {
168
+ throw Object.assign(new Error(`ns does not exist: platform.${name}`), { code: 26 });
169
+ }
170
+ return indexes.get(name) ?? [];
171
+ },
172
+ async dropIndex(ixName: string) {
173
+ const list = indexes.get(name) ?? [];
174
+ const i = list.findIndex((x) => x.name === ixName);
175
+ if (i < 0) throw Object.assign(new Error(`index not found with name [${ixName}]`), { code: 27 });
176
+ list.splice(i, 1);
177
+ },
178
+ };
179
+ }
180
+
181
+ return {
182
+ store,
183
+ indexes,
184
+ writes,
185
+ /** Throw `error` from the next `insertOne` instead of inserting. */
186
+ failNextInsert(error: unknown) {
187
+ failNextInsert = { error };
188
+ },
189
+ /** A handle over the store; each call is a new object (the writer memoizes indexes per handle). */
190
+ handle: () => ({ collection }),
191
+ };
192
+ }
193
+
194
+ export type MongoDouble = ReturnType<typeof mongoDouble>;