@latticecms/store-mongo 0.0.0 → 0.1.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.
Files changed (52) hide show
  1. package/README.md +169 -2
  2. package/dist/errors.d.ts +28 -0
  3. package/dist/errors.d.ts.map +1 -0
  4. package/dist/errors.js +40 -0
  5. package/dist/errors.js.map +1 -0
  6. package/dist/filter.d.ts +20 -0
  7. package/dist/filter.d.ts.map +1 -0
  8. package/dist/filter.js +113 -0
  9. package/dist/filter.js.map +1 -0
  10. package/dist/index.d.ts +5 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +5 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/mapper.d.ts +33 -0
  15. package/dist/mapper.d.ts.map +1 -0
  16. package/dist/mapper.js +23 -0
  17. package/dist/mapper.js.map +1 -0
  18. package/dist/migrate.d.ts +51 -0
  19. package/dist/migrate.d.ts.map +1 -0
  20. package/dist/migrate.js +126 -0
  21. package/dist/migrate.js.map +1 -0
  22. package/dist/migration-error.d.ts +55 -0
  23. package/dist/migration-error.d.ts.map +1 -0
  24. package/dist/migration-error.js +42 -0
  25. package/dist/migration-error.js.map +1 -0
  26. package/dist/migration-lock.d.ts +30 -0
  27. package/dist/migration-lock.d.ts.map +1 -0
  28. package/dist/migration-lock.js +107 -0
  29. package/dist/migration-lock.js.map +1 -0
  30. package/dist/mongo-store.d.ts +58 -0
  31. package/dist/mongo-store.d.ts.map +1 -0
  32. package/dist/mongo-store.js +190 -0
  33. package/dist/mongo-store.js.map +1 -0
  34. package/dist/operations.d.ts +23 -0
  35. package/dist/operations.d.ts.map +1 -0
  36. package/dist/operations.js +149 -0
  37. package/dist/operations.js.map +1 -0
  38. package/dist/tracing.d.ts +14 -0
  39. package/dist/tracing.d.ts.map +1 -0
  40. package/dist/tracing.js +54 -0
  41. package/dist/tracing.js.map +1 -0
  42. package/package.json +63 -2
  43. package/src/errors.ts +43 -0
  44. package/src/filter.ts +127 -0
  45. package/src/index.ts +10 -0
  46. package/src/mapper.ts +30 -0
  47. package/src/migrate.ts +185 -0
  48. package/src/migration-error.ts +41 -0
  49. package/src/migration-lock.ts +146 -0
  50. package/src/mongo-store.ts +303 -0
  51. package/src/operations.ts +213 -0
  52. package/src/tracing.ts +64 -0
