@latticecms/store-mongo 0.0.0-stage → 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 (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +171 -2
  3. package/dist/errors.d.ts +28 -0
  4. package/dist/errors.d.ts.map +1 -0
  5. package/dist/errors.js +40 -0
  6. package/dist/errors.js.map +1 -0
  7. package/dist/filter.d.ts +20 -0
  8. package/dist/filter.d.ts.map +1 -0
  9. package/dist/filter.js +113 -0
  10. package/dist/filter.js.map +1 -0
  11. package/dist/index.d.ts +5 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +5 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/mapper.d.ts +33 -0
  16. package/dist/mapper.d.ts.map +1 -0
  17. package/dist/mapper.js +23 -0
  18. package/dist/mapper.js.map +1 -0
  19. package/dist/migrate.d.ts +51 -0
  20. package/dist/migrate.d.ts.map +1 -0
  21. package/dist/migrate.js +126 -0
  22. package/dist/migrate.js.map +1 -0
  23. package/dist/migration-error.d.ts +55 -0
  24. package/dist/migration-error.d.ts.map +1 -0
  25. package/dist/migration-error.js +42 -0
  26. package/dist/migration-error.js.map +1 -0
  27. package/dist/migration-lock.d.ts +30 -0
  28. package/dist/migration-lock.d.ts.map +1 -0
  29. package/dist/migration-lock.js +107 -0
  30. package/dist/migration-lock.js.map +1 -0
  31. package/dist/mongo-store.d.ts +58 -0
  32. package/dist/mongo-store.d.ts.map +1 -0
  33. package/dist/mongo-store.js +190 -0
  34. package/dist/mongo-store.js.map +1 -0
  35. package/dist/operations.d.ts +23 -0
  36. package/dist/operations.d.ts.map +1 -0
  37. package/dist/operations.js +149 -0
  38. package/dist/operations.js.map +1 -0
  39. package/dist/tracing.d.ts +14 -0
  40. package/dist/tracing.d.ts.map +1 -0
  41. package/dist/tracing.js +54 -0
  42. package/dist/tracing.js.map +1 -0
  43. package/package.json +74 -4
  44. package/src/errors.ts +43 -0
  45. package/src/filter.ts +127 -0
  46. package/src/index.ts +10 -0
  47. package/src/mapper.ts +30 -0
  48. package/src/migrate.ts +185 -0
  49. package/src/migration-error.ts +41 -0
  50. package/src/migration-lock.ts +146 -0
  51. package/src/mongo-store.ts +303 -0
  52. package/src/operations.ts +213 -0
  53. package/src/tracing.ts +64 -0
@@ -0,0 +1,126 @@
1
+ import { MigrationError } from './migration-error.js';
2
+ import { leaseLock } from './migration-lock.js';
3
+ import { connectionOf } from './mongo-store.js';
4
+ /** The list's own checks: ids 1, 2, 3 … in order, none twice. */
5
+ function checkList(migrations) {
6
+ const seen = new Set();
7
+ for (const { id } of migrations) {
8
+ if (seen.has(id))
9
+ throw MigrationError.Duplicate({ id });
10
+ seen.add(id);
11
+ }
12
+ migrations.forEach(({ id }, index) => {
13
+ if (id !== index + 1) {
14
+ throw MigrationError.Gap({ expected: index + 1, found: id });
15
+ }
16
+ });
17
+ }
18
+ /** The recorded migrations against the list: none missing, none renamed. */
19
+ function checkRecords(migrations, records) {
20
+ for (const record of records) {
21
+ const listed = migrations[record._id - 1];
22
+ if (listed === undefined) {
23
+ throw MigrationError.Unknown({ id: record._id, name: record.name });
24
+ }
25
+ if (listed.name !== record.name) {
26
+ throw MigrationError.Renamed({
27
+ id: record._id,
28
+ recorded: record.name,
29
+ listed: listed.name,
30
+ });
31
+ }
32
+ }
33
+ }
34
+ /** Whether the deployment runs transactions: a replica set or a mongos. */
35
+ async function hasTransactions(db) {
36
+ const hello = await db.admin().command({ hello: 1 });
37
+ return typeof hello.setName === 'string' || hello.msg === 'isdbgrid';
38
+ }
39
+ /**
40
+ * Runs each pending migration once, in id order, under a lease lock in the
41
+ * store's database (0027). The store must be started. A second process
42
+ * waits for the lock, then finds nothing left to run. A migration that
43
+ * throws is not recorded: the error passes through, and the next run
44
+ * retries it.
45
+ */
46
+ export async function migrate(store, migrations, options) {
47
+ const { client, db } = connectionOf(store);
48
+ const { logger } = options;
49
+ checkList(migrations);
50
+ const lock = leaseLock(db, {
51
+ ttlMs: options.lock?.ttlMs ?? 60_000,
52
+ waitMs: options.lock?.waitMs ?? 600_000,
53
+ onWait: (heldSince) => logger.info('migrations waiting for lock', {
54
+ ...(heldSince === undefined
55
+ ? {}
56
+ : { heldSince: heldSince.toISOString() }),
57
+ }),
58
+ });
59
+ const records = db.collection('_migrations');
60
+ return lock.run(async (signal) => {
61
+ const recorded = await records.find().sort({ _id: 1 }).toArray();
62
+ checkRecords(migrations, recorded);
63
+ const pending = migrations.slice(recorded.length);
64
+ const transactional = pending.find((migration) => migration.transaction);
65
+ if (transactional !== undefined && !(await hasTransactions(db))) {
66
+ throw MigrationError.NoTransactions({ id: transactional.id });
67
+ }
68
+ if (pending.length === 0) {
69
+ logger.info('migrations up to date', { last: recorded.length });
70
+ return { ran: [] };
71
+ }
72
+ const ran = [];
73
+ for (const migration of pending) {
74
+ if (signal.aborted)
75
+ throw MigrationError.LockLost();
76
+ const { id, name } = migration;
77
+ const context = { db, signal, logger: logger.child({ id, name }) };
78
+ const started = performance.now();
79
+ const record = (durationMs) => ({
80
+ _id: id,
81
+ name,
82
+ ranAt: new Date(),
83
+ durationMs,
84
+ });
85
+ try {
86
+ if (migration.transaction === true) {
87
+ await client.withSession((session) => session.withTransaction(async () => {
88
+ await migration.up({ ...context, session });
89
+ if (signal.aborted)
90
+ throw MigrationError.LockLost();
91
+ await records.insertOne(record(since(started)), { session });
92
+ }));
93
+ }
94
+ else {
95
+ await migration.up(context);
96
+ // The lock was lost while it ran: another process may run it
97
+ // too, so it is not recorded here. up is safe to re-run.
98
+ if (signal.aborted)
99
+ throw MigrationError.LockLost();
100
+ await records.insertOne(record(since(started)));
101
+ }
102
+ }
103
+ catch (error) {
104
+ const fields = {
105
+ id,
106
+ name,
107
+ durationMs: since(started),
108
+ outcome: 'failed',
109
+ };
110
+ if (error instanceof Error)
111
+ logger.error(error, fields);
112
+ else
113
+ logger.error('migration', { ...fields, thrown: String(error) });
114
+ throw error;
115
+ }
116
+ const durationMs = since(started);
117
+ logger.info('migration', { id, name, durationMs, outcome: 'ok' });
118
+ ran.push({ id, name, durationMs });
119
+ }
120
+ return { ran };
121
+ });
122
+ }
123
+ function since(started) {
124
+ return Math.round(performance.now() - started);
125
+ }
126
+ //# sourceMappingURL=migrate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrate.js","sourceRoot":"","sources":["../src/migrate.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAsB,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAAE,YAAY,EAAmB,MAAM,kBAAkB,CAAC;AAmDjE,iEAAiE;AACjE,SAAS,SAAS,CAAC,UAAgC;IACjD,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,EAAE,EAAE,EAAE,IAAI,UAAU,EAAE,CAAC;QAChC,IAAI,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YAAE,MAAM,cAAc,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IACf,CAAC;IACD,UAAU,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE;QACnC,IAAI,EAAE,KAAK,KAAK,GAAG,CAAC,EAAE,CAAC;YACrB,MAAM,cAAc,CAAC,GAAG,CAAC,EAAE,QAAQ,EAAE,KAAK,GAAG,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;QAC/D,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED,4EAA4E;AAC5E,SAAS,YAAY,CACnB,UAAgC,EAChC,OAAmC;IAEnC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC;QAC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AK,EAAE,CAAC;gBACf,MAAM,MAAM,GAAG;oBACb,EAAE;oBACF,IAAI;oBACJ,UAAU,EAAE,KAAK,CAAC,OAAO,CAAC;oBAC1B,OAAO,EAAE,QAAQ;iBAClB,CAAC;gBACF,IAAI,KAAK,YAAY,KAAK;oBAAE,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;;oBACnD,MAAM,CAAC,KAAK,CAAC,WAAW,EAAE,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;gBACrE,MAAM,KAAK,CAAC;YACd,CAAC;YACD,MAAM,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC;YAClC,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;YAClE,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;QACrC,CAAC;QACD,OAAO,EAAE,GAAG,EAAE,CAAC;IACjB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,KAAK,CAAC,OAAe;IAC5B,OAAO,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,OAAO,CAAC,CAAC;AACjD,CAAC"}
@@ -0,0 +1,55 @@
1
+ import { z } from 'zod';
2
+ declare const MigrationError_base: import("hexok").ErrorsHandle<"migrations", {
3
+ readonly Gap: {
4
+ readonly message: "Migration ids must run 1, 2, 3 … in list order, with no gap";
5
+ readonly data: z.ZodObject<{
6
+ expected: z.ZodNumber;
7
+ found: z.ZodNumber;
8
+ }, z.core.$strip>;
9
+ };
10
+ readonly Duplicate: {
11
+ readonly message: "Two migrations share an id";
12
+ readonly data: z.ZodObject<{
13
+ id: z.ZodNumber;
14
+ }, z.core.$strip>;
15
+ };
16
+ readonly Unknown: {
17
+ readonly message: "A migration that ran is missing from the list";
18
+ readonly data: z.ZodObject<{
19
+ id: z.ZodNumber;
20
+ name: z.ZodString;
21
+ }, z.core.$strip>;
22
+ };
23
+ readonly Renamed: {
24
+ readonly message: "A migration that ran has another name in the list";
25
+ readonly data: z.ZodObject<{
26
+ id: z.ZodNumber;
27
+ recorded: z.ZodString;
28
+ listed: z.ZodString;
29
+ }, z.core.$strip>;
30
+ };
31
+ readonly NoTransactions: {
32
+ readonly message: "A migration asks for a transaction, but the deployment has none";
33
+ readonly data: z.ZodObject<{
34
+ id: z.ZodNumber;
35
+ }, z.core.$strip>;
36
+ };
37
+ readonly LockTimeout: {
38
+ readonly message: "Another process held the migrations lock for longer than waitMs";
39
+ readonly data: z.ZodObject<{
40
+ waitMs: z.ZodNumber;
41
+ }, z.core.$strip>;
42
+ };
43
+ readonly LockLost: {
44
+ readonly message: "The migrations lock was lost while a migration ran";
45
+ };
46
+ }>;
47
+ /**
48
+ * Why `migrate` refused to run, or stopped. The list checks (`Gap`,
49
+ * `Duplicate`, `Unknown`, `Renamed`) and `NoTransactions` throw before any
50
+ * migration runs.
51
+ */
52
+ export declare class MigrationError extends MigrationError_base {
53
+ }
54
+ export {};
55
+ //# sourceMappingURL=migration-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration-error.d.ts","sourceRoot":"","sources":["../src/migration-error.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAExB;;;;GAIG;AACH,qBAAa,cAAe,SAAQ,mBAgClC;CAAG"}
@@ -0,0 +1,42 @@
1
+ import { Errors } from 'hexok';
2
+ import { z } from 'zod';
3
+ /**
4
+ * Why `migrate` refused to run, or stopped. The list checks (`Gap`,
5
+ * `Duplicate`, `Unknown`, `Renamed`) and `NoTransactions` throw before any
6
+ * migration runs.
7
+ */
8
+ export class MigrationError extends Errors('migrations', {
9
+ Gap: {
10
+ message: 'Migration ids must run 1, 2, 3 … in list order, with no gap',
11
+ data: z.object({ expected: z.number(), found: z.number() }),
12
+ },
13
+ Duplicate: {
14
+ message: 'Two migrations share an id',
15
+ data: z.object({ id: z.number() }),
16
+ },
17
+ Unknown: {
18
+ message: 'A migration that ran is missing from the list',
19
+ data: z.object({ id: z.number(), name: z.string() }),
20
+ },
21
+ Renamed: {
22
+ message: 'A migration that ran has another name in the list',
23
+ data: z.object({
24
+ id: z.number(),
25
+ recorded: z.string(),
26
+ listed: z.string(),
27
+ }),
28
+ },
29
+ NoTransactions: {
30
+ message: 'A migration asks for a transaction, but the deployment has none',
31
+ data: z.object({ id: z.number() }),
32
+ },
33
+ LockTimeout: {
34
+ message: 'Another process held the migrations lock for longer than waitMs',
35
+ data: z.object({ waitMs: z.number() }),
36
+ },
37
+ LockLost: {
38
+ message: 'The migrations lock was lost while a migration ran',
39
+ },
40
+ }) {
41
+ }
42
+ //# sourceMappingURL=migration-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration-error.js","sourceRoot":"","sources":["../src/migration-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAC/B,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;GAIG;AACH,MAAM,OAAO,cAAe,SAAQ,MAAM,CAAC,YAAY,EAAE;IACvD,GAAG,EAAE;QACH,OAAO,EAAE,6DAA6D;QACtE,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;KAC5D;IACD,SAAS,EAAE;QACT,OAAO,EAAE,4BAA4B;QACrC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;KACnC;IACD,OAAO,EAAE;QACP,OAAO,EAAE,+CAA+C;QACxD,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;KACrD;IACD,OAAO,EAAE;QACP,OAAO,EAAE,mDAAmD;QAC5D,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;YACb,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE;YACd,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE;YACpB,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE;SACnB,CAAC;KACH;IACD,cAAc,EAAE;QACd,OAAO,EAAE,iEAAiE;QAC1E,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;KACnC;IACD,WAAW,EAAE;QACX,OAAO,EAAE,iEAAiE;QAC1E,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;KACvC;IACD,QAAQ,EAAE;QACR,OAAO,EAAE,oDAAoD;KAC9D;CACF,CAAC;CAAG"}
@@ -0,0 +1,30 @@
1
+ import type { Db } from 'mongodb';
2
+ /**
3
+ * The lock migrations run under. An internal seam: the lease below can be
4
+ * replaced by another lock, such as a hexok one, without touching the
5
+ * runner (0027).
6
+ */
7
+ export type MigrationLock = {
8
+ /**
9
+ * Waits for the lock, runs `work` while holding it, and releases it.
10
+ * `signal` aborts when the lock is lost.
11
+ */
12
+ run<T>(work: (signal: AbortSignal) => Promise<T>): Promise<T>;
13
+ };
14
+ export type LeaseOptions = {
15
+ /** How long a lease lives without a renewal. It is renewed every third. */
16
+ readonly ttlMs: number;
17
+ /** How long to wait for another process's lease before `LockTimeout`. */
18
+ readonly waitMs: number;
19
+ /** Called once, when the lock is held by another process and the run waits. */
20
+ readonly onWait: (heldSince: Date | undefined) => void;
21
+ };
22
+ /**
23
+ * A lease in `_migrations_lock`, in the database being migrated. Taken
24
+ * atomically with the server's clock (`$$NOW`), so clocks on different
25
+ * hosts do not matter; renewed every third of its TTL; released by its
26
+ * random token, so a process never releases another's lease. A lease whose
27
+ * holder died expires and is taken over.
28
+ */
29
+ export declare function leaseLock(db: Db, options: LeaseOptions): MigrationLock;
30
+ //# sourceMappingURL=migration-lock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration-lock.d.ts","sourceRoot":"","sources":["../src/migration-lock.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAGlC;;;;GAIG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B;;;OAGG;IACH,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CAC/D,CAAC;AAUF,MAAM,MAAM,YAAY,GAAG;IACzB,2EAA2E;IAC3E,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,yEAAyE;IACzE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,+EAA+E;IAC/E,QAAQ,CAAC,MAAM,EAAE,CAAC,SAAS,EAAE,IAAI,GAAG,SAAS,KAAK,IAAI,CAAC;CACxD,CAAC;AAiBF;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,EAAE,EAAE,EAAE,EAAE,OAAO,EAAE,YAAY,GAAG,aAAa,CA0FtE"}
@@ -0,0 +1,107 @@
1
+ import { MigrationError } from './migration-error.js';
2
+ const leaseId = 'migrations';
3
+ /** Resolves after `ms`, or at once when `signal` aborts. */
4
+ function sleep(ms, signal) {
5
+ return new Promise((resolve) => {
6
+ const timer = setTimeout(done, ms);
7
+ function done() {
8
+ clearTimeout(timer);
9
+ signal?.removeEventListener('abort', done);
10
+ resolve();
11
+ }
12
+ signal?.addEventListener('abort', done, { once: true });
13
+ });
14
+ }
15
+ /**
16
+ * A lease in `_migrations_lock`, in the database being migrated. Taken
17
+ * atomically with the server's clock (`$$NOW`), so clocks on different
18
+ * hosts do not matter; renewed every third of its TTL; released by its
19
+ * random token, so a process never releases another's lease. A lease whose
20
+ * holder died expires and is taken over.
21
+ */
22
+ export function leaseLock(db, options) {
23
+ const leases = db.collection('_migrations_lock');
24
+ const { ttlMs, waitMs } = options;
25
+ async function acquire(token) {
26
+ // One atomic update, on the server's clock: it takes the lease only
27
+ // when it has expired, or does not exist yet (a missing expiresAt
28
+ // compares below any date). Otherwise it leaves the holder's fields as
29
+ // they are. The returned token says who holds it.
30
+ const expired = { $lt: ['$expiresAt', '$$NOW'] };
31
+ const lease = await leases.findOneAndUpdate({ _id: leaseId }, [
32
+ {
33
+ $set: {
34
+ token: { $cond: [expired, token, '$token'] },
35
+ acquiredAt: { $cond: [expired, '$$NOW', '$acquiredAt'] },
36
+ expiresAt: {
37
+ $cond: [expired, { $add: ['$$NOW', ttlMs] }, '$expiresAt'],
38
+ },
39
+ },
40
+ },
41
+ ], { upsert: true, returnDocument: 'after' });
42
+ return lease?.token === token;
43
+ }
44
+ async function renew(token) {
45
+ const result = await leases.updateOne({ _id: leaseId, token }, [
46
+ { $set: { expiresAt: { $add: ['$$NOW', ttlMs] } } },
47
+ ]);
48
+ return result.matchedCount === 1;
49
+ }
50
+ async function wait(token) {
51
+ const deadline = Date.now() + waitMs;
52
+ const poll = Math.min(1000, ttlMs / 3);
53
+ let waited = false;
54
+ while (!(await acquire(token))) {
55
+ if (!waited) {
56
+ waited = true;
57
+ const held = await leases.findOne({ _id: leaseId });
58
+ options.onWait(held?.acquiredAt);
59
+ }
60
+ const left = deadline - Date.now();
61
+ if (left <= 0)
62
+ throw MigrationError.LockTimeout({ waitMs });
63
+ await sleep(Math.min(poll, left));
64
+ }
65
+ }
66
+ return {
67
+ async run(work) {
68
+ const token = crypto.randomUUID();
69
+ await wait(token);
70
+ const lost = new AbortController();
71
+ // A lease is good until the TTL after its last renewal was sent. Abort
72
+ // a margin before that, so this process stops before another can take
73
+ // the lock, even when a renewal never answers.
74
+ const margin = Math.min(1000, ttlMs / 4);
75
+ let sent = Date.now();
76
+ const stopped = new AbortController();
77
+ const keep = (async () => {
78
+ while (!stopped.signal.aborted && !lost.signal.aborted) {
79
+ await sleep(ttlMs / 3, stopped.signal);
80
+ if (stopped.signal.aborted)
81
+ return;
82
+ const at = Date.now();
83
+ const renewed = await Promise.race([
84
+ renew(token).catch(() => false),
85
+ sleep(Math.max(0, sent + ttlMs - margin - at), stopped.signal).then(() => false),
86
+ ]);
87
+ if (stopped.signal.aborted)
88
+ return;
89
+ if (!renewed) {
90
+ lost.abort(MigrationError.LockLost());
91
+ return;
92
+ }
93
+ sent = at;
94
+ }
95
+ })();
96
+ try {
97
+ return await work(lost.signal);
98
+ }
99
+ finally {
100
+ stopped.abort();
101
+ await keep;
102
+ await leases.deleteOne({ _id: leaseId, token });
103
+ }
104
+ },
105
+ };
106
+ }
107
+ //# sourceMappingURL=migration-lock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration-lock.js","sourceRoot":"","sources":["../src/migration-lock.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAgCtD,MAAM,OAAO,GAAG,YAAY,CAAC;AAE7B,4DAA4D;AAC5D,SAAS,KAAK,CAAC,EAAU,EAAE,MAAoB;IAC7C,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,MAAM,KAAK,GAAG,UAAU,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACnC,SAAS,IAAI;YACX,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;YAC3C,OAAO,EAAE,CAAC;QACZ,CAAC;QACD,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,IAAI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C,SAAS,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;YAClD,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,58 @@
1
+ import { type AnyWhere, CollectionStore, type FindQuery, type Index, type Page, type Patch, type StoredDoc } from '@latticecms/core/store';
2
+ import { type Db, MongoClient, type MongoClientOptions } from 'mongodb';
3
+ export type MongoStoreOptions = {
4
+ /** A `mongodb://` or `mongodb+srv://` connection string. */
5
+ readonly url: string;
6
+ /** The database every collection lives in. */
7
+ readonly database: string;
8
+ /**
9
+ * Options for the store's `MongoClient`. `serverSelectionTimeoutMS`
10
+ * bounds how long `start()` waits for the server.
11
+ */
12
+ readonly client?: MongoClientOptions;
13
+ };
14
+ /** The client and database of a started store, or its lifecycle error. */
15
+ export declare function connectionOf(store: MongoStore): {
16
+ readonly client: MongoClient;
17
+ readonly db: Db;
18
+ };
19
+ declare const MongoStore_base: (abstract new (...args: any[]) => {
20
+ start(): Promise<void>;
21
+ stop(): Promise<void>;
22
+ }) & typeof CollectionStore;
23
+ /**
24
+ * The MongoDB `CollectionStore`. It owns its `MongoClient` (0025): `start()`
25
+ * connects and pings, and `stop()` closes the client. A call before
26
+ * `start()`, during it, or after `stop()` rejects with `MongoStoreError`.
27
+ * Each Lattice collection is a Mongo collection of the same name, and a
28
+ * document's `id` is its `_id`.
29
+ */
30
+ export declare class MongoStore extends MongoStore_base {
31
+ #private;
32
+ private readonly options;
33
+ constructor(options: MongoStoreOptions);
34
+ /**
35
+ * Connects and pings the server. A `start()` while one is pending joins
36
+ * it; one after `stop()` opens a new client. Rejects with `Stopped` when
37
+ * `stop()` is called before it finishes.
38
+ */
39
+ start(): Promise<void>;
40
+ /** Closes the client. A pending `start()` rejects with `Stopped`. */
41
+ stop(): Promise<void>;
42
+ ensure(collection: string, indexes: readonly Index[]): Promise<void>;
43
+ find(query: FindQuery): Promise<Page>;
44
+ count(collection: string, where?: AnyWhere): Promise<number>;
45
+ get(collection: string, id: string, where?: AnyWhere): Promise<StoredDoc | null>;
46
+ getMany(collection: string, ids: readonly string[], where?: AnyWhere): Promise<StoredDoc[]>;
47
+ insert(collection: string, doc: StoredDoc): Promise<void>;
48
+ update(collection: string, id: string, patch: Patch, where?: AnyWhere): Promise<StoredDoc | null>;
49
+ remove(collection: string, id: string, where?: AnyWhere): Promise<StoredDoc | null>;
50
+ /**
51
+ * Runs `work` in one transaction on a replica set or a mongos, with a view
52
+ * of this store whose every call joins it. A standalone server has no
53
+ * transactions, so there `work` runs on this store, in order.
54
+ */
55
+ transaction<T>(work: (store: CollectionStore) => Promise<T>): Promise<T>;
56
+ }
57
+ export {};
58
+ //# sourceMappingURL=mongo-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mongo-store.d.ts","sourceRoot":"","sources":["../src/mongo-store.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,QAAQ,EACb,eAAe,EACf,KAAK,SAAS,EACd,KAAK,KAAK,EACV,KAAK,IAAI,EACT,KAAK,KAAK,EACV,KAAK,SAAS,EACf,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,KAAK,EAAE,EAAE,WAAW,EAAE,KAAK,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAMxE,MAAM,MAAM,iBAAiB,GAAG;IAC9B,4DAA4D;IAC5D,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,8CAA8C;IAC9C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,kBAAkB,CAAC;CACtC,CAAC;AAYF,0EAA0E;AAC1E,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG;IAC/C,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAC7B,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC;CACjB,CAIA;;;;;AAkBD;;;;;;GAMG;AACH,qBAAa,UAAW,SAAQ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AAO,CAAC,CAAC,CAAC;CAgBd"}
@@ -0,0 +1,190 @@
1
+ import { CollectionStore, } from '@latticecms/core/store';
2
+ import { Adapter } from 'hexok';
3
+ import { MongoClient } from 'mongodb';
4
+ import { MongoStoreError } from './errors.js';
5
+ import { MongoDoc } from './mapper.js';
6
+ import { MongoOperations } from './operations.js';
7
+ import { traced } from './tracing.js';
8
+ /**
9
+ * The started client of each store, for this package's migrations runner.
10
+ * Not exported from the package: a store's public surface is the port,
11
+ * `start` and `stop`.
12
+ */
13
+ const connections = new WeakMap();
14
+ /** The client and database of a started store, or its lifecycle error. */
15
+ export function connectionOf(store) {
16
+ const connection = connections.get(store);
17
+ if (connection === undefined)
18
+ throw MongoStoreError.NotStarted();
19
+ return connection();
20
+ }
21
+ /**
22
+ * The MongoDB `CollectionStore`. It owns its `MongoClient` (0025): `start()`
23
+ * connects and pings, and `stop()` closes the client. A call before
24
+ * `start()`, during it, or after `stop()` rejects with `MongoStoreError`.
25
+ * Each Lattice collection is a Mongo collection of the same name, and a
26
+ * document's `id` is its `_id`.
27
+ */
28
+ export class MongoStore extends Adapter(CollectionStore) {
29
+ options;
30
+ #state = { kind: 'idle' };
31
+ #docs = new MongoDoc();
32
+ constructor(options) {
33
+ super();
34
+ this.options = options;
35
+ connections.set(this, () => this.#connection());
36
+ }
37
+ /**
38
+ * Connects and pings the server. A `start()` while one is pending joins
39
+ * it; one after `stop()` opens a new client. Rejects with `Stopped` when
40
+ * `stop()` is called before it finishes.
41
+ */
42
+ async start() {
43
+ const state = this.#state;
44
+ if (state.kind === 'ready')
45
+ return;
46
+ if (state.kind === 'starting') {
47
+ await this.#joined(state.ready);
48
+ return;
49
+ }
50
+ const client = new MongoClient(this.options.url, this.options.client);
51
+ const ready = (async () => {
52
+ await client.connect();
53
+ const db = client.db(this.options.database);
54
+ const hello = await db.admin().command({ hello: 1 });
55
+ const transactions = typeof hello.setName === 'string' || hello.msg === 'isdbgrid';
56
+ return { db, transactions };
57
+ })();
58
+ const starting = { kind: 'starting', client, ready };
59
+ this.#state = starting;
60
+ try {
61
+ const { db, transactions } = await ready;
62
+ if (this.#state !== starting)
63
+ throw MongoStoreError.Stopped();
64
+ this.#state = { kind: 'ready', client, db, transactions };
65
+ }
66
+ catch (error) {
67
+ // stop() closed the client under the pending connect: the driver's
68
+ // error says only that, so the caller gets Stopped.
69
+ if (this.#state !== starting)
70
+ throw MongoStoreError.Stopped();
71
+ this.#state = { kind: 'idle' };
72
+ await client.close();
73
+ throw error;
74
+ }
75
+ }
76
+ /** Closes the client. A pending `start()` rejects with `Stopped`. */
77
+ async stop() {
78
+ const state = this.#state;
79
+ this.#state = { kind: 'stopped' };
80
+ if (state.kind === 'starting' || state.kind === 'ready') {
81
+ await state.client.close();
82
+ }
83
+ }
84
+ async #joined(ready) {
85
+ try {
86
+ await ready;
87
+ }
88
+ catch (error) {
89
+ if (this.#state.kind === 'stopped')
90
+ throw MongoStoreError.Stopped();
91
+ throw error;
92
+ }
93
+ if (this.#state.kind !== 'ready')
94
+ throw MongoStoreError.Stopped();
95
+ }
96
+ /** The client and database, or the lifecycle error for a call made now. */
97
+ #connection() {
98
+ const state = this.#state;
99
+ switch (state.kind) {
100
+ case 'ready':
101
+ return state;
102
+ case 'idle':
103
+ throw MongoStoreError.NotStarted();
104
+ case 'starting':
105
+ throw MongoStoreError.Starting();
106
+ case 'stopped':
107
+ throw MongoStoreError.Stopped();
108
+ }
109
+ }
110
+ #operations() {
111
+ return new MongoOperations(this.#connection().db, this.#docs);
112
+ }
113
+ async ensure(collection, indexes) {
114
+ return this.#operations().ensure(collection, indexes);
115
+ }
116
+ async find(query) {
117
+ return this.#operations().find(query);
118
+ }
119
+ async count(collection, where) {
120
+ return this.#operations().count(collection, where);
121
+ }
122
+ async get(collection, id, where) {
123
+ return this.#operations().get(collection, id, where);
124
+ }
125
+ async getMany(collection, ids, where) {
126
+ return this.#operations().getMany(collection, ids, where);
127
+ }
128
+ async insert(collection, doc) {
129
+ return this.#operations().insert(collection, doc);
130
+ }
131
+ async update(collection, id, patch, where) {
132
+ return this.#operations().update(collection, id, patch, where);
133
+ }
134
+ async remove(collection, id, where) {
135
+ return this.#operations().remove(collection, id, where);
136
+ }
137
+ /**
138
+ * Runs `work` in one transaction on a replica set or a mongos, with a view
139
+ * of this store whose every call joins it. A standalone server has no
140
+ * transactions, so there `work` runs on this store, in order.
141
+ */
142
+ async transaction(work) {
143
+ const { client, db, transactions } = this.#connection();
144
+ if (!transactions)
145
+ return work(this);
146
+ // One parent span, active while the transaction runs, so each call in it
147
+ // nests under it. The driver may run `work` again on a transient error;
148
+ // each run's calls nest under the same span.
149
+ return traced(db.databaseName, 'transaction', undefined, () => client.withSession((session) => session.withTransaction(() => work(new TransactionStore(new MongoOperations(db, this.#docs, session))))));
150
+ }
151
+ }
152
+ /**
153
+ * A store inside a transaction: every call carries the session, and a
154
+ * nested `transaction` joins it.
155
+ */
156
+ class TransactionStore extends Adapter(CollectionStore) {
157
+ operations;
158
+ constructor(operations) {
159
+ super();
160
+ this.operations = operations;
161
+ }
162
+ ensure(collection, indexes) {
163
+ return this.operations.ensure(collection, indexes);
164
+ }
165
+ find(query) {
166
+ return this.operations.find(query);
167
+ }
168
+ count(collection, where) {
169
+ return this.operations.count(collection, where);
170
+ }
171
+ get(collection, id, where) {
172
+ return this.operations.get(collection, id, where);
173
+ }
174
+ getMany(collection, ids, where) {
175
+ return this.operations.getMany(collection, ids, where);
176
+ }
177
+ insert(collection, doc) {
178
+ return this.operations.insert(collection, doc);
179
+ }
180
+ update(collection, id, patch, where) {
181
+ return this.operations.update(collection, id, patch, where);
182
+ }
183
+ remove(collection, id, where) {
184
+ return this.operations.remove(collection, id, where);
185
+ }
186
+ transaction(work) {
187
+ return work(this);
188
+ }
189
+ }
190
+ //# sourceMappingURL=mongo-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mongo-store.js","sourceRoot":"","sources":["../src/mongo-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,eAAe,G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