@alexify/migronaut 2.0.0 → 2.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 (49) hide show
  1. package/CHANGELOG.md +320 -0
  2. package/README.md +208 -6
  3. package/bullmq.d.ts +845 -0
  4. package/bullmq.js +1 -0
  5. package/index.d.ts +634 -18
  6. package/migronaut.schema.json +182 -1
  7. package/package.json +21 -5
  8. package/src/bullmq/index.js +55 -0
  9. package/src/bullmq/jobs.js +454 -0
  10. package/src/bullmq/processor.js +608 -0
  11. package/src/bullmq/producer.js +424 -0
  12. package/src/bullmq/service.js +653 -0
  13. package/src/bullmq/wait.js +124 -0
  14. package/src/cli/args.js +12 -2
  15. package/src/cli/commands/converge.js +160 -0
  16. package/src/cli/commands/down.js +2 -0
  17. package/src/cli/commands/lock.js +2 -1
  18. package/src/cli/commands/redo.js +8 -1
  19. package/src/cli/commands/up.js +14 -1
  20. package/src/cli/exit-codes.js +9 -2
  21. package/src/cli/index.js +2 -0
  22. package/src/cli/shared.js +14 -4
  23. package/src/cli/table.js +105 -0
  24. package/src/core/changelog.js +71 -6
  25. package/src/core/collections.js +372 -0
  26. package/src/core/config.js +100 -25
  27. package/src/core/converge-log.js +47 -0
  28. package/src/core/converge-plan.js +483 -0
  29. package/src/core/converge.js +867 -0
  30. package/src/core/index-spec.js +496 -0
  31. package/src/core/lock-wait.js +260 -0
  32. package/src/core/lock.js +45 -16
  33. package/src/core/migrator.js +563 -283
  34. package/src/core/options.js +251 -0
  35. package/src/core/run-recorder.js +157 -0
  36. package/src/core/run.js +58 -90
  37. package/src/core/sequence.js +134 -0
  38. package/src/errors/index.js +56 -0
  39. package/src/index.js +8 -0
  40. package/src/utils/actor.js +48 -0
  41. package/src/utils/canonical.js +179 -0
  42. package/src/utils/collection-name.js +21 -0
  43. package/src/utils/error.js +18 -1
  44. package/src/utils/id.js +77 -0
  45. package/src/utils/loader.js +39 -21
  46. package/src/utils/migration-name.js +32 -0
  47. package/src/utils/redact.js +21 -1
  48. package/src/utils/telemetry.js +393 -0
  49. package/src/utils/template.js +36 -2
