@hop-top/kit 0.5.0-alpha.12 → 0.5.0-alpha.13
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 +29 -0
- package/README.md +5 -5
- package/dist/bus-D2bAOPYz.d.ts +55 -0
- package/dist/bus.d.ts +1 -0
- package/dist/bus.js +13 -0
- package/dist/chunk-74E6RNOI.js +82 -0
- package/dist/chunk-B7XTFDBB.js +17 -0
- package/dist/chunk-CAONBSPO.js +497 -0
- package/dist/chunk-F7RSL4N4.js +88 -0
- package/dist/chunk-I6XDPSXQ.js +75 -0
- package/dist/chunk-IDM6YZXN.js +204 -0
- package/dist/chunk-VKQCOVKI.js +880 -0
- package/dist/cli.js +3 -3
- package/dist/index-BqZ7WGQf.d.ts +731 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.js +27 -13
- package/dist/upgrade/drivers/configfile.d.ts +45 -0
- package/dist/upgrade/drivers/configfile.js +78 -0
- package/dist/upgrade/drivers/fsdir.d.ts +61 -0
- package/dist/upgrade/drivers/fsdir.js +170 -0
- package/dist/upgrade/drivers/postgres.d.ts +121 -0
- package/dist/upgrade/drivers/postgres.js +195 -0
- package/dist/upgrade/drivers/sqlite.d.ts +101 -0
- package/dist/upgrade/drivers/sqlite.js +241 -0
- package/dist/upgrade/index.d.ts +2 -0
- package/dist/upgrade/index.js +73 -0
- package/dist/uri-IJ_AoY3d.d.ts +144 -0
- package/dist/uri.d.ts +1 -0
- package/dist/uri.js +37 -0
- package/dist/version-DEJ3pbiO.d.ts +10 -0
- package/dist/wizard-Bf_qHc31.d.ts +159 -0
- package/dist/wizard.d.ts +1 -0
- package/dist/wizard.js +39 -0
- package/package.json +74 -15
- package/skills/hop-top-kit-ts/.claude-plugin/plugin.json +19 -0
- package/skills/hop-top-kit-ts/SKILL.md +117 -0
- package/skills/hop-top-kit-ts/assets/snippets/mcp/mcp.expected +2 -0
- package/skills/hop-top-kit-ts/assets/snippets/mcp/mcp.ts +20 -0
- package/skills/hop-top-kit-ts/assets/snippets/quickstart/quickstart.expected +13 -0
- package/skills/hop-top-kit-ts/assets/snippets/quickstart/quickstart.ts +26 -0
- package/skills/hop-top-kit-ts/gym.json +5 -0
- package/skills/hop-top-kit-ts/references/ai-and-agents.md +45 -0
- package/skills/hop-top-kit-ts/references/cli-and-console.md +63 -0
- package/skills/hop-top-kit-ts/references/coverage.md +56 -0
- package/skills/hop-top-kit-ts/references/guardrails-and-trust.md +60 -0
- package/skills/hop-top-kit-ts/references/other-ports.md +31 -0
- package/skills/hop-top-kit-ts/references/serving-and-transports.md +49 -0
- package/skills/hop-top-kit-ts/scripts/detect-port.sh +168 -0
- package/src/index.test.ts +48 -2
- package/src/index.ts +6 -1
- package/src/published-types.test.ts +8 -0
- package/src/serve.stopped-order.test.ts +156 -0
- package/src/upgrade/README.md +42 -0
- package/src/upgrade/backup.ts +174 -0
- package/src/upgrade/conformance.test.ts +310 -0
- package/src/upgrade/document.ts +229 -0
- package/src/upgrade/driver.ts +66 -0
- package/src/upgrade/drivers/README.md +47 -0
- package/src/upgrade/drivers/configfile.test.ts +112 -0
- package/src/upgrade/drivers/configfile.ts +107 -0
- package/src/upgrade/drivers/fsdir.test.ts +188 -0
- package/src/upgrade/drivers/fsdir.ts +216 -0
- package/src/upgrade/drivers/isolation.test.ts +18 -0
- package/src/upgrade/drivers/postgres.integration.test.ts +395 -0
- package/src/upgrade/drivers/postgres.test.ts +272 -0
- package/src/upgrade/drivers/postgres.ts +284 -0
- package/src/upgrade/drivers/sqlite.integration.test.ts +492 -0
- package/src/upgrade/drivers/sqlite.ts +300 -0
- package/src/upgrade/drivers/version.ts +21 -0
- package/src/upgrade/errors.ts +117 -0
- package/src/upgrade/events.ts +117 -0
- package/src/{upgrade.test.ts → upgrade/index.test.ts} +1 -1
- package/src/{upgrade.ts → upgrade/index.ts} +20 -0
- package/src/upgrade/migration.ts +89 -0
- package/src/upgrade/migrator.test.ts +391 -0
- package/src/upgrade/migrator.ts +527 -0
- package/src/upgrade/options.ts +59 -0
- package/src/upgrade/semver.ts +90 -0
- package/test/skill-snippets.test.ts +60 -0
- package/test/upgrade/conformance-migrator.ts +439 -0
- package/test/upgrade/conformance-support.ts +44 -0
- package/test/upgrade/driver-support.ts +44 -0
- package/test/upgrade/pg-container.ts +64 -0
- package/test/upgrade/pg-race-worker.ts +48 -0
- package/test/upgrade/race-helper.ts +36 -0
- package/test/upgrade/sqlite-support.ts +41 -0
- package/test/upgrade/testdata/go-fsdir-mydata.tar.gz +0 -0
- package/vitest.config.ts +26 -0
- package/dist/chunk-X4E5QGEB.js +0 -171
- package/dist/upgrade-BJ2z6Oqf.d.ts +0 -156
- package/dist/upgrade.d.ts +0 -1
- package/dist/upgrade.js +0 -9
- package/dist/{chunk-MFVUENZR.js → chunk-KV7FYEAF.js} +2 -2
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The migration runner, ported from Go `core/upgrade/migrate.go`: per
|
|
3
|
+
* schema driver, lock, read the version, baseline, pending selection,
|
|
4
|
+
* backup, each `up` then `verify` then the version record, final verify,
|
|
5
|
+
* rollback, prune, unlock.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import * as path from 'node:path';
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
BackupStore,
|
|
12
|
+
DEFAULT_RETENTION,
|
|
13
|
+
defaultDataDir,
|
|
14
|
+
writeVersionFile,
|
|
15
|
+
} from './backup';
|
|
16
|
+
import type { SchemaDriver } from './driver';
|
|
17
|
+
import {
|
|
18
|
+
NotRestoredError,
|
|
19
|
+
UpgradeError,
|
|
20
|
+
VerifyError,
|
|
21
|
+
abortError,
|
|
22
|
+
errorText,
|
|
23
|
+
isBackupUnsupported,
|
|
24
|
+
} from './errors';
|
|
25
|
+
import {
|
|
26
|
+
emit,
|
|
27
|
+
millisSince,
|
|
28
|
+
resolveTopics,
|
|
29
|
+
type MigrationPayload,
|
|
30
|
+
type MigrationRunPayload,
|
|
31
|
+
type MigrationTopics,
|
|
32
|
+
} from './events';
|
|
33
|
+
import { defaultRegistry, type Migration, type Registry } from './migration';
|
|
34
|
+
import type { AppliedMigration, MigratorOptions, SchemaStatus } from './options';
|
|
35
|
+
|
|
36
|
+
const ERR_NO_BACKUP = 'not restored: no backup was taken';
|
|
37
|
+
const ERR_RESTORE_UNSUPPORTED = 'not restored: restore unsupported';
|
|
38
|
+
|
|
39
|
+
type Stage = 'up' | 'verify' | 'record' | 'final' | 'canceled';
|
|
40
|
+
|
|
41
|
+
/** What stopped a schema's run, with what to roll back. */
|
|
42
|
+
interface StepFailure {
|
|
43
|
+
stage: Stage;
|
|
44
|
+
version: string;
|
|
45
|
+
err: unknown;
|
|
46
|
+
undo: Migration[];
|
|
47
|
+
/**
|
|
48
|
+
* The newest undo entry is a step whose `up` failed: it counts as
|
|
49
|
+
* applied, but its `down` is never called.
|
|
50
|
+
*/
|
|
51
|
+
upFailed?: boolean;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The backup a schema's run can restore from: a path, or none with why. */
|
|
55
|
+
interface BackupState {
|
|
56
|
+
path: string;
|
|
57
|
+
unsupported?: unknown;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const asError = (e: unknown): Error => (e instanceof Error ? e : new Error(String(e), { cause: e }));
|
|
61
|
+
|
|
62
|
+
function recordError(version: string, err: unknown): UpgradeError {
|
|
63
|
+
return new UpgradeError(`record ${version === '' ? '""' : version} failed: ${errorText(err)}`, err);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function wrapFailure(f: StepFailure): UpgradeError {
|
|
67
|
+
const text = errorText(f.err);
|
|
68
|
+
switch (f.stage) {
|
|
69
|
+
case 'verify':
|
|
70
|
+
return new UpgradeError(`verify ${f.version} failed: ${text}`, new VerifyError(f.err));
|
|
71
|
+
case 'record':
|
|
72
|
+
return recordError(f.version, f.err);
|
|
73
|
+
case 'final':
|
|
74
|
+
return new UpgradeError(`final verify ${f.version} failed: ${text}`, new VerifyError(f.err));
|
|
75
|
+
case 'canceled':
|
|
76
|
+
return new UpgradeError(`up ${f.version} canceled: ${text}`, f.err);
|
|
77
|
+
default:
|
|
78
|
+
return new UpgradeError(`up ${f.version} failed: ${text}`, f.err);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Orchestrates versioned migrations across schema drivers. */
|
|
83
|
+
export class Migrator {
|
|
84
|
+
private readonly drivers: SchemaDriver[] = [];
|
|
85
|
+
private readonly applied: AppliedMigration[] = [];
|
|
86
|
+
private readonly target: string;
|
|
87
|
+
private readonly opts: MigratorOptions;
|
|
88
|
+
private readonly registry: Registry;
|
|
89
|
+
private readonly topics: MigrationTopics;
|
|
90
|
+
private readonly warn: (message: string) => void;
|
|
91
|
+
|
|
92
|
+
constructor(
|
|
93
|
+
readonly tool: string,
|
|
94
|
+
version: string,
|
|
95
|
+
options: MigratorOptions = {},
|
|
96
|
+
) {
|
|
97
|
+
this.target = version.startsWith('v') ? version.slice(1) : version;
|
|
98
|
+
this.opts = options;
|
|
99
|
+
this.registry = options.registry ?? defaultRegistry();
|
|
100
|
+
this.topics = resolveTopics(options.topicPrefix, options.topics);
|
|
101
|
+
this.warn = options.warn ?? ((m) => console.warn(m));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The target version, without a leading `v`. */
|
|
105
|
+
get version(): string {
|
|
106
|
+
return this.target;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Registers a schema driver; drivers run in the order added. */
|
|
110
|
+
addDriver(d: SchemaDriver): void {
|
|
111
|
+
this.drivers.push(d);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Migrations applied by this Migrator so far, cumulative. */
|
|
115
|
+
history(): AppliedMigration[] {
|
|
116
|
+
return this.applied.map((a) => ({ ...a }));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Executes pending migrations for every driver. Per schema: take the
|
|
121
|
+
* driver's lock (held until the schema's run ends, rollback included),
|
|
122
|
+
* read the version (when none is stored, ask `baseline` and record its
|
|
123
|
+
* answer), select pending, back up (and save the version the run starts
|
|
124
|
+
* at beside it), then per migration `up`, `verify` and the version
|
|
125
|
+
* record, then the final verify. An unsupported backup lets the run go
|
|
126
|
+
* on with no backup. On failure in auto mode: roll back (`down` in
|
|
127
|
+
* reverse, recording the version before each, else `restore` and record
|
|
128
|
+
* the starting version). A migration whose `up` failed counts as applied
|
|
129
|
+
* but cannot be downed (its `down` is never called): the run restores
|
|
130
|
+
* the backup at once and no older `down` runs. When a `down` is missing
|
|
131
|
+
* or fails, or the `up` failed, and no backup can restore the schema,
|
|
132
|
+
* nothing is reverted and the error matches `isNotRestored`; the stored
|
|
133
|
+
* version stays at the last step still applied. An aborted `signal`
|
|
134
|
+
* stops before the next `up` (`up <v> canceled: context canceled`).
|
|
135
|
+
* Rejects with the first failing schema's error, `migrate <schema>: ...`.
|
|
136
|
+
*/
|
|
137
|
+
async run(signal?: AbortSignal): Promise<void> {
|
|
138
|
+
const start = performance.now();
|
|
139
|
+
emit(this.opts.publisher, this.topics.runStarted, {
|
|
140
|
+
tool: this.tool,
|
|
141
|
+
to: this.target,
|
|
142
|
+
} satisfies MigrationRunPayload);
|
|
143
|
+
let applied = 0;
|
|
144
|
+
for (const d of this.drivers) {
|
|
145
|
+
try {
|
|
146
|
+
applied += await this.runSchema(d, signal);
|
|
147
|
+
} catch (e) {
|
|
148
|
+
const err = new UpgradeError(`migrate ${d.name()}: ${errorText(e)}`, e);
|
|
149
|
+
emit(this.opts.publisher, this.topics.runFailed, {
|
|
150
|
+
tool: this.tool,
|
|
151
|
+
to: this.target,
|
|
152
|
+
schema: d.name(),
|
|
153
|
+
error: err.message,
|
|
154
|
+
duration_ms: millisSince(start),
|
|
155
|
+
} satisfies MigrationRunPayload);
|
|
156
|
+
throw err;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
emit(this.opts.publisher, this.topics.runCompleted, {
|
|
160
|
+
tool: this.tool,
|
|
161
|
+
to: this.target,
|
|
162
|
+
applied,
|
|
163
|
+
duration_ms: millisSince(start),
|
|
164
|
+
} satisfies MigrationRunPayload);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Pending migration counts per driver. Takes no lock and never baselines. */
|
|
168
|
+
async status(): Promise<SchemaStatus[]> {
|
|
169
|
+
const out: SchemaStatus[] = [];
|
|
170
|
+
for (const d of this.drivers) {
|
|
171
|
+
let current = '';
|
|
172
|
+
let error: Error | undefined;
|
|
173
|
+
try {
|
|
174
|
+
current = await d.version();
|
|
175
|
+
} catch (e) {
|
|
176
|
+
error = asError(e);
|
|
177
|
+
}
|
|
178
|
+
const st: SchemaStatus = {
|
|
179
|
+
schema: d.name(),
|
|
180
|
+
current,
|
|
181
|
+
target: this.target,
|
|
182
|
+
pending: this.registry.pending(d.name(), current, this.target).length,
|
|
183
|
+
};
|
|
184
|
+
if (error) st.error = error;
|
|
185
|
+
out.push(st);
|
|
186
|
+
}
|
|
187
|
+
return out;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Restores the latest backup of each driver, then records the version
|
|
192
|
+
* the run that took it started at (saved beside the backup). A backup
|
|
193
|
+
* without that record is still restored, the version is left as it is
|
|
194
|
+
* and the error says so. A driver with `lock` is locked while its schema
|
|
195
|
+
* is rolled back (lock, backup lookup, restore, record, unlock); the
|
|
196
|
+
* version is not read and no events are published. A schema with no
|
|
197
|
+
* backup, or whose `restore` is unsupported, fails with an error that
|
|
198
|
+
* matches `isNotRestored`; nothing is recorded for it. Manual mode only.
|
|
199
|
+
*/
|
|
200
|
+
async rollbackLatest(): Promise<void> {
|
|
201
|
+
if (!this.opts.manualRollback) {
|
|
202
|
+
throw new Error('rollback: only available in manual rollback mode');
|
|
203
|
+
}
|
|
204
|
+
for (const d of this.drivers) {
|
|
205
|
+
try {
|
|
206
|
+
await this.rollbackLatestOne(d);
|
|
207
|
+
} catch (e) {
|
|
208
|
+
throw new UpgradeError(`rollback ${d.name()}: ${errorText(e)}`, e);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
private baseDir(): string {
|
|
214
|
+
if (this.opts.dataDir) return this.opts.dataDir;
|
|
215
|
+
try {
|
|
216
|
+
return defaultDataDir(this.tool);
|
|
217
|
+
} catch (e) {
|
|
218
|
+
throw new Error(`resolve data dir: ${errorText(e)}`, { cause: e });
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private backups(schema: string): BackupStore {
|
|
223
|
+
return new BackupStore(schema, this.baseDir(), this.opts.backupRetention ?? DEFAULT_RETENTION);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Takes the driver's lock when it has one and returns what releases it.
|
|
228
|
+
* The release never throws: a failed unlock is a warning.
|
|
229
|
+
*/
|
|
230
|
+
private async lockDriver(d: SchemaDriver, signal?: AbortSignal): Promise<() => Promise<void>> {
|
|
231
|
+
if (typeof d.lock !== 'function') return async () => {};
|
|
232
|
+
let unlock: Awaited<ReturnType<NonNullable<SchemaDriver['lock']>>>;
|
|
233
|
+
try {
|
|
234
|
+
unlock = await d.lock(signal);
|
|
235
|
+
} catch (e) {
|
|
236
|
+
throw new UpgradeError(`lock: ${errorText(e)}`, e);
|
|
237
|
+
}
|
|
238
|
+
return async () => {
|
|
239
|
+
try {
|
|
240
|
+
await unlock();
|
|
241
|
+
} catch (e) {
|
|
242
|
+
this.warn(`warning: unlock ${d.name()}: ${errorText(e)}`);
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
private async rollbackLatestOne(d: SchemaDriver): Promise<void> {
|
|
248
|
+
const release = await this.lockDriver(d);
|
|
249
|
+
try {
|
|
250
|
+
const store = this.backups(d.name());
|
|
251
|
+
const latest = await store.latestBackup();
|
|
252
|
+
const { version: preRun, recorded } = await store.readPreRun(latest);
|
|
253
|
+
try {
|
|
254
|
+
await d.restore(latest);
|
|
255
|
+
} catch (e) {
|
|
256
|
+
throw isBackupUnsupported(e) ? new NotRestoredError(ERR_RESTORE_UNSUPPORTED, { cause: e }) : e;
|
|
257
|
+
}
|
|
258
|
+
if (!recorded) {
|
|
259
|
+
throw new Error(`restored ${path.basename(latest)} but it records no pre-run version; version left as is`);
|
|
260
|
+
}
|
|
261
|
+
try {
|
|
262
|
+
await this.setVersion(d, preRun);
|
|
263
|
+
} catch (e) {
|
|
264
|
+
throw recordError(preRun, e);
|
|
265
|
+
}
|
|
266
|
+
} finally {
|
|
267
|
+
await release();
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
private async runSchema(d: SchemaDriver, signal?: AbortSignal): Promise<number> {
|
|
272
|
+
const release = await this.lockDriver(d, signal);
|
|
273
|
+
try {
|
|
274
|
+
return await this.runLocked(d, signal);
|
|
275
|
+
} finally {
|
|
276
|
+
await release();
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
private async runLocked(d: SchemaDriver, signal?: AbortSignal): Promise<number> {
|
|
281
|
+
let current: string;
|
|
282
|
+
try {
|
|
283
|
+
current = await d.version();
|
|
284
|
+
} catch (e) {
|
|
285
|
+
throw new UpgradeError(`read version: ${errorText(e)}`, e);
|
|
286
|
+
}
|
|
287
|
+
if (current === '' && this.opts.baseline) current = await this.stampBaseline(d, signal);
|
|
288
|
+
|
|
289
|
+
const pending = this.registry.pending(d.name(), current, this.target);
|
|
290
|
+
if (pending.length === 0) return 0;
|
|
291
|
+
|
|
292
|
+
const store = this.backups(d.name());
|
|
293
|
+
const bk = await this.takeBackup(store, d, pending[0].version, current);
|
|
294
|
+
|
|
295
|
+
const { fail, n } = await this.applyAll(d, current, pending, signal);
|
|
296
|
+
if (fail) throw await this.fail(d, current, bk, fail);
|
|
297
|
+
|
|
298
|
+
// Prune on success, non-fatal; a schema with no backup this run is left alone.
|
|
299
|
+
if (bk.path !== '') {
|
|
300
|
+
try {
|
|
301
|
+
await store.prune();
|
|
302
|
+
} catch (e) {
|
|
303
|
+
this.warn(`warning: prune old backups for ${d.name()}: ${errorText(e)}`);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return n;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Makes the backup directory (named after the first pending version),
|
|
311
|
+
* has the driver fill it and saves beside it the version the run starts
|
|
312
|
+
* at. A backup that is unsupported is no failure: the directory this
|
|
313
|
+
* call created is removed again, no version is saved and the run goes on.
|
|
314
|
+
*/
|
|
315
|
+
private async takeBackup(store: BackupStore, d: SchemaDriver, first: string, current: string): Promise<BackupState> {
|
|
316
|
+
const existed = await store.hasBackup(first);
|
|
317
|
+
let dir: string;
|
|
318
|
+
try {
|
|
319
|
+
dir = await store.backupDir(first);
|
|
320
|
+
} catch (e) {
|
|
321
|
+
throw new UpgradeError(`prepare backup: ${errorText(e)}`, e);
|
|
322
|
+
}
|
|
323
|
+
try {
|
|
324
|
+
await d.backup(dir);
|
|
325
|
+
} catch (e) {
|
|
326
|
+
if (!isBackupUnsupported(e)) throw new UpgradeError(`backup: ${errorText(e)}`, e);
|
|
327
|
+
if (!existed) await store.discard(dir);
|
|
328
|
+
return { path: '', unsupported: e };
|
|
329
|
+
}
|
|
330
|
+
try {
|
|
331
|
+
await store.savePreRun(dir, current);
|
|
332
|
+
} catch (e) {
|
|
333
|
+
throw new UpgradeError(`prepare backup: ${errorText(e)}`, e);
|
|
334
|
+
}
|
|
335
|
+
return { path: dir };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Asks `baseline` what the unversioned store is at and records a non-empty answer. */
|
|
339
|
+
private async stampBaseline(d: SchemaDriver, signal?: AbortSignal): Promise<string> {
|
|
340
|
+
let v: string | undefined;
|
|
341
|
+
try {
|
|
342
|
+
v = await this.opts.baseline!(d.name(), signal);
|
|
343
|
+
} catch (e) {
|
|
344
|
+
throw new UpgradeError(`baseline: ${errorText(e)}`, e);
|
|
345
|
+
}
|
|
346
|
+
if (v === undefined || v === '') return '';
|
|
347
|
+
try {
|
|
348
|
+
await this.setVersion(d, v);
|
|
349
|
+
} catch (e) {
|
|
350
|
+
const r = recordError(v, e);
|
|
351
|
+
throw new UpgradeError(`baseline: ${r.message}`, r);
|
|
352
|
+
}
|
|
353
|
+
emit(this.opts.publisher, this.topics.baselined, {
|
|
354
|
+
tool: this.tool,
|
|
355
|
+
schema: d.name(),
|
|
356
|
+
from: '',
|
|
357
|
+
to: v,
|
|
358
|
+
} satisfies MigrationPayload);
|
|
359
|
+
return v;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** `up`, `verify` and the version record per pending migration, then the final verify. */
|
|
363
|
+
private async applyAll(
|
|
364
|
+
d: SchemaDriver,
|
|
365
|
+
current: string,
|
|
366
|
+
pending: Migration[],
|
|
367
|
+
signal?: AbortSignal,
|
|
368
|
+
): Promise<{ fail?: StepFailure; n: number }> {
|
|
369
|
+
const schema = d.name();
|
|
370
|
+
const pub = this.opts.publisher;
|
|
371
|
+
const done: Migration[] = [];
|
|
372
|
+
let from = current;
|
|
373
|
+
const failed = (
|
|
374
|
+
ev: MigrationPayload,
|
|
375
|
+
t: number | undefined,
|
|
376
|
+
stage: Stage,
|
|
377
|
+
err: unknown,
|
|
378
|
+
undo: Migration[],
|
|
379
|
+
): { fail: StepFailure; n: number } => {
|
|
380
|
+
const payload: MigrationPayload = { ...ev, stage, error: errorText(err) };
|
|
381
|
+
if (t !== undefined) payload.duration_ms = millisSince(t);
|
|
382
|
+
emit(pub, this.topics.failed, payload);
|
|
383
|
+
return { fail: { stage, version: ev.to, err, undo }, n: done.length };
|
|
384
|
+
};
|
|
385
|
+
for (const mig of pending) {
|
|
386
|
+
const ev: MigrationPayload = { tool: this.tool, schema, from, to: mig.version };
|
|
387
|
+
if (signal?.aborted) return failed(ev, undefined, 'canceled', abortError(signal), done);
|
|
388
|
+
emit(pub, this.topics.started, ev);
|
|
389
|
+
let t = performance.now();
|
|
390
|
+
try {
|
|
391
|
+
await mig.up(signal);
|
|
392
|
+
} catch (e) {
|
|
393
|
+
// A failed up is an applied step that cannot be downed: it joins
|
|
394
|
+
// the undo list, newest, and its down is never called.
|
|
395
|
+
const f = failed(ev, t, 'up', e, [...done, mig]);
|
|
396
|
+
f.fail.upFailed = true;
|
|
397
|
+
return f;
|
|
398
|
+
}
|
|
399
|
+
emit(pub, this.topics.applied, { ...ev, duration_ms: millisSince(t) });
|
|
400
|
+
if (mig.verify) {
|
|
401
|
+
t = performance.now();
|
|
402
|
+
try {
|
|
403
|
+
await mig.verify(signal);
|
|
404
|
+
} catch (e) {
|
|
405
|
+
// up completed: the rollback must undo this step too
|
|
406
|
+
return failed(ev, t, 'verify', e, [...done, mig]);
|
|
407
|
+
}
|
|
408
|
+
emit(pub, this.topics.verified, { ...ev, duration_ms: millisSince(t) });
|
|
409
|
+
}
|
|
410
|
+
t = performance.now();
|
|
411
|
+
try {
|
|
412
|
+
await this.setVersion(d, mig.version);
|
|
413
|
+
} catch (e) {
|
|
414
|
+
return failed(ev, t, 'record', e, [...done, mig]);
|
|
415
|
+
}
|
|
416
|
+
done.push(mig);
|
|
417
|
+
this.applied.push({ version: mig.version, schema: mig.schema });
|
|
418
|
+
from = mig.version;
|
|
419
|
+
}
|
|
420
|
+
if (this.opts.verify) {
|
|
421
|
+
const ev: MigrationPayload = { tool: this.tool, schema, from: current, to: from };
|
|
422
|
+
const t = performance.now();
|
|
423
|
+
try {
|
|
424
|
+
await this.opts.verify(schema, from, signal);
|
|
425
|
+
} catch (e) {
|
|
426
|
+
return failed(ev, t, 'final', e, done);
|
|
427
|
+
}
|
|
428
|
+
emit(pub, this.topics.verified, { ...ev, duration_ms: millisSince(t), final: true });
|
|
429
|
+
}
|
|
430
|
+
return { n: done.length };
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Rolls back (auto mode) and builds the schema's error. The undo list is
|
|
435
|
+
* empty only when nothing ran: a canceled run before the first `up`.
|
|
436
|
+
*/
|
|
437
|
+
private async fail(d: SchemaDriver, current: string, bk: BackupState, f: StepFailure): Promise<Error> {
|
|
438
|
+
const err = wrapFailure(f);
|
|
439
|
+
if (this.opts.manualRollback || f.undo.length === 0) return err;
|
|
440
|
+
const t = performance.now();
|
|
441
|
+
let method: string;
|
|
442
|
+
try {
|
|
443
|
+
method = await this.rollback(d, current, f.undo, f.upFailed === true, bk);
|
|
444
|
+
} catch (rollbackErr) {
|
|
445
|
+
return new UpgradeError(`${err.message} (rollback also failed: ${errorText(rollbackErr)})`, err, [
|
|
446
|
+
err,
|
|
447
|
+
rollbackErr,
|
|
448
|
+
]);
|
|
449
|
+
}
|
|
450
|
+
emit(this.opts.publisher, this.topics.reverted, {
|
|
451
|
+
tool: this.tool,
|
|
452
|
+
schema: d.name(),
|
|
453
|
+
from: f.version,
|
|
454
|
+
to: current,
|
|
455
|
+
method,
|
|
456
|
+
duration_ms: millisSince(t),
|
|
457
|
+
} satisfies MigrationPayload);
|
|
458
|
+
return err;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Runs `down` in reverse order, recording the version before each
|
|
463
|
+
* migration once its `down` succeeded; falls back to `restore` (and
|
|
464
|
+
* records the starting version) if a `down` is missing or fails. Returns
|
|
465
|
+
* which of the two undid the changes. When `upFailed`, the newest step's
|
|
466
|
+
* `up` failed: its `down` is never called (a `down` assumes a completed
|
|
467
|
+
* `up`), so the rollback restores at once and no older `down` runs. A
|
|
468
|
+
* failed record stops the rollback. With no backup, or a `restore` that
|
|
469
|
+
* is unsupported, nothing is restored: a NotRestoredError, and the
|
|
470
|
+
* version stays at the last record, the step whose `down` was missing,
|
|
471
|
+
* failed or not callable. Runs without the run's signal, so a canceled
|
|
472
|
+
* run still rolls back.
|
|
473
|
+
*/
|
|
474
|
+
private async rollback(
|
|
475
|
+
d: SchemaDriver,
|
|
476
|
+
current: string,
|
|
477
|
+
applied: Migration[],
|
|
478
|
+
upFailed: boolean,
|
|
479
|
+
bk: BackupState,
|
|
480
|
+
): Promise<string> {
|
|
481
|
+
for (let i = applied.length - 1; i >= 0; i--) {
|
|
482
|
+
const mig = applied[i];
|
|
483
|
+
let downOk = false;
|
|
484
|
+
if (mig.down && !(upFailed && i === applied.length - 1)) {
|
|
485
|
+
try {
|
|
486
|
+
await mig.down();
|
|
487
|
+
downOk = true;
|
|
488
|
+
} catch {
|
|
489
|
+
downOk = false;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
if (!downOk) {
|
|
493
|
+
if (bk.path === '') throw new NotRestoredError(ERR_NO_BACKUP, { cause: bk.unsupported });
|
|
494
|
+
try {
|
|
495
|
+
await d.restore(bk.path);
|
|
496
|
+
} catch (e) {
|
|
497
|
+
throw isBackupUnsupported(e) ? new NotRestoredError(ERR_RESTORE_UNSUPPORTED, { cause: e }) : e;
|
|
498
|
+
}
|
|
499
|
+
try {
|
|
500
|
+
await this.setVersion(d, current);
|
|
501
|
+
} catch (e) {
|
|
502
|
+
throw recordError(current, e);
|
|
503
|
+
}
|
|
504
|
+
return 'restore';
|
|
505
|
+
}
|
|
506
|
+
const prev = i > 0 ? applied[i - 1].version : current;
|
|
507
|
+
try {
|
|
508
|
+
await this.setVersion(d, prev);
|
|
509
|
+
} catch (e) {
|
|
510
|
+
throw recordError(prev, e);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
return 'down';
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Records a version for the driver. A driver with `storesVersion` owns
|
|
518
|
+
* its version: only `setVersion` is called, no version file is touched.
|
|
519
|
+
* Any other driver gets the version file first (the canonical copy) and
|
|
520
|
+
* then `setVersion` as a notification, so a refused `setVersion` leaves
|
|
521
|
+
* the file at the new version.
|
|
522
|
+
*/
|
|
523
|
+
private async setVersion(d: SchemaDriver, version: string): Promise<void> {
|
|
524
|
+
if (d.storesVersion !== true) await writeVersionFile(this.baseDir(), d.name(), version);
|
|
525
|
+
await d.setVersion(version);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/** Options and result types of the {@link Migrator}. */
|
|
2
|
+
|
|
3
|
+
import type { EventPublisher, MigrationTopics } from './events';
|
|
4
|
+
import type { Registry } from './migration';
|
|
5
|
+
|
|
6
|
+
/** Options of a {@link Migrator}. */
|
|
7
|
+
export interface MigratorOptions {
|
|
8
|
+
/** Disables automatic rollback on failure; enables `rollbackLatest`. */
|
|
9
|
+
manualRollback?: boolean;
|
|
10
|
+
/** Recent backups kept per schema (default 5). */
|
|
11
|
+
backupRetention?: number;
|
|
12
|
+
/** Migrations to read instead of the default registry. */
|
|
13
|
+
registry?: Registry;
|
|
14
|
+
/**
|
|
15
|
+
* Where version files and backups live instead of
|
|
16
|
+
* `<xdg data dir>/hop/<tool>`. Drivers that read the version file need
|
|
17
|
+
* the same dir (`readVersionFile`).
|
|
18
|
+
*/
|
|
19
|
+
dataDir?: string;
|
|
20
|
+
/**
|
|
21
|
+
* Checks each schema's final state after its last pending migration,
|
|
22
|
+
* once that migration's version is recorded. A failure rolls back every
|
|
23
|
+
* migration applied to that schema in the run.
|
|
24
|
+
*/
|
|
25
|
+
verify?: (schema: string, version: string, signal?: AbortSignal) => void | Promise<void>;
|
|
26
|
+
/**
|
|
27
|
+
* What an unversioned store is already at. Called when a driver's
|
|
28
|
+
* `version()` is `""`, before pending selection; a non-empty result is
|
|
29
|
+
* recorded like any version (event `baselined`) and the migrations at or
|
|
30
|
+
* below it are not applied. An error fails that schema's run
|
|
31
|
+
* (`baseline: ...`) before any backup or `up`. Never called when a
|
|
32
|
+
* version is stored, when reading it failed, or by `status`.
|
|
33
|
+
*/
|
|
34
|
+
baseline?: (schema: string, signal?: AbortSignal) => string | undefined | Promise<string | undefined>;
|
|
35
|
+
/** Receives the lifecycle events (a kit `Bus` fits). Without it a Migrator is silent. */
|
|
36
|
+
publisher?: EventPublisher;
|
|
37
|
+
/** Replaces individual topics; others keep their `kit.core.migration.*` value. */
|
|
38
|
+
topics?: Partial<MigrationTopics>;
|
|
39
|
+
/** Sets every topic from a 3-segment prefix (`myapp.core.migration`); `topics` wins per field. */
|
|
40
|
+
topicPrefix?: string;
|
|
41
|
+
/** Receives warnings (an unlock or a prune that failed). Default `console.warn`. */
|
|
42
|
+
warn?: (message: string) => void;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A successfully applied migration. */
|
|
46
|
+
export interface AppliedMigration {
|
|
47
|
+
version: string;
|
|
48
|
+
schema: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Migration state of one schema. */
|
|
52
|
+
export interface SchemaStatus {
|
|
53
|
+
schema: string;
|
|
54
|
+
current: string;
|
|
55
|
+
target: string;
|
|
56
|
+
pending: number;
|
|
57
|
+
/** Set when the driver's `version()` failed; `current` is then `""`. */
|
|
58
|
+
error?: Error;
|
|
59
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lenient semver for migration versions, ported from Go `core/upgrade`.
|
|
3
|
+
*
|
|
4
|
+
* Not the strict `semver` package: a leading `v` is dropped, build metadata
|
|
5
|
+
* after `+` is ignored, and each of major, minor and patch is the leading
|
|
6
|
+
* decimal digits of its dot-separated part (missing or non-numeric is 0;
|
|
7
|
+
* anything after the third dot belongs to patch and is ignored). A release
|
|
8
|
+
* sorts above its pre-releases; pre-release identifiers compare left to
|
|
9
|
+
* right, a numeric identifier (decimal, no leading zero) below an
|
|
10
|
+
* alphanumeric one, numbers by value, text bytewise, and a shorter list of
|
|
11
|
+
* equal identifiers first. Nothing here throws: any string parses.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** A parsed lenient version. `pre` is empty for a release. */
|
|
15
|
+
export interface Semver {
|
|
16
|
+
major: number;
|
|
17
|
+
minor: number;
|
|
18
|
+
patch: number;
|
|
19
|
+
pre: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function leadingInt(s: string): number {
|
|
23
|
+
const m = /^\d+/.exec(s);
|
|
24
|
+
return m ? Number(m[0]) : 0;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Parses `s` leniently. A leading `v` is NOT dropped here; see {@link compareVersions}. */
|
|
28
|
+
export function parseSemver(s: string): Semver {
|
|
29
|
+
const v: Semver = { major: 0, minor: 0, patch: 0, pre: '' };
|
|
30
|
+
let rest = s;
|
|
31
|
+
const plus = rest.indexOf('+');
|
|
32
|
+
if (plus >= 0) rest = rest.slice(0, plus);
|
|
33
|
+
const dash = rest.indexOf('-');
|
|
34
|
+
if (dash >= 0) {
|
|
35
|
+
v.pre = rest.slice(dash + 1);
|
|
36
|
+
rest = rest.slice(0, dash);
|
|
37
|
+
}
|
|
38
|
+
const parts = rest.split('.');
|
|
39
|
+
v.major = leadingInt(parts[0] ?? '');
|
|
40
|
+
v.minor = leadingInt(parts[1] ?? '');
|
|
41
|
+
// Everything after the second dot is the patch part; only its leading digits count.
|
|
42
|
+
v.patch = leadingInt(parts.slice(2).join('.'));
|
|
43
|
+
return v;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function sign(n: number): -1 | 0 | 1 {
|
|
47
|
+
return n < 0 ? -1 : n > 0 ? 1 : 0;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const NUMERIC = /^(0|[1-9]\d*)$/;
|
|
51
|
+
|
|
52
|
+
function comparePreIdent(a: string, b: string): number {
|
|
53
|
+
const aNum = NUMERIC.test(a);
|
|
54
|
+
const bNum = NUMERIC.test(b);
|
|
55
|
+
if (aNum && bNum) return sign(Number(a) - Number(b));
|
|
56
|
+
if (aNum) return -1;
|
|
57
|
+
if (bNum) return 1;
|
|
58
|
+
return Buffer.compare(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function comparePreRelease(a: string, b: string): number {
|
|
62
|
+
const ap = a.split('.');
|
|
63
|
+
const bp = b.split('.');
|
|
64
|
+
const n = Math.min(ap.length, bp.length);
|
|
65
|
+
for (let i = 0; i < n; i++) {
|
|
66
|
+
const d = comparePreIdent(ap[i], bp[i]);
|
|
67
|
+
if (d !== 0) return d;
|
|
68
|
+
}
|
|
69
|
+
return sign(ap.length - bp.length);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Orders two parsed versions: -1, 0 or 1. */
|
|
73
|
+
export function compareSemver(a: Semver, b: Semver): -1 | 0 | 1 {
|
|
74
|
+
const d = a.major - b.major || a.minor - b.minor || a.patch - b.patch;
|
|
75
|
+
if (d !== 0) return sign(d);
|
|
76
|
+
if (a.pre === '' && b.pre === '') return 0;
|
|
77
|
+
if (a.pre === '') return 1;
|
|
78
|
+
if (b.pre === '') return -1;
|
|
79
|
+
return sign(comparePreRelease(a.pre, b.pre));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Orders two version strings after dropping one leading `v`: -1, 0 or 1. */
|
|
83
|
+
export function compareVersions(a: string, b: string): -1 | 0 | 1 {
|
|
84
|
+
return compareSemver(parseSemver(trimV(a)), parseSemver(trimV(b)));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Drops one leading `v`. */
|
|
88
|
+
export function trimV(s: string): string {
|
|
89
|
+
return s.startsWith('v') ? s.slice(1) : s;
|
|
90
|
+
}
|