@proteinjs/db 1.34.3 → 1.35.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/CHANGELOG.md +22 -0
- package/dist/generated/index.js +1 -1
- package/dist/generated/index.js.map +1 -1
- package/dist/generated/test/index.d.ts.map +1 -1
- package/dist/generated/test/index.js +3 -1
- package/dist/generated/test/index.js.map +1 -1
- package/dist/src/Db.d.ts +10 -0
- package/dist/src/Db.d.ts.map +1 -1
- package/dist/src/Db.js +42 -2
- package/dist/src/Db.js.map +1 -1
- package/dist/src/MigrationRunner.d.ts +26 -0
- package/dist/src/MigrationRunner.d.ts.map +1 -1
- package/dist/src/MigrationRunner.js +82 -0
- package/dist/src/MigrationRunner.js.map +1 -1
- package/dist/src/source/SourceRecord.d.ts +35 -2
- package/dist/src/source/SourceRecord.d.ts.map +1 -1
- package/dist/src/source/SourceRecord.js +8 -1
- package/dist/src/source/SourceRecord.js.map +1 -1
- package/dist/src/source/SourceRecordLoader.d.ts +105 -7
- package/dist/src/source/SourceRecordLoader.d.ts.map +1 -1
- package/dist/src/source/SourceRecordLoader.js +358 -94
- package/dist/src/source/SourceRecordLoader.js.map +1 -1
- package/dist/src/tables/MigrationTable.d.ts +26 -0
- package/dist/src/tables/MigrationTable.d.ts.map +1 -1
- package/dist/src/tables/MigrationTable.js +1 -0
- package/dist/src/tables/MigrationTable.js.map +1 -1
- package/dist/test/reusable/SourceRecordSyncTests.d.ts.map +1 -1
- package/dist/test/reusable/SourceRecordSyncTests.js +803 -27
- package/dist/test/reusable/SourceRecordSyncTests.js.map +1 -1
- package/dist/test/util/tables/sourceRecordSyncTestTables.d.ts +16 -0
- package/dist/test/util/tables/sourceRecordSyncTestTables.d.ts.map +1 -1
- package/dist/test/util/tables/sourceRecordSyncTestTables.js +23 -1
- package/dist/test/util/tables/sourceRecordSyncTestTables.js.map +1 -1
- package/generated/index.ts +1 -1
- package/generated/test/index.ts +3 -1
- package/package.json +4 -4
- package/src/Db.ts +19 -0
- package/src/MigrationRunner.ts +62 -0
- package/src/source/SourceRecord.ts +42 -4
- package/src/source/SourceRecordLoader.ts +342 -48
- package/src/tables/MigrationTable.ts +24 -0
- package/test/reusable/SourceRecordSyncTests.ts +462 -11
- package/test/util/tables/sourceRecordSyncTestTables.ts +20 -0
|
@@ -6,32 +6,119 @@ import { Db, getDbAsSystem } from '../Db';
|
|
|
6
6
|
import { SourceRecordRepo } from './SourceRecordRepo';
|
|
7
7
|
import { RecordSerializer } from '../Record';
|
|
8
8
|
|
|
9
|
+
type DeclaredRecord = {
|
|
10
|
+
/** The owning package (the declaring loader's package) — the grain the sync prunes within. */
|
|
11
|
+
source: string;
|
|
12
|
+
record: Omit<SourceRecord, 'created' | 'updated'>;
|
|
13
|
+
};
|
|
14
|
+
|
|
9
15
|
type SourceRecordsMap = {
|
|
10
|
-
[tableName: string]: { table: Table<any>; records:
|
|
16
|
+
[tableName: string]: { table: Table<any>; records: DeclaredRecord[] };
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** What one boot of the sync did to one source-record table. */
|
|
20
|
+
export type SourceRecordTableLoadSummary = {
|
|
21
|
+
inserts: number;
|
|
22
|
+
updates: number;
|
|
23
|
+
unchanged: number;
|
|
24
|
+
adopted: number;
|
|
25
|
+
deletes: number;
|
|
26
|
+
removedUpdates: number;
|
|
27
|
+
/** Rows stamped by a newer version of their declaring package — left exactly as they are. */
|
|
28
|
+
skippedNewer: number;
|
|
29
|
+
/** Source-loaded rows with no owner stamp that no declaration in this build claims. */
|
|
30
|
+
unowned: number;
|
|
11
31
|
};
|
|
12
32
|
|
|
33
|
+
export type SourceRecordLoadSummary = { [tableName: string]: SourceRecordTableLoadSummary };
|
|
34
|
+
|
|
13
35
|
export class SourceRecordLoader {
|
|
14
36
|
private logger = new Logger({ name: this.constructor.name });
|
|
15
37
|
|
|
16
|
-
|
|
17
|
-
|
|
38
|
+
/** Memo of resolved package versions — one resolution (and at most one warning) per source. */
|
|
39
|
+
private sourceVersions = new Map<string, string | undefined>();
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* One boot of the source-record sync, per source-record table in this build. Returns what it
|
|
43
|
+
* did to each table (also logged).
|
|
44
|
+
*
|
|
45
|
+
* Ownership model — every row has one owner, the package that declares it, ordered by that
|
|
46
|
+
* package's version:
|
|
47
|
+
* - A boot speaks only for the packages it carries. Rows owned by a package this build does
|
|
48
|
+
* not carry are never touched: several servers running different builds against one shared
|
|
49
|
+
* database coexist without pruning each other's rows.
|
|
50
|
+
* - Within a package, a boot speaks only for its own version or older. A row stamped by a
|
|
51
|
+
* NEWER version of the same package is left exactly as it is — neither pruned nor rewritten —
|
|
52
|
+
* so ordinary version skew (an older build restarting against rows a newer build added or
|
|
53
|
+
* redefined) cannot delete or churn data. The newest version stays authoritative for
|
|
54
|
+
* genuine removals and redefinitions.
|
|
55
|
+
* - A package in the build is authoritative for all of its rows on every table, including
|
|
56
|
+
* tables it no longer declares anything for: dropping the last declaration is a removal.
|
|
57
|
+
* - Rows with no owner stamp (written before `source_package` existed) are claimed by the
|
|
58
|
+
* declaration that still matches them; the rest are reported as unowned and left alone.
|
|
59
|
+
*
|
|
60
|
+
* Accepted residuals: a package removed from every build leaves its rows behind (no surviving
|
|
61
|
+
* boot carries its authority — clean up explicitly); two builds of one package at the SAME
|
|
62
|
+
* version with differing sets (uncommitted local skew) are last-writer-wins, since versions
|
|
63
|
+
* cannot order them.
|
|
64
|
+
*
|
|
65
|
+
* With no argument, every source-record table is synced (the `Db.init` full pass). Passing
|
|
66
|
+
* `onlyTable` scopes the sync to that one table — the pre-schema-sync migration phase uses
|
|
67
|
+
* this to land the migration ledger's rows before the full schema sync has run (see
|
|
68
|
+
* {@link MigrationRunner.runPreSchemaSyncMigrations}); the later full pass re-reconciles the
|
|
69
|
+
* same rows idempotently under the same ownership model.
|
|
70
|
+
*/
|
|
71
|
+
async load(onlyTable?: Table<any>): Promise<SourceRecordLoadSummary> {
|
|
72
|
+
const { tables, buildSources } = await this.getDeclarations();
|
|
18
73
|
const db = getDbAsSystem();
|
|
19
|
-
|
|
20
|
-
|
|
74
|
+
const summary: SourceRecordLoadSummary = {};
|
|
75
|
+
for (const tableName in tables) {
|
|
76
|
+
if (onlyTable && tableName !== onlyTable.name) {
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
const { table, records } = tables[tableName];
|
|
21
80
|
// 'id' unless the table declares a natural key (validated: unique-indexed, present and
|
|
22
81
|
// unambiguous across declarations).
|
|
23
|
-
const keyProperty = this.validateSyncKey(
|
|
24
|
-
|
|
25
|
-
|
|
82
|
+
const keyProperty = this.validateSyncKey(
|
|
83
|
+
table,
|
|
84
|
+
records.map(({ record }) => record)
|
|
85
|
+
);
|
|
86
|
+
// The exclusion set is the UNION of every key the build declares for the table: a key
|
|
87
|
+
// declared by ANY package in this build is re-owned by the stamp leg, never pruned (a
|
|
88
|
+
// declaration moving between packages within one build must not transit a delete+re-insert).
|
|
89
|
+
const allDeclaredKeys = records.map(({ record }) => (record as any)[keyProperty]);
|
|
90
|
+
const removed = await this.reconcileRemoved(db, table, keyProperty, buildSources, allDeclaredKeys);
|
|
26
91
|
|
|
27
92
|
let insertCount = 0;
|
|
28
93
|
let updateCount = 0;
|
|
29
94
|
let unchangedCount = 0;
|
|
30
95
|
let adoptedCount = 0;
|
|
31
|
-
|
|
96
|
+
let skippedNewer = removed.skippedNewer;
|
|
97
|
+
for (const { source, record } of records) {
|
|
98
|
+
let sourceRecord = record;
|
|
32
99
|
sourceRecord.isLoadedFromSource = true;
|
|
100
|
+
// Ownership stamp: the declaring package (and its version) claims the row. Stamped
|
|
101
|
+
// before the drift comparison so pre-existing rows (including pre-source_package legacy
|
|
102
|
+
// rows and rows whose declaration moved packages) converge to the current owner on
|
|
103
|
+
// their next boot.
|
|
104
|
+
sourceRecord.sourcePackage = source;
|
|
105
|
+
const sourceVersion = this.sourceVersion(source);
|
|
106
|
+
if (sourceVersion !== undefined) {
|
|
107
|
+
sourceRecord.sourcePackageVersion = sourceVersion;
|
|
108
|
+
}
|
|
33
109
|
const existingRecord = await db.get(table, { [keyProperty]: (sourceRecord as any)[keyProperty] });
|
|
34
110
|
if (existingRecord) {
|
|
111
|
+
if (
|
|
112
|
+
existingRecord.sourcePackage === source &&
|
|
113
|
+
this.isNewerStamp(existingRecord.sourcePackageVersion, sourceVersion)
|
|
114
|
+
) {
|
|
115
|
+
// A newer version of this very package already defined the row: this build's older
|
|
116
|
+
// definition does not land, and the row's stamp is not downgraded.
|
|
117
|
+
skippedNewer += 1;
|
|
118
|
+
new SourceRecordRepo().loadSourceRecord(table.name, existingRecord);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
|
|
35
122
|
if (existingRecord.id !== sourceRecord.id) {
|
|
36
123
|
// Adopt in place: the existing row keeps its id — other tables may reference it.
|
|
37
124
|
// The declared id is only ever used for fresh inserts.
|
|
@@ -64,61 +151,118 @@ export class SourceRecordLoader {
|
|
|
64
151
|
new SourceRecordRepo().loadSourceRecord(table.name, sourceRecord as any);
|
|
65
152
|
}
|
|
66
153
|
|
|
154
|
+
const unowned = await this.countUnowned(db, table, keyProperty);
|
|
155
|
+
summary[table.name] = {
|
|
156
|
+
inserts: insertCount,
|
|
157
|
+
updates: updateCount,
|
|
158
|
+
unchanged: unchangedCount,
|
|
159
|
+
adopted: adoptedCount,
|
|
160
|
+
deletes: removed.deleteCount,
|
|
161
|
+
removedUpdates: removed.removedUpdateCount,
|
|
162
|
+
skippedNewer,
|
|
163
|
+
unowned,
|
|
164
|
+
};
|
|
67
165
|
this.logger.info({
|
|
68
166
|
message: `(${table.name}) Loaded ${records.length} ${records.length == 1 ? 'record' : 'records'} from source`,
|
|
69
|
-
obj:
|
|
70
|
-
inserts: insertCount,
|
|
71
|
-
updates: updateCount,
|
|
72
|
-
unchanged: unchangedCount,
|
|
73
|
-
adopted: adoptedCount,
|
|
74
|
-
deletes: deleteCount,
|
|
75
|
-
removedUpdates: removedUpdateCount,
|
|
76
|
-
},
|
|
167
|
+
obj: summary[table.name],
|
|
77
168
|
});
|
|
78
169
|
}
|
|
170
|
+
|
|
171
|
+
return summary;
|
|
79
172
|
}
|
|
80
173
|
|
|
81
174
|
/**
|
|
82
|
-
* The removed-reconcile leg: rows
|
|
83
|
-
*
|
|
84
|
-
* `
|
|
85
|
-
*
|
|
86
|
-
* `
|
|
175
|
+
* The removed-reconcile leg: rows owned by a package this build carries, at that package's
|
|
176
|
+
* version or older, that NO package in this build still declares
|
|
177
|
+
* (`is_loaded_from_source = true AND source_package IN <build's packages> AND <key> NOT IN
|
|
178
|
+
* <build's declared keys for the table>`, minus rows stamped by a newer version of their
|
|
179
|
+
* package) are handled per the table's `onSourceRemoved` policy — delete (default), keep, or
|
|
180
|
+
* update with a patch. The update leg applies the patch only to rows whose fields actually
|
|
181
|
+
* differ (idempotent boots), through `Db.update` so table watchers observe each write.
|
|
182
|
+
* See {@link load} for the ownership model.
|
|
87
183
|
*/
|
|
88
184
|
private async reconcileRemoved(
|
|
89
185
|
db: Db,
|
|
90
186
|
table: Table<any>,
|
|
91
187
|
keyProperty: string,
|
|
92
|
-
|
|
93
|
-
|
|
188
|
+
buildSources: Set<string>,
|
|
189
|
+
allDeclaredKeys: unknown[]
|
|
190
|
+
): Promise<{ deleteCount: number; removedUpdateCount: number; skippedNewer: number }> {
|
|
94
191
|
const policy = table.sourceRecordOptions.onSourceRemoved ?? 'delete';
|
|
95
|
-
if (policy === 'keep') {
|
|
96
|
-
return { deleteCount: 0, removedUpdateCount: 0 };
|
|
192
|
+
if (policy === 'keep' || buildSources.size == 0) {
|
|
193
|
+
return { deleteCount: 0, removedUpdateCount: 0, skippedNewer: 0 };
|
|
97
194
|
}
|
|
98
195
|
|
|
99
196
|
const qb = QueryBuilder.fromObject<SourceRecord>({ isLoadedFromSource: true }, table.name);
|
|
100
|
-
|
|
101
|
-
|
|
197
|
+
qb.condition({ field: 'sourcePackage', operator: 'IN', value: Array.from(buildSources) as any });
|
|
198
|
+
if (allDeclaredKeys.length > 0) {
|
|
199
|
+
qb.condition({ field: keyProperty as any, operator: 'NOT IN', value: allDeclaredKeys as any });
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const candidates: SourceRecord[] = await db.query(table, qb);
|
|
203
|
+
const stampedNewer = (candidate: SourceRecord) =>
|
|
204
|
+
this.isNewerStamp(candidate.sourcePackageVersion, this.sourceVersion(candidate.sourcePackage as string));
|
|
205
|
+
const removedRecords = candidates.filter((candidate) => !stampedNewer(candidate));
|
|
206
|
+
const skippedNewer = candidates.length - removedRecords.length;
|
|
207
|
+
if (skippedNewer > 0) {
|
|
208
|
+
this.logger.info({
|
|
209
|
+
message: `(${table.name}) Left ${skippedNewer} record${skippedNewer == 1 ? '' : 's'} stamped by a newer version of ${skippedNewer == 1 ? 'its' : 'their'} package — not treated as removed`,
|
|
210
|
+
obj: { [keyProperty]: candidates.filter(stampedNewer).map((candidate) => (candidate as any)[keyProperty]) },
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (removedRecords.length == 0) {
|
|
215
|
+
return { deleteCount: 0, removedUpdateCount: 0, skippedNewer };
|
|
102
216
|
}
|
|
103
217
|
|
|
104
218
|
if (policy === 'delete') {
|
|
105
|
-
|
|
219
|
+
const deleteQb = QueryBuilder.fromObject<SourceRecord>({ isLoadedFromSource: true }, table.name);
|
|
220
|
+
deleteQb.condition({ field: 'id', operator: 'IN', value: removedRecords.map((record) => record.id) });
|
|
221
|
+
return { deleteCount: await db.delete(table, deleteQb), removedUpdateCount: 0, skippedNewer };
|
|
106
222
|
}
|
|
107
223
|
|
|
108
224
|
let removedUpdateCount = 0;
|
|
109
|
-
const removedRecords = await db.query(table, qb);
|
|
110
225
|
for (const removedRecord of removedRecords) {
|
|
111
226
|
if (await this.hasChanges(table, policy.update, removedRecord)) {
|
|
112
227
|
await db.update(table, { id: removedRecord.id, ...policy.update });
|
|
113
228
|
removedUpdateCount += 1;
|
|
114
229
|
this.logger.info({
|
|
115
230
|
message: `(${table.name}) Applied onSourceRemoved update to record removed from source`,
|
|
116
|
-
obj: {
|
|
231
|
+
obj: {
|
|
232
|
+
id: removedRecord.id,
|
|
233
|
+
[keyProperty]: (removedRecord as any)[keyProperty],
|
|
234
|
+
source: removedRecord.sourcePackage,
|
|
235
|
+
},
|
|
117
236
|
});
|
|
118
237
|
}
|
|
119
238
|
}
|
|
120
239
|
|
|
121
|
-
return { deleteCount: 0, removedUpdateCount };
|
|
240
|
+
return { deleteCount: 0, removedUpdateCount, skippedNewer };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Source-loaded rows with no owner stamp that no declaration in this build claimed on this
|
|
245
|
+
* boot (the stamp leg has already run). They predate `source_package`, or their declaring
|
|
246
|
+
* package is not in this build; nobody prunes them. Reported so they are visible, never acted
|
|
247
|
+
* on. Tables that keep removed rows (`onSourceRemoved: 'keep'`) opted out of removal
|
|
248
|
+
* semantics altogether, so there is nothing to explain there.
|
|
249
|
+
*/
|
|
250
|
+
private async countUnowned(db: Db, table: Table<any>, keyProperty: string): Promise<number> {
|
|
251
|
+
if ((table.sourceRecordOptions.onSourceRemoved ?? 'delete') === 'keep') {
|
|
252
|
+
return 0;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const qb = QueryBuilder.fromObject<SourceRecord>({ isLoadedFromSource: true }, table.name);
|
|
256
|
+
qb.condition({ field: 'sourcePackage', operator: 'IS NULL' });
|
|
257
|
+
const unowned: SourceRecord[] = await db.query(table, qb);
|
|
258
|
+
if (unowned.length > 0) {
|
|
259
|
+
this.logger.warn({
|
|
260
|
+
message: `(${table.name}) ${unowned.length} source-loaded ${unowned.length == 1 ? 'record has' : 'records have'} no owning package and no declaration in this build — left untouched`,
|
|
261
|
+
obj: { [keyProperty]: unowned.map((record) => (record as any)[keyProperty]) },
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
return unowned.length;
|
|
122
266
|
}
|
|
123
267
|
|
|
124
268
|
/**
|
|
@@ -205,28 +349,27 @@ export class SourceRecordLoader {
|
|
|
205
349
|
return false;
|
|
206
350
|
}
|
|
207
351
|
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
352
|
+
/**
|
|
353
|
+
* Every source-record table in this build with the records declared for it, plus the set of
|
|
354
|
+
* packages that declare ANY source record in this build — the packages this boot speaks for.
|
|
355
|
+
*/
|
|
356
|
+
private async getDeclarations(): Promise<{ tables: SourceRecordsMap; buildSources: Set<string> }> {
|
|
357
|
+
const tables: SourceRecordsMap = {};
|
|
358
|
+
for (const table of getSourceRecordTables()) {
|
|
359
|
+
tables[table.name] = { table, records: [] };
|
|
215
360
|
}
|
|
216
361
|
|
|
217
|
-
const
|
|
218
|
-
for (const
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
records: [],
|
|
223
|
-
};
|
|
362
|
+
const buildSources = new Set<string>();
|
|
363
|
+
for (const { source, loader } of getSourceRecordLoaders()) {
|
|
364
|
+
buildSources.add(source);
|
|
365
|
+
if (!tables[loader.table.name]) {
|
|
366
|
+
tables[loader.table.name] = { table: loader.table, records: [] };
|
|
224
367
|
}
|
|
225
368
|
|
|
226
|
-
|
|
369
|
+
tables[loader.table.name].records.push({ source, record: loader.record });
|
|
227
370
|
}
|
|
228
371
|
|
|
229
|
-
return
|
|
372
|
+
return { tables, buildSources };
|
|
230
373
|
}
|
|
231
374
|
|
|
232
375
|
/**
|
|
@@ -323,4 +466,155 @@ export class SourceRecordLoader {
|
|
|
323
466
|
.sort();
|
|
324
467
|
return '{' + keys.map((k) => JSON.stringify(k) + ':' + this.canonicalStringify(obj[k])).join(',') + '}';
|
|
325
468
|
}
|
|
469
|
+
|
|
470
|
+
/** Memoized {@link resolveSourceVersion} — one resolution (and at most one warning) per source. */
|
|
471
|
+
private sourceVersion(source: string): string | undefined {
|
|
472
|
+
if (!this.sourceVersions.has(source)) {
|
|
473
|
+
this.sourceVersions.set(source, this.resolveSourceVersion(source));
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
return this.sourceVersions.get(source);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* The declaring package's version, read from its own package.json at runtime. Resolution runs
|
|
481
|
+
* from the process cwd — the booting server's package, the one dependency tree every declaring
|
|
482
|
+
* package is reachable from (`@proteinjs/db` itself does not depend on the packages that
|
|
483
|
+
* declare records, so module-relative resolution could never find them). The package's entry
|
|
484
|
+
* is resolved (honoring exports maps, where `<pkg>/package.json` is usually not requireable),
|
|
485
|
+
* then the nearest package.json whose `name` matches is read walking up from it.
|
|
486
|
+
*
|
|
487
|
+
* Returns undefined where resolution is impossible — no Node `require` (browser bundles), or a
|
|
488
|
+
* package not resolvable from cwd. The sync then has no place in the version order for that
|
|
489
|
+
* package: it never touches its version-stamped rows, and what it writes is unversioned
|
|
490
|
+
* (see {@link isNewerStamp}). Logged once per boot so a misconfigured cwd is visible.
|
|
491
|
+
*/
|
|
492
|
+
private resolveSourceVersion(source: string): string | undefined {
|
|
493
|
+
// The ambient CJS `require` — the only require carrying `.resolve` (module.require does
|
|
494
|
+
// not). Every use below goes through the variable, so bundlers never see a statically
|
|
495
|
+
// analyzable `require(...)` call; in a browser bundle the runtime attempts throw into
|
|
496
|
+
// their catches and the method degrades to undefined.
|
|
497
|
+
const nodeRequire: NodeRequire | undefined =
|
|
498
|
+
typeof require === 'function' && typeof require.resolve === 'function' ? require : undefined;
|
|
499
|
+
const cwd = typeof process !== 'undefined' && typeof process.cwd === 'function' ? process.cwd() : undefined;
|
|
500
|
+
if (nodeRequire && cwd) {
|
|
501
|
+
try {
|
|
502
|
+
const entryPath = nodeRequire.resolve(source, { paths: [cwd] });
|
|
503
|
+
const path = nodeRequire('path');
|
|
504
|
+
const fs = nodeRequire('fs');
|
|
505
|
+
// Walk up from the entry file to the package's own package.json (the name check skips
|
|
506
|
+
// nested stubs like a dist/package.json); stop at the filesystem root.
|
|
507
|
+
for (let directory = path.dirname(entryPath); ; directory = path.dirname(directory)) {
|
|
508
|
+
const candidate = path.join(directory, 'package.json');
|
|
509
|
+
if (fs.existsSync(candidate)) {
|
|
510
|
+
const packageJson = JSON.parse(fs.readFileSync(candidate, 'utf8'));
|
|
511
|
+
if (packageJson?.name === source && typeof packageJson.version === 'string') {
|
|
512
|
+
return packageJson.version;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
if (path.dirname(directory) === directory) {
|
|
517
|
+
break;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
} catch (error) {
|
|
521
|
+
// Unresolvable from cwd — reported below.
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
this.logger.warn({
|
|
526
|
+
message: `Could not resolve a version for source package '${source}' from '${cwd}' — its records sync without version ordering (this build never touches its version-stamped rows)`,
|
|
527
|
+
});
|
|
528
|
+
return undefined;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* Whether a row's version stamp is strictly newer than the reconciling build's version of the
|
|
533
|
+
* same package — the guard that makes version skew of one package safe on a shared database:
|
|
534
|
+
* an older build never prunes (or flags) rows a newer build of the same package declared.
|
|
535
|
+
*
|
|
536
|
+
* Unversioned stamps (NULL — legacy rows, or builds whose version could not be resolved)
|
|
537
|
+
* carry no ordering and stay reconcilable (last-writer-wins, the pre-version behavior). A
|
|
538
|
+
* build whose OWN version is unresolvable cannot place itself in the order, so it never
|
|
539
|
+
* touches a version-stamped row — conservative: prefer leaving a removed row behind over
|
|
540
|
+
* deleting one that might be newer.
|
|
541
|
+
*/
|
|
542
|
+
private isNewerStamp(stampedVersion: string | null | undefined, reconcilingVersion: string | undefined): boolean {
|
|
543
|
+
if (stampedVersion == null) {
|
|
544
|
+
return false;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
if (reconcilingVersion == null) {
|
|
548
|
+
return true;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
const comparison = this.compareVersions(stampedVersion, reconcilingVersion);
|
|
552
|
+
return comparison === undefined ? true : comparison > 0;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Semver comparison (major.minor.patch, prerelease-aware): negative when a < b, 0 when equal,
|
|
557
|
+
* positive when a > b, and undefined when either side does not parse as semver (unorderable —
|
|
558
|
+
* the caller treats that conservatively).
|
|
559
|
+
*/
|
|
560
|
+
private compareVersions(a: string, b: string): number | undefined {
|
|
561
|
+
const parse = (version: string): { main: number[]; prerelease?: string[] } | undefined => {
|
|
562
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?/.exec(version.trim());
|
|
563
|
+
if (!match) {
|
|
564
|
+
return undefined;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
return { main: [Number(match[1]), Number(match[2]), Number(match[3])], prerelease: match[4]?.split('.') };
|
|
568
|
+
};
|
|
569
|
+
|
|
570
|
+
const parsedA = parse(a);
|
|
571
|
+
const parsedB = parse(b);
|
|
572
|
+
if (!parsedA || !parsedB) {
|
|
573
|
+
return undefined;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
for (let i = 0; i < 3; i++) {
|
|
577
|
+
if (parsedA.main[i] !== parsedB.main[i]) {
|
|
578
|
+
return parsedA.main[i] - parsedB.main[i];
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
if (!parsedA.prerelease && !parsedB.prerelease) {
|
|
583
|
+
return 0;
|
|
584
|
+
}
|
|
585
|
+
if (!parsedA.prerelease) {
|
|
586
|
+
return 1; // a release outranks any prerelease of the same triple
|
|
587
|
+
}
|
|
588
|
+
if (!parsedB.prerelease) {
|
|
589
|
+
return -1;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
const length = Math.max(parsedA.prerelease.length, parsedB.prerelease.length);
|
|
593
|
+
for (let i = 0; i < length; i++) {
|
|
594
|
+
const identifierA = parsedA.prerelease[i];
|
|
595
|
+
const identifierB = parsedB.prerelease[i];
|
|
596
|
+
if (identifierA === undefined) {
|
|
597
|
+
return -1; // fewer identifiers sorts first when all shared ones are equal
|
|
598
|
+
}
|
|
599
|
+
if (identifierB === undefined) {
|
|
600
|
+
return 1;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
const numericA = /^\d+$/.test(identifierA) ? Number(identifierA) : undefined;
|
|
604
|
+
const numericB = /^\d+$/.test(identifierB) ? Number(identifierB) : undefined;
|
|
605
|
+
if (numericA !== undefined && numericB !== undefined) {
|
|
606
|
+
if (numericA !== numericB) {
|
|
607
|
+
return numericA - numericB;
|
|
608
|
+
}
|
|
609
|
+
} else if (numericA !== undefined) {
|
|
610
|
+
return -1; // numeric identifiers sort before alphanumeric ones
|
|
611
|
+
} else if (numericB !== undefined) {
|
|
612
|
+
return 1;
|
|
613
|
+
} else if (identifierA !== identifierB) {
|
|
614
|
+
return identifierA < identifierB ? -1 : 1;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
return 0;
|
|
619
|
+
}
|
|
326
620
|
}
|
|
@@ -14,6 +14,29 @@ export interface Migration extends SourceRecord {
|
|
|
14
14
|
* schema, not in deploy-pipeline prose.
|
|
15
15
|
*/
|
|
16
16
|
manual?: boolean;
|
|
17
|
+
/**
|
|
18
|
+
* Runs during `Db.init()` BEFORE schema sync (the pre-schema-sync phase —
|
|
19
|
+
* {@link MigrationRunner.runPreSchemaSyncMigrations}), instead of after init like the
|
|
20
|
+
* deploy-gated series. This is the class for data repairs a NEW SCHEMA INVARIANT depends on —
|
|
21
|
+
* e.g. deduplicating rows before a unique index lands: schema sync's unique-index preflight
|
|
22
|
+
* fails loudly over violating data ({@link DuplicateValuesForUniqueIndexError}), and the
|
|
23
|
+
* ordinary series (deploy Job, after init) is too late by construction.
|
|
24
|
+
*
|
|
25
|
+
* Contract for this class (stricter than the ordinary automated class):
|
|
26
|
+
* - IDEMPOTENT and tolerant of CONCURRENT duplicate runs: every booting replica and the deploy
|
|
27
|
+
* Job each run init — two actors can observe the row un-applied and both run the body.
|
|
28
|
+
* - TABLE-EXISTENCE tolerant: on a fresh database the body runs before ANY schema sync, so its
|
|
29
|
+
* target tables may not exist yet (check and no-op — a fresh database has nothing to repair).
|
|
30
|
+
* - Never `manual` (a contradiction — the phase exists to run unattended before DDL; declaring
|
|
31
|
+
* both fails init loudly).
|
|
32
|
+
* A failure fails `Db.init()` loudly (recorded on the ledger row, retried next boot) — exactly
|
|
33
|
+
* the failure the schema sync would otherwise hit, but named and retryable.
|
|
34
|
+
*
|
|
35
|
+
* The phase reads the SOURCE declaration (like {@link runPendingMigrations} reads
|
|
36
|
+
* `source.manual`); the column mirrors it into the ledger so the Migrations page shows why a
|
|
37
|
+
* row ran at boot.
|
|
38
|
+
*/
|
|
39
|
+
preSchemaSync?: boolean;
|
|
17
40
|
/**
|
|
18
41
|
* Ledger-owned state (like `status` — never declared on a source record): stamped `true` by the
|
|
19
42
|
* deploy-gated series ({@link MigrationRunner.runPendingMigrations}) when the row's source class
|
|
@@ -47,6 +70,7 @@ export class MigrationTable extends Table<Migration> {
|
|
|
47
70
|
public columns = withSourceRecordColumns<Migration>({
|
|
48
71
|
description: new StringColumn('description', {}, 4000),
|
|
49
72
|
manual: new BooleanColumn('manual'),
|
|
73
|
+
preSchemaSync: new BooleanColumn('pre_schema_sync'),
|
|
50
74
|
retired: new BooleanColumn('retired'),
|
|
51
75
|
status: new StringColumn('status', { defaultValue: async () => 'proposed' }),
|
|
52
76
|
failureMessage: new StringColumn('failure_message', {}, 4000),
|