@@ -0,0 +1,483 @@
1
+ const { deepEqual } = require('../utils/canonical.js');
2
+ const { compareIndex, normalizeLiveIndex, restoreSpec, sameSignature } = require('./index-spec.js');
3
+
4
+ /**
5
+ * The converge planner: one declared collection against its live state, as
6
+ * result rows (what will happen and why) and executable steps (how). Pure, so
7
+ * the whole decision table is unit-tested without a database; converge.js
8
+ * only reads the live state in and carries the steps out.
9
+ *
10
+ * The rules, in short:
11
+ * - declared indexes pair with live ones by name, then compare: unchanged, a
12
+ * `collMod` (TTL, hidden), or a rebuild;
13
+ * - an index the server would refuse because an undeclared one already
14
+ * covers the same key under another name is never resolved by dropping that
15
+ * index unless `prune` is on — an identical one is accepted as is, a
16
+ * different one is a conflict that refuses the run;
17
+ * - undeclared indexes are kept (and reported) unless `prune` is on;
18
+ * - a rebuild that drops a unique index to build a unique one back is a
19
+ * conflict unless `rebuildUnique` is on — see UNIQUE_REBUILD_REASON;
20
+ * - `_id_` and a clustered index are the collection's own and never listed.
21
+ */
22
+
23
+ /** Actions that change the database — what a plan "would do" and a run "did" */
24
+ const CHANGE_ACTIONS = new Set(['create', 'modify', 'recreate', 'drop']);
25
+
26
+ /** Server defaults for a collection that has a validator but did not say how to apply it */
27
+ const VALIDATOR_DEFAULTS = { validationLevel: 'strict', validationAction: 'error' };
28
+
29
+ /** Whether a row drops or rebuilds an index */
30
+ function isDestructive(action) {
31
+ return action.target === 'index' && (action.action === 'drop' || action.action === 'recreate');
32
+ }
33
+
34
+ /**
35
+ * Whether a row is one the CLI asks to confirm: a destructive index change,
36
+ * or a validator change on a collection that already holds data — tightening
37
+ * a validator (`validationAction: 'error'`) can start rejecting the
38
+ * application's writes. A validator created with a new collection guards
39
+ * nothing yet.
40
+ */
41
+ function needsConfirmation(action, collectionActions = []) {
42
+ if (isDestructive(action)) return true;
43
+ if (action.target !== 'validator' || !CHANGE_ACTIONS.has(action.action)) return false;
44
+ const created = collectionActions.some(
45
+ (other) => other.target === 'collection' && other.action === 'create',
46
+ );
47
+ return !created;
48
+ }
49
+
50
+ /**
51
+ * An index as data for a result row (`from` / `to`): plain JSON, the key as
52
+ * an object, without the server-managed `v`/`ns` — what a reader of `--json`
53
+ * or of the converge history needs to see what changed.
54
+ */
55
+ function indexValue(spec) {
56
+ const { key, v: _v, ns: _ns, background: _background, ...rest } = spec;
57
+ return { key: key instanceof Map ? Object.fromEntries(key) : { ...key }, ...rest };
58
+ }
59
+
60
+ const isEmptyValidator = (validator) =>
61
+ validator === null || (typeof validator === 'object' && Object.keys(validator).length === 0);
62
+
63
+ /** The validator state a definition asks for: `undefined` = unmanaged, `null` = none */
64
+ function desiredValidator(definition) {
65
+ if (definition.validator === undefined) return undefined;
66
+ if (isEmptyValidator(definition.validator)) return null;
67
+ return {
68
+ validator: definition.validator,
69
+ validationLevel: definition.validationLevel ?? VALIDATOR_DEFAULTS.validationLevel,
70
+ validationAction: definition.validationAction ?? VALIDATOR_DEFAULTS.validationAction,
71
+ };
72
+ }
73
+
74
+ /** The validator a collection has (`null` = none). Level and action are omitted until set. */
75
+ function liveValidator(options) {
76
+ const validator = options?.validator;
77
+ if (validator === undefined || validator === null || isEmptyValidator(validator)) return null;
78
+ return {
79
+ validator,
80
+ validationLevel: options.validationLevel ?? VALIDATOR_DEFAULTS.validationLevel,
81
+ validationAction: options.validationAction ?? VALIDATOR_DEFAULTS.validationAction,
82
+ };
83
+ }
84
+
85
+ function planValidator(name, desired, current, row, steps) {
86
+ if (desired === null) {
87
+ if (current === null) {
88
+ row({ target: 'validator', name, action: 'unchanged' });
89
+ return;
90
+ }
91
+ const action = row({ target: 'validator', name, action: 'drop', from: current });
92
+ steps.push({ op: 'collMod', command: { validator: {} }, actions: [action] });
93
+ return;
94
+ }
95
+ if (current === null) {
96
+ const action = row({ target: 'validator', name, action: 'create', to: desired });
97
+ steps.push({ op: 'collMod', command: { ...desired }, actions: [action] });
98
+ return;
99
+ }
100
+ const diffs = [];
101
+ if (!deepEqual(desired.validator, current.validator)) diffs.push('validator');
102
+ if (desired.validationLevel !== current.validationLevel) diffs.push('validationLevel');
103
+ if (desired.validationAction !== current.validationAction) diffs.push('validationAction');
104
+ if (diffs.length === 0) {
105
+ row({ target: 'validator', name, action: 'unchanged' });
106
+ return;
107
+ }
108
+ const action = row({
109
+ target: 'validator',
110
+ name,
111
+ action: 'modify',
112
+ reason: diffs.join(', '),
113
+ from: current,
114
+ to: desired,
115
+ });
116
+ steps.push({ op: 'collMod', command: { ...desired }, actions: [action] });
117
+ }
118
+
119
+ /**
120
+ * The reason a rebuild is refused: it drops a unique index and builds a
121
+ * unique one back, so the constraint is gone until the build ends. A write in
122
+ * between can add a duplicate — and then neither the new index nor the old
123
+ * one can be built again, leaving the collection with no unique index at all.
124
+ */
125
+ const UNIQUE_REBUILD_REASON =
126
+ 'rebuilding drops the unique constraint until the new index is built — a duplicate written ' +
127
+ 'in between leaves neither index buildable; declare it under a new name (converge, then ' +
128
+ 'remove the old declaration and converge with prune), or converge with rebuildUnique ' +
129
+ '(CLI: --rebuild-unique)';
130
+
131
+ /** Whether a rebuild would open a window without a uniqueness the declaration keeps */
132
+ function dropsUniqueConstraint(declared, drops) {
133
+ return declared.options.unique === true && drops.some((index) => index.options.unique === true);
134
+ }
135
+
136
+ /**
137
+ * Whether a live index backs the collection's shard key (its key begins with
138
+ * every shard-key field, in order) — the server refuses to drop it, so prune
139
+ * leaves it alone instead of failing on it last.
140
+ */
141
+ function backsShardKey(index, shardKey) {
142
+ if (!shardKey) return false;
143
+ const shardFields = Object.keys(shardKey);
144
+ const fields = index.serverKey.map(([field]) => field);
145
+ return shardFields.every((field, position) => fields[position] === field);
146
+ }
147
+
148
+ function planIndexes(declaredIndexes, live, { prune, rebuildUnique, capabilities }, row, steps) {
149
+ const defaultCollation = live.options?.collation;
150
+ const liveIndexes = [];
151
+ for (const raw of live.indexes) {
152
+ if (raw.name === '_id_' || raw.clustered === true) continue;
153
+ liveIndexes.push(normalizeLiveIndex(raw));
154
+ }
155
+ const byName = new Map();
156
+ for (const index of liveIndexes) byName.set(index.name, index);
157
+ const declaredNames = new Set();
158
+ for (const declared of declaredIndexes) declaredNames.add(declared.name);
159
+
160
+ // Live indexes already accounted for — paired by name, or claimed as the
161
+ // blocker of a declaration — so none of them is also listed as an extra.
162
+ const consumed = new Set();
163
+ const creates = [];
164
+ const modifies = [];
165
+ const pending = [];
166
+
167
+ // Rows are made in declaration order; a pending one is settled below, once
168
+ // the blockers are known.
169
+ for (const declared of declaredIndexes) {
170
+ const current = byName.get(declared.name);
171
+ if (!current) {
172
+ const action = row({
173
+ target: 'index',
174
+ name: declared.name,
175
+ action: 'create',
176
+ to: indexValue(declared.spec),
177
+ });
178
+ pending.push({ declared, live: undefined, reason: undefined, action });
179
+ continue;
180
+ }
181
+ consumed.add(current.name);
182
+ const { diffs, inPlace, rebuild } = compareIndex(
183
+ declared,
184
+ current,
185
+ defaultCollation,
186
+ capabilities,
187
+ );
188
+ if (diffs.length === 0) {
189
+ row({ target: 'index', name: declared.name, action: 'unchanged' });
190
+ } else if (!rebuild) {
191
+ const action = row({
192
+ target: 'index',
193
+ name: declared.name,
194
+ action: 'modify',
195
+ reason: diffs.join(', '),
196
+ from: indexValue(current.raw),
197
+ to: indexValue(declared.spec),
198
+ });
199
+ const { unique, ...rest } = inPlace;
200
+ modifies.push(
201
+ unique
202
+ ? // Two collMods: prepareUnique (no new duplicates from here on),
203
+ // then unique (checks the existing data) — see converge.js.
204
+ { op: 'convertUnique', name: declared.name, rest, actions: [action] }
205
+ : {
206
+ op: 'collMod',
207
+ command: { index: { name: declared.name, ...rest } },
208
+ actions: [action],
209
+ },
210
+ );
211
+ } else {
212
+ const reason = diffs.join(', ');
213
+ const action = row({
214
+ target: 'index',
215
+ name: declared.name,
216
+ action: 'recreate',
217
+ reason,
218
+ from: indexValue(current.raw),
219
+ to: indexValue(declared.spec),
220
+ });
221
+ pending.push({ declared, live: current, reason, action });
222
+ }
223
+ }
224
+
225
+ const collides = (declared, index) =>
226
+ sameSignature(declared, index, defaultCollation) || (declared.isText && index.isText);
227
+
228
+ // A declaration that the server would refuse next to an undeclared index:
229
+ // same key, filter and collation under another name, or a second text index.
230
+ const undeclared = [];
231
+ for (const index of liveIndexes) {
232
+ if (!declaredNames.has(index.name)) undeclared.push(index);
233
+ }
234
+
235
+ const rebuilds = [];
236
+ for (const item of pending) {
237
+ const { declared, action } = item;
238
+ const blockers = [];
239
+ for (const index of undeclared) {
240
+ if (!consumed.has(index.name) && collides(declared, index)) blockers.push(index);
241
+ }
242
+ for (const blocker of blockers) consumed.add(blocker.name);
243
+ const drops = item.live ? [item.live] : [];
244
+
245
+ if (blockers.length > 0) {
246
+ const names = blockers.map((blocker) => `"${blocker.name}"`).join(', ');
247
+ const identical =
248
+ !item.live &&
249
+ blockers.length === 1 &&
250
+ compareIndex(declared, blockers[0], defaultCollation).diffs.length === 0;
251
+ action.liveName = blockers[0].name;
252
+ action.from = indexValue(blockers[0].raw);
253
+ if (!prune) {
254
+ if (identical) {
255
+ // The index the declaration describes exists, only under another
256
+ // name. Renaming means a full rebuild (and, for a unique index, a
257
+ // window without the constraint) — not something to do unasked.
258
+ action.action = 'unchanged';
259
+ action.reason = `exists as ${names}`;
260
+ } else {
261
+ action.action = 'conflict';
262
+ action.reason =
263
+ `the undeclared index ${names} covers the same key — declare it under its own ` +
264
+ 'name, or converge with prune to replace it';
265
+ }
266
+ continue;
267
+ }
268
+ drops.push(...blockers);
269
+ action.action = 'recreate';
270
+ action.reason = identical
271
+ ? 'name'
272
+ : [item.reason, `replaces ${names}`].filter(Boolean).join('; ');
273
+ }
274
+
275
+ if (drops.length === 0) {
276
+ creates.push({ declared, action });
277
+ } else if (!rebuildUnique && dropsUniqueConstraint(declared, drops)) {
278
+ // Not done unasked: the CLI asks with --rebuild-unique, while the paths
279
+ // nobody watches (after up, a queue job) never get this far on their own.
280
+ action.action = 'conflict';
281
+ action.reason = [action.reason, UNIQUE_REBUILD_REASON].filter(Boolean).join('; ');
282
+ } else {
283
+ rebuilds.push({ declared, action, drops });
284
+ }
285
+ }
286
+
287
+ // A create that collides with an index another rebuild is about to drop has
288
+ // to wait for that drop — and two rebuilds that swap keys each wait for the
289
+ // other. Such entangled ones run as one group: every drop, then every create.
290
+ const doomed = new Map();
291
+ for (const rebuild of rebuilds) {
292
+ for (const index of rebuild.drops) doomed.set(index.name, rebuild);
293
+ }
294
+ const entangled = new Set();
295
+ for (const item of [...creates, ...rebuilds]) {
296
+ for (const [name, owner] of doomed) {
297
+ if (owner === item) continue;
298
+ const index = owner.drops.find((drop) => drop.name === name);
299
+ if (collides(item.declared, index)) {
300
+ entangled.add(item);
301
+ entangled.add(owner);
302
+ }
303
+ }
304
+ }
305
+
306
+ const waiting = [];
307
+ for (const item of creates) {
308
+ if (entangled.has(item)) {
309
+ waiting.push(item);
310
+ continue;
311
+ }
312
+ steps.push({ op: 'createIndex', spec: item.declared.spec, actions: [item.action] });
313
+ }
314
+ steps.push(...modifies);
315
+ const group = { op: 'rebuild', drops: [], creates: [], actions: [] };
316
+ for (const item of [...rebuilds, ...waiting]) {
317
+ const step = entangled.has(item)
318
+ ? group
319
+ : { op: 'rebuild', drops: [], creates: [], actions: [] };
320
+ for (const index of item.drops ?? []) {
321
+ step.drops.push({ name: index.name, restore: restoreSpec(index.raw) });
322
+ }
323
+ step.creates.push({ spec: item.declared.spec, action: item.action });
324
+ step.actions.push(item.action);
325
+ if (step !== group) steps.push(step);
326
+ }
327
+ if (group.actions.length > 0) steps.push(group);
328
+
329
+ // Last, so an index is only ever removed once everything declared exists.
330
+ for (const index of liveIndexes) {
331
+ if (consumed.has(index.name) || declaredNames.has(index.name)) continue;
332
+ if (prune && backsShardKey(index, live.shardKey)) {
333
+ row({
334
+ target: 'index',
335
+ name: index.name,
336
+ action: 'keep',
337
+ reason: 'backs the shard key',
338
+ from: indexValue(index.raw),
339
+ });
340
+ } else if (prune) {
341
+ const action = row({
342
+ target: 'index',
343
+ name: index.name,
344
+ action: 'drop',
345
+ reason: 'not declared',
346
+ from: indexValue(index.raw),
347
+ });
348
+ steps.push({ op: 'dropIndex', name: index.name, actions: [action] });
349
+ } else {
350
+ row({
351
+ target: 'index',
352
+ name: index.name,
353
+ action: 'keep',
354
+ reason: 'not declared',
355
+ from: indexValue(index.raw),
356
+ });
357
+ }
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Plan one collection. `definition` is a normalized definition (see
363
+ * collections.js); `live` is `{ exists, type?, options?, indexes }` as
364
+ * converge.js reads it. Returns `{ name, actions, steps }`: `actions` are the
365
+ * result rows (status `'planned'`), `steps` the operations that carry them
366
+ * out, in execution order, each pointing at the rows it settles.
367
+ */
368
+ /**
369
+ * Fold every run of consecutive `createIndex` steps into one `createIndexes`:
370
+ * the server builds several indexes in a single pass over the collection, so
371
+ * three new indexes on a large collection cost one scan, not three. Only
372
+ * neighbours merge — the order between creates, modifications, rebuilds and
373
+ * drops is kept as planned.
374
+ */
375
+ function batchCreates(steps) {
376
+ const batched = [];
377
+ for (const step of steps) {
378
+ const last = batched.at(-1);
379
+ if (step.op !== 'createIndex') {
380
+ batched.push(step);
381
+ } else if (last?.op === 'createIndexes') {
382
+ last.specs.push(step.spec);
383
+ last.actions.push(...step.actions);
384
+ } else {
385
+ batched.push({ op: 'createIndexes', specs: [step.spec], actions: [...step.actions] });
386
+ }
387
+ }
388
+ return batched;
389
+ }
390
+
391
+ function planCollection(definition, live, options = {}) {
392
+ const plan = planCollectionSteps(definition, live, options);
393
+ return { ...plan, steps: batchCreates(plan.steps) };
394
+ }
395
+
396
+ function planCollectionSteps(
397
+ definition,
398
+ live,
399
+ { prune = false, rebuildUnique = false, capabilities = {} } = {},
400
+ ) {
401
+ const name = definition.name;
402
+ const actions = [];
403
+ const steps = [];
404
+ const row = (fields) => {
405
+ const action = { ...fields, status: 'planned' };
406
+ actions.push(action);
407
+ return action;
408
+ };
409
+
410
+ if (live.exists && live.type !== undefined && live.type !== 'collection') {
411
+ row({
412
+ target: 'collection',
413
+ name,
414
+ action: 'conflict',
415
+ reason: `is a ${live.type}, not a regular collection`,
416
+ });
417
+ return { name, actions, steps };
418
+ }
419
+
420
+ const desired = desiredValidator(definition);
421
+ const declaredIndexes = definition.indexes;
422
+
423
+ if (!live.exists) {
424
+ // Nothing worth creating an empty collection for — a definition that only
425
+ // says "no validator" is already true of a collection that does not exist.
426
+ if (!desired && !(declaredIndexes?.length > 0)) return { name, actions, steps };
427
+ const linked = [row({ target: 'collection', name, action: 'create' })];
428
+ if (desired) {
429
+ linked.push(row({ target: 'validator', name, action: 'create', to: desired }));
430
+ }
431
+ steps.push({ op: 'createCollection', options: desired ? { ...desired } : {}, actions: linked });
432
+ for (const declared of declaredIndexes ?? []) {
433
+ const action = row({
434
+ target: 'index',
435
+ name: declared.name,
436
+ action: 'create',
437
+ to: indexValue(declared.spec),
438
+ });
439
+ steps.push({ op: 'createIndex', spec: declared.spec, actions: [action] });
440
+ }
441
+ return { name, actions, steps };
442
+ }
443
+
444
+ if (desired !== undefined) {
445
+ planValidator(name, desired, liveValidator(live.options), row, steps);
446
+ }
447
+ if (declaredIndexes !== undefined) {
448
+ planIndexes(declaredIndexes, live, { prune, rebuildUnique, capabilities }, row, steps);
449
+ }
450
+ return { name, actions, steps };
451
+ }
452
+
453
+ /** Counts over planned (or executed) collections */
454
+ function summarize(collections) {
455
+ let changes = 0;
456
+ let applied = 0;
457
+ let conflicts = 0;
458
+ let destructive = 0;
459
+ for (const collection of collections) {
460
+ for (const action of collection.actions) {
461
+ if (action.action === 'conflict') conflicts += 1;
462
+ if (!CHANGE_ACTIONS.has(action.action)) continue;
463
+ changes += 1;
464
+ if (action.status === 'applied') applied += 1;
465
+ if (isDestructive(action)) destructive += 1;
466
+ }
467
+ }
468
+ return { changes, applied, conflicts, destructive };
469
+ }
470
+
471
+ module.exports = {
472
+ CHANGE_ACTIONS,
473
+ UNIQUE_REBUILD_REASON,
474
+ VALIDATOR_DEFAULTS,
475
+ desiredValidator,
476
+ indexValue,
477
+ isDestructive,
478
+ isEmptyValidator,
479
+ needsConfirmation,
480
+ liveValidator,
481
+ planCollection,
482
+ summarize,
483
+ };