@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.
- package/LICENSE +21 -0
- package/README.md +171 -2
- package/dist/errors.d.ts +28 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +40 -0
- package/dist/errors.js.map +1 -0
- package/dist/filter.d.ts +20 -0
- package/dist/filter.d.ts.map +1 -0
- package/dist/filter.js +113 -0
- package/dist/filter.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/mapper.d.ts +33 -0
- package/dist/mapper.d.ts.map +1 -0
- package/dist/mapper.js +23 -0
- package/dist/mapper.js.map +1 -0
- package/dist/migrate.d.ts +51 -0
- package/dist/migrate.d.ts.map +1 -0
- package/dist/migrate.js +126 -0
- package/dist/migrate.js.map +1 -0
- package/dist/migration-error.d.ts +55 -0
- package/dist/migration-error.d.ts.map +1 -0
- package/dist/migration-error.js +42 -0
- package/dist/migration-error.js.map +1 -0
- package/dist/migration-lock.d.ts +30 -0
- package/dist/migration-lock.d.ts.map +1 -0
- package/dist/migration-lock.js +107 -0
- package/dist/migration-lock.js.map +1 -0
- package/dist/mongo-store.d.ts +58 -0
- package/dist/mongo-store.d.ts.map +1 -0
- package/dist/mongo-store.js +190 -0
- package/dist/mongo-store.js.map +1 -0
- package/dist/operations.d.ts +23 -0
- package/dist/operations.d.ts.map +1 -0
- package/dist/operations.js +149 -0
- package/dist/operations.js.map +1 -0
- package/dist/tracing.d.ts +14 -0
- package/dist/tracing.d.ts.map +1 -0
- package/dist/tracing.js +54 -0
- package/dist/tracing.js.map +1 -0
- package/package.json +74 -4
- package/src/errors.ts +43 -0
- package/src/filter.ts +127 -0
- package/src/index.ts +10 -0
- package/src/mapper.ts +30 -0
- package/src/migrate.ts +185 -0
- package/src/migration-error.ts +41 -0
- package/src/migration-lock.ts +146 -0
- package/src/mongo-store.ts +303 -0
- package/src/operations.ts +213 -0
- package/src/tracing.ts +64 -0
package/src/migrate.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import type { Logger } from '@hexok/logger';
|
|
2
|
+
import type { ClientSession, Db } from 'mongodb';
|
|
3
|
+
import { MigrationError } from './migration-error.js';
|
|
4
|
+
import { leaseLock, type MigrationLock } from './migration-lock.js';
|
|
5
|
+
import { connectionOf, type MongoStore } from './mongo-store.js';
|
|
6
|
+
|
|
7
|
+
/** What a migration's `up` receives. */
|
|
8
|
+
export type MigrationContext = {
|
|
9
|
+
/** The store's database, raw: a migration reads documents in their old shape. */
|
|
10
|
+
readonly db: Db;
|
|
11
|
+
/** The transaction's session, when the migration sets `transaction: true`. */
|
|
12
|
+
readonly session?: ClientSession;
|
|
13
|
+
/** Aborts when the migrations lock is lost. Pass it to long loops. */
|
|
14
|
+
readonly signal: AbortSignal;
|
|
15
|
+
/** A child of the runner's logger, with the migration's id and name. */
|
|
16
|
+
readonly logger: Logger;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* One data migration. Forward only. `up` must be safe to run again after it
|
|
21
|
+
* failed partway: the next run retries it.
|
|
22
|
+
*/
|
|
23
|
+
export type Migration = {
|
|
24
|
+
/** 1, 2, 3 … in list order. */
|
|
25
|
+
readonly id: number;
|
|
26
|
+
readonly name: string;
|
|
27
|
+
/** Runs `up` and its record in one transaction. Needs a replica set. */
|
|
28
|
+
readonly transaction?: boolean;
|
|
29
|
+
up(context: MigrationContext): Promise<void>;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export type MigrateOptions = {
|
|
33
|
+
readonly logger: Logger;
|
|
34
|
+
readonly lock?: {
|
|
35
|
+
/** A lease's lifetime without renewal. Default 60 000. */
|
|
36
|
+
readonly ttlMs?: number;
|
|
37
|
+
/** How long to wait for another process's lease. Default 600 000. */
|
|
38
|
+
readonly waitMs?: number;
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export type Ran = {
|
|
43
|
+
readonly id: number;
|
|
44
|
+
readonly name: string;
|
|
45
|
+
readonly durationMs: number;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/** What `_migrations` keeps for each migration that ran. */
|
|
49
|
+
type MigrationRecord = {
|
|
50
|
+
_id: number;
|
|
51
|
+
name: string;
|
|
52
|
+
ranAt: Date;
|
|
53
|
+
durationMs: number;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/** The list's own checks: ids 1, 2, 3 … in order, none twice. */
|
|
57
|
+
function checkList(migrations: readonly Migration[]): void {
|
|
58
|
+
const seen = new Set<number>();
|
|
59
|
+
for (const { id } of migrations) {
|
|
60
|
+
if (seen.has(id)) throw MigrationError.Duplicate({ id });
|
|
61
|
+
seen.add(id);
|
|
62
|
+
}
|
|
63
|
+
migrations.forEach(({ id }, index) => {
|
|
64
|
+
if (id !== index + 1) {
|
|
65
|
+
throw MigrationError.Gap({ expected: index + 1, found: id });
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The recorded migrations against the list: none missing, none renamed. */
|
|
71
|
+
function checkRecords(
|
|
72
|
+
migrations: readonly Migration[],
|
|
73
|
+
records: readonly MigrationRecord[],
|
|
74
|
+
): void {
|
|
75
|
+
for (const record of records) {
|
|
76
|
+
const listed = migrations[record._id - 1];
|
|
77
|
+
if (listed === undefined) {
|
|
78
|
+
throw MigrationError.Unknown({ id: record._id, name: record.name });
|
|
79
|
+
}
|
|
80
|
+
if (listed.name !== record.name) {
|
|
81
|
+
throw MigrationError.Renamed({
|
|
82
|
+
id: record._id,
|
|
83
|
+
recorded: record.name,
|
|
84
|
+
listed: listed.name,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Whether the deployment runs transactions: a replica set or a mongos. */
|
|
91
|
+
async function hasTransactions(db: Db): Promise<boolean> {
|
|
92
|
+
const hello = await db.admin().command({ hello: 1 });
|
|
93
|
+
return typeof hello.setName === 'string' || hello.msg === 'isdbgrid';
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Runs each pending migration once, in id order, under a lease lock in the
|
|
98
|
+
* store's database (0027). The store must be started. A second process
|
|
99
|
+
* waits for the lock, then finds nothing left to run. A migration that
|
|
100
|
+
* throws is not recorded: the error passes through, and the next run
|
|
101
|
+
* retries it.
|
|
102
|
+
*/
|
|
103
|
+
export async function migrate(
|
|
104
|
+
store: MongoStore,
|
|
105
|
+
migrations: readonly Migration[],
|
|
106
|
+
options: MigrateOptions,
|
|
107
|
+
): Promise<{ readonly ran: readonly Ran[] }> {
|
|
108
|
+
const { client, db } = connectionOf(store);
|
|
109
|
+
const { logger } = options;
|
|
110
|
+
checkList(migrations);
|
|
111
|
+
const lock: MigrationLock = leaseLock(db, {
|
|
112
|
+
ttlMs: options.lock?.ttlMs ?? 60_000,
|
|
113
|
+
waitMs: options.lock?.waitMs ?? 600_000,
|
|
114
|
+
onWait: (heldSince) =>
|
|
115
|
+
logger.info('migrations waiting for lock', {
|
|
116
|
+
...(heldSince === undefined
|
|
117
|
+
? {}
|
|
118
|
+
: { heldSince: heldSince.toISOString() }),
|
|
119
|
+
}),
|
|
120
|
+
});
|
|
121
|
+
const records = db.collection<MigrationRecord>('_migrations');
|
|
122
|
+
|
|
123
|
+
return lock.run(async (signal) => {
|
|
124
|
+
const recorded = await records.find().sort({ _id: 1 }).toArray();
|
|
125
|
+
checkRecords(migrations, recorded);
|
|
126
|
+
const pending = migrations.slice(recorded.length);
|
|
127
|
+
const transactional = pending.find((migration) => migration.transaction);
|
|
128
|
+
if (transactional !== undefined && !(await hasTransactions(db))) {
|
|
129
|
+
throw MigrationError.NoTransactions({ id: transactional.id });
|
|
130
|
+
}
|
|
131
|
+
if (pending.length === 0) {
|
|
132
|
+
logger.info('migrations up to date', { last: recorded.length });
|
|
133
|
+
return { ran: [] };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const ran: Ran[] = [];
|
|
137
|
+
for (const migration of pending) {
|
|
138
|
+
if (signal.aborted) throw MigrationError.LockLost();
|
|
139
|
+
const { id, name } = migration;
|
|
140
|
+
const context = { db, signal, logger: logger.child({ id, name }) };
|
|
141
|
+
const started = performance.now();
|
|
142
|
+
const record = (durationMs: number): MigrationRecord => ({
|
|
143
|
+
_id: id,
|
|
144
|
+
name,
|
|
145
|
+
ranAt: new Date(),
|
|
146
|
+
durationMs,
|
|
147
|
+
});
|
|
148
|
+
try {
|
|
149
|
+
if (migration.transaction === true) {
|
|
150
|
+
await client.withSession((session) =>
|
|
151
|
+
session.withTransaction(async () => {
|
|
152
|
+
await migration.up({ ...context, session });
|
|
153
|
+
if (signal.aborted) throw MigrationError.LockLost();
|
|
154
|
+
await records.insertOne(record(since(started)), { session });
|
|
155
|
+
}),
|
|
156
|
+
);
|
|
157
|
+
} else {
|
|
158
|
+
await migration.up(context);
|
|
159
|
+
// The lock was lost while it ran: another process may run it
|
|
160
|
+
// too, so it is not recorded here. up is safe to re-run.
|
|
161
|
+
if (signal.aborted) throw MigrationError.LockLost();
|
|
162
|
+
await records.insertOne(record(since(started)));
|
|
163
|
+
}
|
|
164
|
+
} catch (error) {
|
|
165
|
+
const fields = {
|
|
166
|
+
id,
|
|
167
|
+
name,
|
|
168
|
+
durationMs: since(started),
|
|
169
|
+
outcome: 'failed',
|
|
170
|
+
};
|
|
171
|
+
if (error instanceof Error) logger.error(error, fields);
|
|
172
|
+
else logger.error('migration', { ...fields, thrown: String(error) });
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
const durationMs = since(started);
|
|
176
|
+
logger.info('migration', { id, name, durationMs, outcome: 'ok' });
|
|
177
|
+
ran.push({ id, name, durationMs });
|
|
178
|
+
}
|
|
179
|
+
return { ran };
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function since(started: number): number {
|
|
184
|
+
return Math.round(performance.now() - started);
|
|
185
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Errors } from 'hexok';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Why `migrate` refused to run, or stopped. The list checks (`Gap`,
|
|
6
|
+
* `Duplicate`, `Unknown`, `Renamed`) and `NoTransactions` throw before any
|
|
7
|
+
* migration runs.
|
|
8
|
+
*/
|
|
9
|
+
export class MigrationError extends Errors('migrations', {
|
|
10
|
+
Gap: {
|
|
11
|
+
message: 'Migration ids must run 1, 2, 3 … in list order, with no gap',
|
|
12
|
+
data: z.object({ expected: z.number(), found: z.number() }),
|
|
13
|
+
},
|
|
14
|
+
Duplicate: {
|
|
15
|
+
message: 'Two migrations share an id',
|
|
16
|
+
data: z.object({ id: z.number() }),
|
|
17
|
+
},
|
|
18
|
+
Unknown: {
|
|
19
|
+
message: 'A migration that ran is missing from the list',
|
|
20
|
+
data: z.object({ id: z.number(), name: z.string() }),
|
|
21
|
+
},
|
|
22
|
+
Renamed: {
|
|
23
|
+
message: 'A migration that ran has another name in the list',
|
|
24
|
+
data: z.object({
|
|
25
|
+
id: z.number(),
|
|
26
|
+
recorded: z.string(),
|
|
27
|
+
listed: z.string(),
|
|
28
|
+
}),
|
|
29
|
+
},
|
|
30
|
+
NoTransactions: {
|
|
31
|
+
message: 'A migration asks for a transaction, but the deployment has none',
|
|
32
|
+
data: z.object({ id: z.number() }),
|
|
33
|
+
},
|
|
34
|
+
LockTimeout: {
|
|
35
|
+
message: 'Another process held the migrations lock for longer than waitMs',
|
|
36
|
+
data: z.object({ waitMs: z.number() }),
|
|
37
|
+
},
|
|
38
|
+
LockLost: {
|
|
39
|
+
message: 'The migrations lock was lost while a migration ran',
|
|
40
|
+
},
|
|
41
|
+
}) {}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import type { Db } from 'mongodb';
|
|
2
|
+
import { MigrationError } from './migration-error.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The lock migrations run under. An internal seam: the lease below can be
|
|
6
|
+
* replaced by another lock, such as a hexok one, without touching the
|
|
7
|
+
* runner (0027).
|
|
8
|
+
*/
|
|
9
|
+
export type MigrationLock = {
|
|
10
|
+
/**
|
|
11
|
+
* Waits for the lock, runs `work` while holding it, and releases it.
|
|
12
|
+
* `signal` aborts when the lock is lost.
|
|
13
|
+
*/
|
|
14
|
+
run<T>(work: (signal: AbortSignal) => Promise<T>): Promise<T>;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/** The lease document: who holds the lock, and until when by the server's clock. */
|
|
18
|
+
type Lease = {
|
|
19
|
+
_id: string;
|
|
20
|
+
token: string;
|
|
21
|
+
acquiredAt: Date;
|
|
22
|
+
expiresAt: Date;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export type LeaseOptions = {
|
|
26
|
+
/** How long a lease lives without a renewal. It is renewed every third. */
|
|
27
|
+
readonly ttlMs: number;
|
|
28
|
+
/** How long to wait for another process's lease before `LockTimeout`. */
|
|
29
|
+
readonly waitMs: number;
|
|
30
|
+
/** Called once, when the lock is held by another process and the run waits. */
|
|
31
|
+
readonly onWait: (heldSince: Date | undefined) => void;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const leaseId = 'migrations';
|
|
35
|
+
|
|
36
|
+
/** Resolves after `ms`, or at once when `signal` aborts. */
|
|
37
|
+
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
38
|
+
return new Promise((resolve) => {
|
|
39
|
+
const timer = setTimeout(done, ms);
|
|
40
|
+
function done() {
|
|
41
|
+
clearTimeout(timer);
|
|
42
|
+
signal?.removeEventListener('abort', done);
|
|
43
|
+
resolve();
|
|
44
|
+
}
|
|
45
|
+
signal?.addEventListener('abort', done, { once: true });
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* A lease in `_migrations_lock`, in the database being migrated. Taken
|
|
51
|
+
* atomically with the server's clock (`$$NOW`), so clocks on different
|
|
52
|
+
* hosts do not matter; renewed every third of its TTL; released by its
|
|
53
|
+
* random token, so a process never releases another's lease. A lease whose
|
|
54
|
+
* holder died expires and is taken over.
|
|
55
|
+
*/
|
|
56
|
+
export function leaseLock(db: Db, options: LeaseOptions): MigrationLock {
|
|
57
|
+
const leases = db.collection<Lease>('_migrations_lock');
|
|
58
|
+
const { ttlMs, waitMs } = options;
|
|
59
|
+
|
|
60
|
+
async function acquire(token: string): Promise<boolean> {
|
|
61
|
+
// One atomic update, on the server's clock: it takes the lease only
|
|
62
|
+
// when it has expired, or does not exist yet (a missing expiresAt
|
|
63
|
+
// compares below any date). Otherwise it leaves the holder's fields as
|
|
64
|
+
// they are. The returned token says who holds it.
|
|
65
|
+
const expired = { $lt: ['$expiresAt', '$$NOW'] };
|
|
66
|
+
const lease = await leases.findOneAndUpdate(
|
|
67
|
+
{ _id: leaseId },
|
|
68
|
+
[
|
|
69
|
+
{
|
|
70
|
+
$set: {
|
|
71
|
+
token: { $cond: [expired, token, '$token'] },
|
|
72
|
+
acquiredAt: { $cond: [expired, '$$NOW', '$acquiredAt'] },
|
|
73
|
+
expiresAt: {
|
|
74
|
+
$cond: [expired, { $add: ['$$NOW', ttlMs] }, '$expiresAt'],
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
],
|
|
79
|
+
{ upsert: true, returnDocument: 'after' },
|
|
80
|
+
);
|
|
81
|
+
return lease?.token === token;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function renew(token: string): Promise<boolean> {
|
|
85
|
+
const result = await leases.updateOne({ _id: leaseId, token }, [
|
|
86
|
+
{ $set: { expiresAt: { $add: ['$$NOW', ttlMs] } } },
|
|
87
|
+
]);
|
|
88
|
+
return result.matchedCount === 1;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function wait(token: string): Promise<void> {
|
|
92
|
+
const deadline = Date.now() + waitMs;
|
|
93
|
+
const poll = Math.min(1000, ttlMs / 3);
|
|
94
|
+
let waited = false;
|
|
95
|
+
while (!(await acquire(token))) {
|
|
96
|
+
if (!waited) {
|
|
97
|
+
waited = true;
|
|
98
|
+
const held = await leases.findOne({ _id: leaseId });
|
|
99
|
+
options.onWait(held?.acquiredAt);
|
|
100
|
+
}
|
|
101
|
+
const left = deadline - Date.now();
|
|
102
|
+
if (left <= 0) throw MigrationError.LockTimeout({ waitMs });
|
|
103
|
+
await sleep(Math.min(poll, left));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
async run(work) {
|
|
109
|
+
const token = crypto.randomUUID();
|
|
110
|
+
await wait(token);
|
|
111
|
+
const lost = new AbortController();
|
|
112
|
+
// A lease is good until the TTL after its last renewal was sent. Abort
|
|
113
|
+
// a margin before that, so this process stops before another can take
|
|
114
|
+
// the lock, even when a renewal never answers.
|
|
115
|
+
const margin = Math.min(1000, ttlMs / 4);
|
|
116
|
+
let sent = Date.now();
|
|
117
|
+
const stopped = new AbortController();
|
|
118
|
+
const keep = (async () => {
|
|
119
|
+
while (!stopped.signal.aborted && !lost.signal.aborted) {
|
|
120
|
+
await sleep(ttlMs / 3, stopped.signal);
|
|
121
|
+
if (stopped.signal.aborted) return;
|
|
122
|
+
const at = Date.now();
|
|
123
|
+
const renewed = await Promise.race([
|
|
124
|
+
renew(token).catch(() => false),
|
|
125
|
+
sleep(Math.max(0, sent + ttlMs - margin - at), stopped.signal).then(
|
|
126
|
+
() => false,
|
|
127
|
+
),
|
|
128
|
+
]);
|
|
129
|
+
if (stopped.signal.aborted) return;
|
|
130
|
+
if (!renewed) {
|
|
131
|
+
lost.abort(MigrationError.LockLost());
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
sent = at;
|
|
135
|
+
}
|
|
136
|
+
})();
|
|
137
|
+
try {
|
|
138
|
+
return await work(lost.signal);
|
|
139
|
+
} finally {
|
|
140
|
+
stopped.abort();
|
|
141
|
+
await keep;
|
|
142
|
+
await leases.deleteOne({ _id: leaseId, token });
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
}
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type AnyWhere,
|
|
3
|
+
CollectionStore,
|
|
4
|
+
type FindQuery,
|
|
5
|
+
type Index,
|
|
6
|
+
type Page,
|
|
7
|
+
type Patch,
|
|
8
|
+
type StoredDoc,
|
|
9
|
+
} from '@latticecms/core/store';
|
|
10
|
+
import { Adapter } from 'hexok';
|
|
11
|
+
import { type Db, MongoClient, type MongoClientOptions } from 'mongodb';
|
|
12
|
+
import { MongoStoreError } from './errors.js';
|
|
13
|
+
import { MongoDoc } from './mapper.js';
|
|
14
|
+
import { MongoOperations } from './operations.js';
|
|
15
|
+
import { traced } from './tracing.js';
|
|
16
|
+
|
|
17
|
+
export type MongoStoreOptions = {
|
|
18
|
+
/** A `mongodb://` or `mongodb+srv://` connection string. */
|
|
19
|
+
readonly url: string;
|
|
20
|
+
/** The database every collection lives in. */
|
|
21
|
+
readonly database: string;
|
|
22
|
+
/**
|
|
23
|
+
* Options for the store's `MongoClient`. `serverSelectionTimeoutMS`
|
|
24
|
+
* bounds how long `start()` waits for the server.
|
|
25
|
+
*/
|
|
26
|
+
readonly client?: MongoClientOptions;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The started client of each store, for this package's migrations runner.
|
|
31
|
+
* Not exported from the package: a store's public surface is the port,
|
|
32
|
+
* `start` and `stop`.
|
|
33
|
+
*/
|
|
34
|
+
const connections = new WeakMap<
|
|
35
|
+
MongoStore,
|
|
36
|
+
() => { readonly client: MongoClient; readonly db: Db }
|
|
37
|
+
>();
|
|
38
|
+
|
|
39
|
+
/** The client and database of a started store, or its lifecycle error. */
|
|
40
|
+
export function connectionOf(store: MongoStore): {
|
|
41
|
+
readonly client: MongoClient;
|
|
42
|
+
readonly db: Db;
|
|
43
|
+
} {
|
|
44
|
+
const connection = connections.get(store);
|
|
45
|
+
if (connection === undefined) throw MongoStoreError.NotStarted();
|
|
46
|
+
return connection();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
type State =
|
|
50
|
+
| { readonly kind: 'idle' }
|
|
51
|
+
| {
|
|
52
|
+
readonly kind: 'starting';
|
|
53
|
+
readonly client: MongoClient;
|
|
54
|
+
readonly ready: Promise<{ db: Db; transactions: boolean }>;
|
|
55
|
+
}
|
|
56
|
+
| {
|
|
57
|
+
readonly kind: 'ready';
|
|
58
|
+
readonly client: MongoClient;
|
|
59
|
+
readonly db: Db;
|
|
60
|
+
/** A replica set or a mongos, which run transactions. */
|
|
61
|
+
readonly transactions: boolean;
|
|
62
|
+
}
|
|
63
|
+
| { readonly kind: 'stopped' };
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The MongoDB `CollectionStore`. It owns its `MongoClient` (0025): `start()`
|
|
67
|
+
* connects and pings, and `stop()` closes the client. A call before
|
|
68
|
+
* `start()`, during it, or after `stop()` rejects with `MongoStoreError`.
|
|
69
|
+
* Each Lattice collection is a Mongo collection of the same name, and a
|
|
70
|
+
* document's `id` is its `_id`.
|
|
71
|
+
*/
|
|
72
|
+
export class MongoStore extends Adapter(CollectionStore) {
|
|
73
|
+
#state: State = { kind: 'idle' };
|
|
74
|
+
readonly #docs = new MongoDoc();
|
|
75
|
+
|
|
76
|
+
constructor(private readonly options: MongoStoreOptions) {
|
|
77
|
+
super();
|
|
78
|
+
connections.set(this, () => this.#connection());
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Connects and pings the server. A `start()` while one is pending joins
|
|
83
|
+
* it; one after `stop()` opens a new client. Rejects with `Stopped` when
|
|
84
|
+
* `stop()` is called before it finishes.
|
|
85
|
+
*/
|
|
86
|
+
override async start(): Promise<void> {
|
|
87
|
+
const state = this.#state;
|
|
88
|
+
if (state.kind === 'ready') return;
|
|
89
|
+
if (state.kind === 'starting') {
|
|
90
|
+
await this.#joined(state.ready);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const client = new MongoClient(this.options.url, this.options.client);
|
|
94
|
+
const ready = (async () => {
|
|
95
|
+
await client.connect();
|
|
96
|
+
const db = client.db(this.options.database);
|
|
97
|
+
const hello = await db.admin().command({ hello: 1 });
|
|
98
|
+
const transactions =
|
|
99
|
+
typeof hello.setName === 'string' || hello.msg === 'isdbgrid';
|
|
100
|
+
return { db, transactions };
|
|
101
|
+
})();
|
|
102
|
+
const starting: State = { kind: 'starting', client, ready };
|
|
103
|
+
this.#state = starting;
|
|
104
|
+
try {
|
|
105
|
+
const { db, transactions } = await ready;
|
|
106
|
+
if (this.#state !== starting) throw MongoStoreError.Stopped();
|
|
107
|
+
this.#state = { kind: 'ready', client, db, transactions };
|
|
108
|
+
} catch (error) {
|
|
109
|
+
// stop() closed the client under the pending connect: the driver's
|
|
110
|
+
// error says only that, so the caller gets Stopped.
|
|
111
|
+
if (this.#state !== starting) throw MongoStoreError.Stopped();
|
|
112
|
+
this.#state = { kind: 'idle' };
|
|
113
|
+
await client.close();
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Closes the client. A pending `start()` rejects with `Stopped`. */
|
|
119
|
+
override async stop(): Promise<void> {
|
|
120
|
+
const state = this.#state;
|
|
121
|
+
this.#state = { kind: 'stopped' };
|
|
122
|
+
if (state.kind === 'starting' || state.kind === 'ready') {
|
|
123
|
+
await state.client.close();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async #joined(ready: Promise<unknown>): Promise<void> {
|
|
128
|
+
try {
|
|
129
|
+
await ready;
|
|
130
|
+
} catch (error) {
|
|
131
|
+
if (this.#state.kind === 'stopped') throw MongoStoreError.Stopped();
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
if (this.#state.kind !== 'ready') throw MongoStoreError.Stopped();
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The client and database, or the lifecycle error for a call made now. */
|
|
138
|
+
#connection(): {
|
|
139
|
+
readonly client: MongoClient;
|
|
140
|
+
readonly db: Db;
|
|
141
|
+
readonly transactions: boolean;
|
|
142
|
+
} {
|
|
143
|
+
const state = this.#state;
|
|
144
|
+
switch (state.kind) {
|
|
145
|
+
case 'ready':
|
|
146
|
+
return state;
|
|
147
|
+
case 'idle':
|
|
148
|
+
throw MongoStoreError.NotStarted();
|
|
149
|
+
case 'starting':
|
|
150
|
+
throw MongoStoreError.Starting();
|
|
151
|
+
case 'stopped':
|
|
152
|
+
throw MongoStoreError.Stopped();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
#operations(): MongoOperations {
|
|
157
|
+
return new MongoOperations(this.#connection().db, this.#docs);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
override async ensure(
|
|
161
|
+
collection: string,
|
|
162
|
+
indexes: readonly Index[],
|
|
163
|
+
): Promise<void> {
|
|
164
|
+
return this.#operations().ensure(collection, indexes);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
override async find(query: FindQuery): Promise<Page> {
|
|
168
|
+
return this.#operations().find(query);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
override async count(collection: string, where?: AnyWhere): Promise<number> {
|
|
172
|
+
return this.#operations().count(collection, where);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
override async get(
|
|
176
|
+
collection: string,
|
|
177
|
+
id: string,
|
|
178
|
+
where?: AnyWhere,
|
|
179
|
+
): Promise<StoredDoc | null> {
|
|
180
|
+
return this.#operations().get(collection, id, where);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
override async getMany(
|
|
184
|
+
collection: string,
|
|
185
|
+
ids: readonly string[],
|
|
186
|
+
where?: AnyWhere,
|
|
187
|
+
): Promise<StoredDoc[]> {
|
|
188
|
+
return this.#operations().getMany(collection, ids, where);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
override async insert(collection: string, doc: StoredDoc): Promise<void> {
|
|
192
|
+
return this.#operations().insert(collection, doc);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
override async update(
|
|
196
|
+
collection: string,
|
|
197
|
+
id: string,
|
|
198
|
+
patch: Patch,
|
|
199
|
+
where?: AnyWhere,
|
|
200
|
+
): Promise<StoredDoc | null> {
|
|
201
|
+
return this.#operations().update(collection, id, patch, where);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
override async remove(
|
|
205
|
+
collection: string,
|
|
206
|
+
id: string,
|
|
207
|
+
where?: AnyWhere,
|
|
208
|
+
): Promise<StoredDoc | null> {
|
|
209
|
+
return this.#operations().remove(collection, id, where);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Runs `work` in one transaction on a replica set or a mongos, with a view
|
|
214
|
+
* of this store whose every call joins it. A standalone server has no
|
|
215
|
+
* transactions, so there `work` runs on this store, in order.
|
|
216
|
+
*/
|
|
217
|
+
override async transaction<T>(
|
|
218
|
+
work: (store: CollectionStore) => Promise<T>,
|
|
219
|
+
): Promise<T> {
|
|
220
|
+
const { client, db, transactions } = this.#connection();
|
|
221
|
+
if (!transactions) return work(this);
|
|
222
|
+
// One parent span, active while the transaction runs, so each call in it
|
|
223
|
+
// nests under it. The driver may run `work` again on a transient error;
|
|
224
|
+
// each run's calls nest under the same span.
|
|
225
|
+
return traced(db.databaseName, 'transaction', undefined, () =>
|
|
226
|
+
client.withSession((session) =>
|
|
227
|
+
session.withTransaction(() =>
|
|
228
|
+
work(
|
|
229
|
+
new TransactionStore(new MongoOperations(db, this.#docs, session)),
|
|
230
|
+
),
|
|
231
|
+
),
|
|
232
|
+
),
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* A store inside a transaction: every call carries the session, and a
|
|
239
|
+
* nested `transaction` joins it.
|
|
240
|
+
*/
|
|
241
|
+
class TransactionStore extends Adapter(CollectionStore) {
|
|
242
|
+
constructor(private readonly operations: MongoOperations) {
|
|
243
|
+
super();
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
override ensure(
|
|
247
|
+
collection: string,
|
|
248
|
+
indexes: readonly Index[],
|
|
249
|
+
): Promise<void> {
|
|
250
|
+
return this.operations.ensure(collection, indexes);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
override find(query: FindQuery): Promise<Page> {
|
|
254
|
+
return this.operations.find(query);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
override count(collection: string, where?: AnyWhere): Promise<number> {
|
|
258
|
+
return this.operations.count(collection, where);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
override get(
|
|
262
|
+
collection: string,
|
|
263
|
+
id: string,
|
|
264
|
+
where?: AnyWhere,
|
|
265
|
+
): Promise<StoredDoc | null> {
|
|
266
|
+
return this.operations.get(collection, id, where);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
override getMany(
|
|
270
|
+
collection: string,
|
|
271
|
+
ids: readonly string[],
|
|
272
|
+
where?: AnyWhere,
|
|
273
|
+
): Promise<StoredDoc[]> {
|
|
274
|
+
return this.operations.getMany(collection, ids, where);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
override insert(collection: string, doc: StoredDoc): Promise<void> {
|
|
278
|
+
return this.operations.insert(collection, doc);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
override update(
|
|
282
|
+
collection: string,
|
|
283
|
+
id: string,
|
|
284
|
+
patch: Patch,
|
|
285
|
+
where?: AnyWhere,
|
|
286
|
+
): Promise<StoredDoc | null> {
|
|
287
|
+
return this.operations.update(collection, id, patch, where);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
override remove(
|
|
291
|
+
collection: string,
|
|
292
|
+
id: string,
|
|
293
|
+
where?: AnyWhere,
|
|
294
|
+
): Promise<StoredDoc | null> {
|
|
295
|
+
return this.operations.remove(collection, id, where);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
override transaction<T>(
|
|
299
|
+
work: (store: CollectionStore) => Promise<T>,
|
|
300
|
+
): Promise<T> {
|
|
301
|
+
return work(this);
|
|
302
|
+
}
|
|
303
|
+
}
|