@@ -0,0 +1,213 @@
1
+ import {
2
+ type AnyWhere,
3
+ after,
4
+ encodeCursor,
5
+ type FindQuery,
6
+ type Index,
7
+ orderOf,
8
+ type Page,
9
+ type Patch,
10
+ type StoredDoc,
11
+ } from '@latticecms/core/store';
12
+ import type { ClientSession, Collection, Db, Document } from 'mongodb';
13
+ import { writing } from './errors.js';
14
+ import { and, mongoField, toFilter, toSort } from './filter.js';
15
+ import type { MongoDoc, MongoDocument } from './mapper.js';
16
+ import { traced } from './tracing.js';
17
+
18
+ /**
19
+ * The port's operations on one database, optionally inside a session. The
20
+ * store runs them without one, and a transaction's view of the store with
21
+ * its session, so both share every query.
22
+ */
23
+ export class MongoOperations {
24
+ readonly #session: { readonly session?: ClientSession };
25
+
26
+ constructor(
27
+ private readonly db: Db,
28
+ private readonly docs: MongoDoc,
29
+ session?: ClientSession,
30
+ ) {
31
+ this.#session = session === undefined ? {} : { session };
32
+ }
33
+
34
+ #collection(name: string): Collection<MongoDocument> {
35
+ return this.db.collection<MongoDocument>(name);
36
+ }
37
+
38
+ #toDoc(doc: MongoDocument): StoredDoc {
39
+ return this.docs.fromModel(doc);
40
+ }
41
+
42
+ /** `work` as one span, named by the Mongo command it runs. */
43
+ #traced<T>(
44
+ operation: string,
45
+ collection: string,
46
+ work: () => Promise<T>,
47
+ ): Promise<T> {
48
+ return traced(this.db.databaseName, operation, collection, work);
49
+ }
50
+
51
+ async ensure(collection: string, indexes: readonly Index[]): Promise<void> {
52
+ return this.#traced('createIndexes', collection, async () => {
53
+ const target = this.#collection(collection);
54
+ // createIndex is a no-op for an index that exists, and rejects one with
55
+ // the same keys and other options (IndexOptionsConflict or
56
+ // IndexKeySpecsConflict), or a unique one over duplicates (11000).
57
+ // Each passes through: changing an index is a migration. An index is
58
+ // never built inside a transaction, so it takes no session.
59
+ for (const index of indexes) {
60
+ const keys = Object.fromEntries(
61
+ Object.entries(index.fields).map(([field, direction]) => [
62
+ mongoField(field),
63
+ direction,
64
+ ]),
65
+ );
66
+ await target.createIndex(
67
+ keys,
68
+ index.unique === true ? { unique: true } : {},
69
+ );
70
+ }
71
+ });
72
+ }
73
+
74
+ async find(query: FindQuery): Promise<Page> {
75
+ return this.#traced('find', query.collection, async () => {
76
+ const target = this.#collection(query.collection);
77
+ const order = orderOf(query.sort);
78
+ // The keyset is a Where, so it is filtered like any other.
79
+ const filter = and(
80
+ toFilter(query.where),
81
+ query.after === undefined
82
+ ? undefined
83
+ : toFilter(after(order, query.after)),
84
+ );
85
+ // One more than the page tells whether another page follows.
86
+ const window = await target
87
+ .find(filter, this.#session)
88
+ .sort(toSort(order))
89
+ .limit(query.limit + 1)
90
+ .toArray();
91
+ const docs = window.slice(0, query.limit).map((doc) => this.#toDoc(doc));
92
+ const last = docs.at(-1);
93
+ return {
94
+ docs,
95
+ next:
96
+ window.length > query.limit && last !== undefined
97
+ ? encodeCursor(order, last)
98
+ : null,
99
+ };
100
+ });
101
+ }
102
+
103
+ async count(collection: string, where?: AnyWhere): Promise<number> {
104
+ return this.#traced('aggregate', collection, async () => {
105
+ return this.#collection(collection).countDocuments(
106
+ toFilter(where),
107
+ this.#session,
108
+ );
109
+ });
110
+ }
111
+
112
+ async get(
113
+ collection: string,
114
+ id: string,
115
+ where?: AnyWhere,
116
+ ): Promise<StoredDoc | null> {
117
+ return this.#traced('find', collection, async () => {
118
+ const doc = await this.#collection(collection).findOne(
119
+ byId(id, where),
120
+ this.#session,
121
+ );
122
+ return doc === null ? null : this.#toDoc(doc);
123
+ });
124
+ }
125
+
126
+ async getMany(
127
+ collection: string,
128
+ ids: readonly string[],
129
+ where?: AnyWhere,
130
+ ): Promise<StoredDoc[]> {
131
+ return this.#traced('find', collection, async () => {
132
+ const found = await this.#collection(collection)
133
+ .find(and({ _id: { $in: [...ids] } }, toFilter(where)), this.#session)
134
+ .toArray();
135
+ const byKey = new Map(found.map((doc) => [doc._id, doc]));
136
+ return ids.flatMap((id) => {
137
+ const doc = byKey.get(id);
138
+ return doc === undefined ? [] : [this.#toDoc(doc)];
139
+ });
140
+ });
141
+ }
142
+
143
+ async insert(collection: string, doc: StoredDoc): Promise<void> {
144
+ return this.#traced('insert', collection, async () => {
145
+ const target = this.#collection(collection);
146
+ await writing(collection, doc.id, () =>
147
+ target.insertOne(this.docs.toModel(doc), this.#session),
148
+ );
149
+ });
150
+ }
151
+
152
+ async update(
153
+ collection: string,
154
+ id: string,
155
+ patch: Patch,
156
+ where?: AnyWhere,
157
+ ): Promise<StoredDoc | null> {
158
+ return this.#traced('findAndModify', collection, async () => {
159
+ const target = this.#collection(collection);
160
+ const filter = byId(id, where);
161
+ const changes = updateOf(patch);
162
+ if (changes === undefined) {
163
+ const doc = await target.findOne(filter, this.#session);
164
+ return doc === null ? null : this.#toDoc(doc);
165
+ }
166
+ const doc = await writing(collection, id, () =>
167
+ target.findOneAndUpdate(filter, changes, {
168
+ returnDocument: 'after',
169
+ ...this.#session,
170
+ }),
171
+ );
172
+ return doc === null ? null : this.#toDoc(doc);
173
+ });
174
+ }
175
+
176
+ async remove(
177
+ collection: string,
178
+ id: string,
179
+ where?: AnyWhere,
180
+ ): Promise<StoredDoc | null> {
181
+ return this.#traced('findAndModify', collection, async () => {
182
+ const doc = await this.#collection(collection).findOneAndDelete(
183
+ byId(id, where),
184
+ this.#session,
185
+ );
186
+ return doc === null ? null : this.#toDoc(doc);
187
+ });
188
+ }
189
+ }
190
+
191
+ /** The document `id`, if it is inside `where`. */
192
+ function byId(id: string, where: AnyWhere | undefined): Document {
193
+ return and({ _id: id }, toFilter(where));
194
+ }
195
+
196
+ /**
197
+ * A patch as a Mongo update: `$set` for each value, `$unset` for each key
198
+ * set to undefined. `id` is never written, even when a JavaScript caller
199
+ * passes one. Undefined when the patch changes nothing.
200
+ */
201
+ function updateOf(patch: Patch): Document | undefined {
202
+ const set: Record<string, unknown> = {};
203
+ const unset: Record<string, ''> = {};
204
+ for (const [field, value] of Object.entries(patch)) {
205
+ if (field === 'id') continue;
206
+ if (value === undefined) unset[field] = '';
207
+ else set[field] = value;
208
+ }
209
+ const update: Document = {};
210
+ if (Object.keys(set).length > 0) update.$set = set;
211
+ if (Object.keys(unset).length > 0) update.$unset = unset;
212
+ return Object.keys(update).length === 0 ? undefined : update;
213
+ }
package/src/tracing.ts ADDED
@@ -0,0 +1,64 @@
1
+ import { createRequire } from 'node:module';
2
+ import { LatticeError } from '@latticecms/core';
3
+ import { SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';
4
+ import { z } from 'zod';
5
+
6
+ // The package's own version, read from its package.json at runtime, so the
7
+ // tracer's version never drifts from the release. src/ and dist/ both sit
8
+ // one level below it.
9
+ const { version } = z
10
+ .object({ version: z.string() })
11
+ .parse(createRequire(import.meta.url)('../package.json'));
12
+
13
+ /**
14
+ * The package's tracer. With no OpenTelemetry SDK registered it is the
15
+ * API's no-op, so tracing costs nothing until an app registers one.
16
+ */
17
+ export const tracer = trace.getTracer('@latticecms/store-mongo', version);
18
+
19
+ /**
20
+ * Runs `work` as one database client span, `{operation} {collection}`, with
21
+ * OpenTelemetry's database attributes. No query text: a Mongo filter has no
22
+ * parameters, so its text would carry the values it matches. A failure is
23
+ * status ERROR with its type, and no exception event: a driver's message
24
+ * can quote a document's values, such as a duplicate key.
25
+ */
26
+ export function traced<T>(
27
+ database: string,
28
+ operation: string,
29
+ collection: string | undefined,
30
+ work: () => Promise<T>,
31
+ ): Promise<T> {
32
+ const name =
33
+ collection === undefined ? operation : `${operation} ${collection}`;
34
+ return tracer.startActiveSpan(
35
+ name,
36
+ {
37
+ kind: SpanKind.CLIENT,
38
+ attributes: {
39
+ 'db.system.name': 'mongodb',
40
+ 'db.namespace': database,
41
+ 'db.operation.name': operation,
42
+ ...(collection === undefined
43
+ ? {}
44
+ : { 'db.collection.name': collection }),
45
+ },
46
+ },
47
+ async (span) => {
48
+ try {
49
+ return await work();
50
+ } catch (error) {
51
+ const type = LatticeError.is(error)
52
+ ? String(error.code)
53
+ : error instanceof Error
54
+ ? error.name
55
+ : typeof error;
56
+ span.setAttribute('error.type', type);
57
+ span.setStatus({ code: SpanStatusCode.ERROR, message: type });
58
+ throw error;
59
+ } finally {
60
+ span.end();
61
+ }
62
+ },
63
+ );
64
+ }