@hop-top/kit 0.5.0-alpha.11 → 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 +47 -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-P3Y46PYF.js +138 -0
- package/dist/chunk-VKQCOVKI.js +880 -0
- package/dist/cli.js +3 -3
- package/dist/id/index.d.ts +1 -1
- package/dist/id/index.js +4 -2
- package/dist/index-BqZ7WGQf.d.ts +731 -0
- package/dist/{index-VLDcI5NF.d.ts → index-D9zpUrpE.d.ts} +18 -6
- package/dist/index.d.ts +5 -2
- 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 +78 -19
- 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/id/README.md +2 -2
- package/src/id/contract.test.ts +11 -8
- package/src/id/differential.test.ts +54 -0
- package/src/id/index.ts +123 -17
- 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} +102 -1
- package/src/{upgrade.ts → upgrade/index.ts} +96 -27
- 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-4GPCWBBA.js +0 -143
- package/dist/chunk-L23O2FFE.js +0 -51
- package/dist/upgrade-C3RWGwRi.d.ts +0 -125
- package/dist/upgrade.d.ts +0 -1
- package/dist/upgrade.js +0 -7
- package/dist/{chunk-MFVUENZR.js → chunk-KV7FYEAF.js} +2 -2
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A {@link SchemaDriver} for a SQLite database file, ported from Go
|
|
3
|
+
* `core/upgrade/driver/sqlite`, over `better-sqlite3`.
|
|
4
|
+
*
|
|
5
|
+
* Two modes. Path only: `new SqliteDriver(dbPath)` opens its own
|
|
6
|
+
* short-lived connection for `backup` and swaps the file on `restore`.
|
|
7
|
+
* Handle: `new SqliteDriver(dbPath, { db })` backs up through the caller's
|
|
8
|
+
* `Database`, never closes it, and cannot restore (the file cannot be
|
|
9
|
+
* replaced under a live connection): `restore` throws
|
|
10
|
+
* {@link BackupUnsupportedError} and the backup stays for manual recovery.
|
|
11
|
+
*
|
|
12
|
+
* The lock is `BEGIN EXCLUSIVE` on a separate database `.lock.db` beside
|
|
13
|
+
* the version file, because Node has no `flock`. It excludes other
|
|
14
|
+
* connections and processes using this driver, but does NOT interoperate
|
|
15
|
+
* with the `flock` on `.lock` that the Go, Python and Rust drivers take: a
|
|
16
|
+
* TypeScript and a non-TypeScript process migrating one file do not
|
|
17
|
+
* exclude each other.
|
|
18
|
+
*
|
|
19
|
+
* Imports `better-sqlite3`: import this module only where it is used
|
|
20
|
+
* (`@hop-top/kit/upgrade/drivers/sqlite`); the main entry never loads it.
|
|
21
|
+
*
|
|
22
|
+
* @packageDocumentation
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { promises as fs } from 'node:fs';
|
|
26
|
+
import { randomBytes } from 'node:crypto';
|
|
27
|
+
import * as path from 'node:path';
|
|
28
|
+
|
|
29
|
+
import Database from 'better-sqlite3';
|
|
30
|
+
|
|
31
|
+
import { BackupUnsupportedError, abortError } from '../errors';
|
|
32
|
+
import { resolveDataDir, versionOf, type DriverOptions } from './version';
|
|
33
|
+
|
|
34
|
+
/** Options of a {@link SqliteDriver}. */
|
|
35
|
+
export interface SqliteOptions extends DriverOptions {
|
|
36
|
+
/** The schema name (default `"sqlite"`). */
|
|
37
|
+
name?: string;
|
|
38
|
+
/**
|
|
39
|
+
* The caller's open connection. `backup` runs on it and leaves it open;
|
|
40
|
+
* `restore` throws {@link BackupUnsupportedError}. `dbPath` then only
|
|
41
|
+
* names the backup file (and may be empty).
|
|
42
|
+
*/
|
|
43
|
+
db?: Database.Database;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Files SQLite keeps beside a database; a stale -wal or -journal would be replayed onto a restored one. */
|
|
47
|
+
const SIDECARS = ['-wal', '-shm', '-journal'];
|
|
48
|
+
/** How long the driver's own backup connection waits on a lock. */
|
|
49
|
+
const BUSY_TIMEOUT_MS = 5000;
|
|
50
|
+
/** The lock database, in the version file's directory. */
|
|
51
|
+
export const LOCK_FILE = '.lock.db';
|
|
52
|
+
/** How often a blocked `lock` retries. */
|
|
53
|
+
const LOCK_POLL_MS = 50;
|
|
54
|
+
|
|
55
|
+
const isMissing = (e: unknown): boolean => (e as NodeJS.ErrnoException).code === 'ENOENT';
|
|
56
|
+
const msg = (e: unknown): string => (e instanceof Error ? e.message : String(e));
|
|
57
|
+
const isBusy = (e: unknown): boolean => {
|
|
58
|
+
const code = (e as { code?: unknown }).code;
|
|
59
|
+
return typeof code === 'string' && (code.startsWith('SQLITE_BUSY') || code.startsWith('SQLITE_LOCKED'));
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Backs up, restores and locks one SQLite database file.
|
|
64
|
+
*
|
|
65
|
+
* A `SchemaDriver`; not declared with `implements` so the bundled declarations
|
|
66
|
+
* keep `SchemaDriver` out of a chunk shared with the root barrel (the tests
|
|
67
|
+
* check the fit).
|
|
68
|
+
*/
|
|
69
|
+
export class SqliteDriver {
|
|
70
|
+
private readonly schema: string;
|
|
71
|
+
private readonly db?: Database.Database;
|
|
72
|
+
private readonly opts: DriverOptions;
|
|
73
|
+
|
|
74
|
+
constructor(
|
|
75
|
+
private readonly dbPath: string,
|
|
76
|
+
options: SqliteOptions = {},
|
|
77
|
+
) {
|
|
78
|
+
this.schema = options.name ?? 'sqlite';
|
|
79
|
+
this.db = options.db;
|
|
80
|
+
this.opts = { dataDir: options.dataDir, tool: options.tool };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
name(): string {
|
|
84
|
+
return this.schema;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
version(): Promise<string> {
|
|
88
|
+
return versionOf(this.opts, this.schema);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The Migrator writes the version file; nothing to do here. */
|
|
92
|
+
setVersion(): void {}
|
|
93
|
+
|
|
94
|
+
/** The backup file's name: the database file's base name, or `<schema>.db` without a path. */
|
|
95
|
+
private backupName(): string {
|
|
96
|
+
return this.dbPath !== '' ? path.basename(this.dbPath) : this.schema + '.db';
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Writes a consistent snapshot to `<dest>/<database file name>` with
|
|
101
|
+
* `VACUUM INTO`, which reads through the WAL: rows committed but not yet
|
|
102
|
+
* checkpointed are in it. Path only: a missing database file is
|
|
103
|
+
* "nothing to back up" (no file, no error); the driver opens a
|
|
104
|
+
* connection of its own and closes it. With a caller handle the snapshot
|
|
105
|
+
* runs on it, left open; it must not be inside a transaction.
|
|
106
|
+
*/
|
|
107
|
+
async backup(dest: string): Promise<void> {
|
|
108
|
+
if (this.db === undefined) {
|
|
109
|
+
try {
|
|
110
|
+
await fs.stat(this.dbPath);
|
|
111
|
+
} catch (e) {
|
|
112
|
+
if (isMissing(e)) return;
|
|
113
|
+
throw new Error(`stat db: ${msg(e)}`, { cause: e });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
await fs.mkdir(dest, { recursive: true, mode: 0o750 });
|
|
118
|
+
} catch (e) {
|
|
119
|
+
throw new Error(`create backup dir: ${msg(e)}`, { cause: e });
|
|
120
|
+
}
|
|
121
|
+
const target = path.join(dest, this.backupName());
|
|
122
|
+
const tmp = target + '.tmp';
|
|
123
|
+
// VACUUM INTO refuses an existing file; a leftover is stale.
|
|
124
|
+
try {
|
|
125
|
+
await fs.rm(tmp, { force: true });
|
|
126
|
+
await fs.rm(target, { force: true });
|
|
127
|
+
} catch (e) {
|
|
128
|
+
throw new Error(`clear backup file: ${msg(e)}`, { cause: e });
|
|
129
|
+
}
|
|
130
|
+
try {
|
|
131
|
+
this.vacuumInto(tmp);
|
|
132
|
+
await fs.rename(tmp, target);
|
|
133
|
+
} catch (e) {
|
|
134
|
+
await fs.rm(tmp, { force: true });
|
|
135
|
+
throw new Error(`backup db: ${msg(e)}`, { cause: e });
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Snapshots the database to `file`, bound as a parameter so no path needs quoting. */
|
|
140
|
+
private vacuumInto(file: string): void {
|
|
141
|
+
if (this.db !== undefined) {
|
|
142
|
+
if (this.db.inTransaction) {
|
|
143
|
+
throw new Error(
|
|
144
|
+
"the caller's connection has an open transaction; VACUUM INTO cannot run inside one: commit or roll it back first",
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
this.db.prepare('VACUUM INTO ?').run(file);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const own = new Database(this.dbPath, { fileMustExist: true, timeout: BUSY_TIMEOUT_MS });
|
|
151
|
+
try {
|
|
152
|
+
own.prepare('VACUUM INTO ?').run(file);
|
|
153
|
+
} finally {
|
|
154
|
+
own.close();
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Replaces the database file with the backup in `src`, then removes the
|
|
160
|
+
* replaced database's `-wal`, `-shm` and `-journal` files.
|
|
161
|
+
*
|
|
162
|
+
* Precondition: no open handle on the file, in this process or another;
|
|
163
|
+
* a connection left open keeps using the replaced file and may recreate
|
|
164
|
+
* its -wal beside the restored one. With a caller handle it restores
|
|
165
|
+
* nothing and throws {@link BackupUnsupportedError}; the backup stays.
|
|
166
|
+
*
|
|
167
|
+
* The backup is copied to a temporary file beside the database, synced
|
|
168
|
+
* and renamed over it, so a failure before the rename leaves the
|
|
169
|
+
* database and its sidecars untouched. An error after the rename means
|
|
170
|
+
* the database already holds the backup; a sidecar named in the error
|
|
171
|
+
* must be removed before the database is opened.
|
|
172
|
+
*/
|
|
173
|
+
async restore(src: string): Promise<void> {
|
|
174
|
+
if (this.db !== undefined) {
|
|
175
|
+
throw new BackupUnsupportedError(
|
|
176
|
+
`restore ${this.dbPath} under a caller-owned handle: upgrade: backup unsupported`,
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
const backup = path.join(src, this.backupName());
|
|
180
|
+
try {
|
|
181
|
+
await fs.stat(backup);
|
|
182
|
+
} catch (e) {
|
|
183
|
+
throw new Error(`open backup: ${msg(e)}`, { cause: e });
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const dir = path.dirname(this.dbPath);
|
|
187
|
+
try {
|
|
188
|
+
await fs.mkdir(dir, { recursive: true, mode: 0o750 });
|
|
189
|
+
} catch (e) {
|
|
190
|
+
throw new Error(`create db dir: ${msg(e)}`, { cause: e });
|
|
191
|
+
}
|
|
192
|
+
let mode = 0o600;
|
|
193
|
+
try {
|
|
194
|
+
mode = (await fs.stat(this.dbPath)).mode & 0o777;
|
|
195
|
+
} catch {
|
|
196
|
+
// No database yet: private by default.
|
|
197
|
+
}
|
|
198
|
+
const tmp = `${this.dbPath}.restore-${randomBytes(6).toString('hex')}`;
|
|
199
|
+
try {
|
|
200
|
+
await fs.copyFile(backup, tmp, fs.constants.COPYFILE_EXCL);
|
|
201
|
+
await fs.chmod(tmp, mode);
|
|
202
|
+
await syncFile(tmp);
|
|
203
|
+
await fs.rename(tmp, this.dbPath);
|
|
204
|
+
} catch (e) {
|
|
205
|
+
await fs.rm(tmp, { force: true });
|
|
206
|
+
throw new Error(`restore db: ${msg(e)}`, { cause: e });
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const errs: string[] = [];
|
|
210
|
+
for (const suffix of SIDECARS) {
|
|
211
|
+
const p = this.dbPath + suffix;
|
|
212
|
+
try {
|
|
213
|
+
await fs.rm(p);
|
|
214
|
+
} catch (e) {
|
|
215
|
+
if (!isMissing(e)) errs.push(`remove stale ${p}: ${msg(e)}`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (process.platform !== 'win32') {
|
|
219
|
+
try {
|
|
220
|
+
await syncFile(dir);
|
|
221
|
+
} catch (e) {
|
|
222
|
+
errs.push(`fsync dir ${dir}: ${msg(e)}`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (errs.length > 0) throw new Error(`restore: ${this.dbPath} replaced: ${errs.join('; ')}`);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** `<data dir>/<schema>`: where the version file and the lock database live. */
|
|
229
|
+
private stateDir(): string {
|
|
230
|
+
return path.join(resolveDataDir(this.opts), this.schema);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Holds `BEGIN EXCLUSIVE` on `<version dir>/.lock.db` (the directory is
|
|
235
|
+
* created if needed) until the returned function runs, retrying about
|
|
236
|
+
* every 50 ms while another connection holds it. When `signal` aborts
|
|
237
|
+
* while waiting it rejects with `abortError(signal)` and holds nothing.
|
|
238
|
+
* The retry loop is asynchronous (the busy timeout is 0), so a wait
|
|
239
|
+
* never blocks the event loop. The file is never deleted. Does not
|
|
240
|
+
* interoperate with the other ports' `flock` on `.lock`.
|
|
241
|
+
*/
|
|
242
|
+
async lock(signal?: AbortSignal): Promise<() => void> {
|
|
243
|
+
const dir = this.stateDir();
|
|
244
|
+
try {
|
|
245
|
+
await fs.mkdir(dir, { recursive: true, mode: 0o750 });
|
|
246
|
+
} catch (e) {
|
|
247
|
+
throw new Error(`create lock dir: ${msg(e)}`, { cause: e });
|
|
248
|
+
}
|
|
249
|
+
const file = path.join(dir, LOCK_FILE);
|
|
250
|
+
const conn = new Database(file, { timeout: 0 });
|
|
251
|
+
try {
|
|
252
|
+
for (;;) {
|
|
253
|
+
if (signal?.aborted) throw abortError(signal);
|
|
254
|
+
try {
|
|
255
|
+
conn.exec('BEGIN EXCLUSIVE');
|
|
256
|
+
break;
|
|
257
|
+
} catch (e) {
|
|
258
|
+
if (!isBusy(e)) throw new Error(`lock ${file}: ${msg(e)}`, { cause: e });
|
|
259
|
+
}
|
|
260
|
+
await sleep(LOCK_POLL_MS, signal);
|
|
261
|
+
}
|
|
262
|
+
} catch (e) {
|
|
263
|
+
conn.close();
|
|
264
|
+
throw e;
|
|
265
|
+
}
|
|
266
|
+
let released = false;
|
|
267
|
+
return () => {
|
|
268
|
+
if (released) return;
|
|
269
|
+
released = true;
|
|
270
|
+
try {
|
|
271
|
+
if (conn.inTransaction) conn.exec('ROLLBACK');
|
|
272
|
+
} finally {
|
|
273
|
+
conn.close();
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Resolves after `ms`, or as soon as `signal` aborts. */
|
|
280
|
+
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
281
|
+
return new Promise((resolve) => {
|
|
282
|
+
const done = (): void => {
|
|
283
|
+
clearTimeout(timer);
|
|
284
|
+
signal?.removeEventListener('abort', done);
|
|
285
|
+
resolve();
|
|
286
|
+
};
|
|
287
|
+
const timer = setTimeout(done, ms);
|
|
288
|
+
signal?.addEventListener('abort', done, { once: true });
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** fsyncs a file or a directory. */
|
|
293
|
+
async function syncFile(p: string): Promise<void> {
|
|
294
|
+
const h = await fs.open(p, 'r');
|
|
295
|
+
try {
|
|
296
|
+
await h.sync();
|
|
297
|
+
} finally {
|
|
298
|
+
await h.close();
|
|
299
|
+
}
|
|
300
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Where a version-file driver reads its version, shared by the drivers here. */
|
|
2
|
+
|
|
3
|
+
import { defaultDataDir, readVersionFile } from '../backup';
|
|
4
|
+
|
|
5
|
+
/** Options every driver in this directory accepts. */
|
|
6
|
+
export interface DriverOptions {
|
|
7
|
+
/** Reads the version file under this dir, for a Migrator built with the same `dataDir`. */
|
|
8
|
+
dataDir?: string;
|
|
9
|
+
/** Tool name for the default data dir `<xdg data dir>/hop/<tool>`. */
|
|
10
|
+
tool?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** The data dir the Migrator keeps `<schema>/version` and backups in. */
|
|
14
|
+
export function resolveDataDir(opts: DriverOptions): string {
|
|
15
|
+
return opts.dataDir !== undefined && opts.dataDir !== '' ? opts.dataDir : defaultDataDir(opts.tool ?? '');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The version the Migrator recorded for `schema`; `""` when none. */
|
|
19
|
+
export function versionOf(opts: DriverOptions, schema: string): Promise<string> {
|
|
20
|
+
return readVersionFile(resolveDataDir(opts), schema);
|
|
21
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Errors of the Migrator, ported from Go `core/upgrade`. Go matches them
|
|
3
|
+
* with `errors.Is` through wrapped errors; here a wrapped error keeps its
|
|
4
|
+
* cause in `cause` (and in `errors` when two failures are reported
|
|
5
|
+
* together), and the type guards walk that chain.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Text of an unknown thrown value: a message for an Error, else String(). */
|
|
9
|
+
export function errorText(e: unknown): string {
|
|
10
|
+
return e instanceof Error ? e.message : String(e);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A Migrator error that wraps what caused it. `cause` is the first
|
|
15
|
+
* underlying failure; `errors` lists every one when a run failed and its
|
|
16
|
+
* rollback failed too.
|
|
17
|
+
*/
|
|
18
|
+
export class UpgradeError extends Error {
|
|
19
|
+
readonly errors: readonly unknown[];
|
|
20
|
+
constructor(message: string, cause?: unknown, errors?: readonly unknown[]) {
|
|
21
|
+
super(message, cause === undefined ? undefined : { cause });
|
|
22
|
+
this.name = 'UpgradeError';
|
|
23
|
+
this.errors = errors ?? (cause === undefined ? [] : [cause]);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* What a driver's `backup` or `restore` throws when kit cannot back up or
|
|
29
|
+
* restore its store (a server database, a file under a live connection
|
|
30
|
+
* pool). A `backup` that throws it is not a failure: the run goes on with
|
|
31
|
+
* no backup. A `restore` that throws it restores nothing. Wrap it with
|
|
32
|
+
* `cause` to keep it matchable: {@link isBackupUnsupported}.
|
|
33
|
+
*/
|
|
34
|
+
export class BackupUnsupportedError extends Error {
|
|
35
|
+
constructor(message = 'upgrade: backup unsupported', options?: { cause?: unknown }) {
|
|
36
|
+
super(message, options);
|
|
37
|
+
this.name = 'BackupUnsupportedError';
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A rollback that could not undo a failed run: a `down` was missing or
|
|
43
|
+
* failed, or the newest step's `up` failed (it cannot be downed), and no
|
|
44
|
+
* backup could restore the schema, so the stored version stays at the last
|
|
45
|
+
* step still applied. The run's error carries it in its
|
|
46
|
+
* chain: {@link isNotRestored}. No `reverted` event is published for it.
|
|
47
|
+
* `message` is the text the vectors pin; `cause` is typically a
|
|
48
|
+
* {@link BackupUnsupportedError}.
|
|
49
|
+
*/
|
|
50
|
+
export class NotRestoredError extends Error {
|
|
51
|
+
constructor(message: string, options?: { cause?: unknown }) {
|
|
52
|
+
super(message, options);
|
|
53
|
+
this.name = 'NotRestoredError';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A failed `Migration.verify` or final verify check. Keeps the check's own
|
|
59
|
+
* text and carries its error as `cause`: {@link isVerifyError}. The
|
|
60
|
+
* document migrator's `DocError` of kind `verify` is a different thing.
|
|
61
|
+
*/
|
|
62
|
+
export class VerifyError extends Error {
|
|
63
|
+
constructor(cause: unknown) {
|
|
64
|
+
super(errorText(cause), { cause });
|
|
65
|
+
this.name = 'VerifyError';
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The run's signal was aborted. The text is Go's `context canceled`, or
|
|
71
|
+
* `context deadline exceeded` when the abort reason is a `TimeoutError`
|
|
72
|
+
* (`AbortSignal.timeout`); `cause` is the signal's reason.
|
|
73
|
+
*/
|
|
74
|
+
export class CanceledError extends Error {
|
|
75
|
+
constructor(signal: AbortSignal) {
|
|
76
|
+
const reason: unknown = signal.reason;
|
|
77
|
+
const timeout = reason instanceof Error && reason.name === 'TimeoutError';
|
|
78
|
+
super(timeout ? 'context deadline exceeded' : 'context canceled', { cause: reason });
|
|
79
|
+
this.name = 'CanceledError';
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The error a driver's `lock` rejects with when its signal aborts while it waits. */
|
|
84
|
+
export function abortError(signal: AbortSignal): CanceledError {
|
|
85
|
+
return new CanceledError(signal);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** True when `err` or anything in its `cause`/`errors` chain satisfies `test`. */
|
|
89
|
+
function inChain(err: unknown, test: (e: unknown) => boolean, seen = new Set<unknown>()): boolean {
|
|
90
|
+
if (err === null || err === undefined || seen.has(err)) return false;
|
|
91
|
+
seen.add(err);
|
|
92
|
+
if (test(err)) return true;
|
|
93
|
+
if (typeof err !== 'object') return false;
|
|
94
|
+
const e = err as { cause?: unknown; errors?: unknown };
|
|
95
|
+
if (inChain(e.cause, test, seen)) return true;
|
|
96
|
+
return Array.isArray(e.errors) && e.errors.some((c) => inChain(c, test, seen));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Whether `err` is, or wraps, a {@link BackupUnsupportedError}. */
|
|
100
|
+
export function isBackupUnsupported(err: unknown): boolean {
|
|
101
|
+
return inChain(err, (e) => e instanceof BackupUnsupportedError);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Whether `err` is, or wraps, a {@link NotRestoredError}. */
|
|
105
|
+
export function isNotRestored(err: unknown): boolean {
|
|
106
|
+
return inChain(err, (e) => e instanceof NotRestoredError);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Whether `err` is, or wraps, a {@link VerifyError}. */
|
|
110
|
+
export function isVerifyError(err: unknown): boolean {
|
|
111
|
+
return inChain(err, (e) => e instanceof VerifyError);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Whether `err` is, or wraps, a {@link CanceledError}. */
|
|
115
|
+
export function isCanceled(err: unknown): boolean {
|
|
116
|
+
return inChain(err, (e) => e instanceof CanceledError);
|
|
117
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Migration lifecycle events, ported from Go `core/upgrade/migrate_events.go`.
|
|
3
|
+
* Published as kit bus `Event`s (the `Bus` of the SDK's bus module):
|
|
4
|
+
* pass any object with `publish(event)`, typically a `Bus`. Payload keys
|
|
5
|
+
* are the Go JSON names.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { createEvent, type Event } from '../bus';
|
|
9
|
+
|
|
10
|
+
/** Anything events can be published to; a kit `Bus` fits. */
|
|
11
|
+
export interface EventPublisher {
|
|
12
|
+
publish(event: Event): void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Source set on every published event. */
|
|
16
|
+
export const PUBLISH_SOURCE = 'core.upgrade';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Topics a Migrator publishes on. Run level: `runStarted`, then
|
|
20
|
+
* `runCompleted` or `runFailed`. `baselined` follows a baseline stamp,
|
|
21
|
+
* before that schema's migrations. Per migration: `started`, then
|
|
22
|
+
* `applied` and `verified`, or `failed`; `reverted` follows a rollback
|
|
23
|
+
* that succeeded. The final verify publishes `verified` with
|
|
24
|
+
* `final: true`, or `failed` with stage `final`.
|
|
25
|
+
*/
|
|
26
|
+
export interface MigrationTopics {
|
|
27
|
+
runStarted: string;
|
|
28
|
+
runCompleted: string;
|
|
29
|
+
runFailed: string;
|
|
30
|
+
started: string;
|
|
31
|
+
applied: string;
|
|
32
|
+
verified: string;
|
|
33
|
+
failed: string;
|
|
34
|
+
reverted: string;
|
|
35
|
+
baselined: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const ACTIONS: Record<keyof MigrationTopics, string> = {
|
|
39
|
+
runStarted: 'run_started',
|
|
40
|
+
runCompleted: 'run_completed',
|
|
41
|
+
runFailed: 'run_failed',
|
|
42
|
+
started: 'started',
|
|
43
|
+
applied: 'applied',
|
|
44
|
+
verified: 'verified',
|
|
45
|
+
failed: 'failed',
|
|
46
|
+
reverted: 'reverted',
|
|
47
|
+
baselined: 'baselined',
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** `kit.core.migration.<action>`. */
|
|
51
|
+
export const DEFAULT_MIGRATION_TOPICS: MigrationTopics = topicsFromPrefix('kit.core.migration');
|
|
52
|
+
|
|
53
|
+
/** Every topic from a 3-segment prefix (`myapp.core.migration`). Throws a TypeError otherwise. */
|
|
54
|
+
export function topicsFromPrefix(prefix: string): MigrationTopics {
|
|
55
|
+
const segs = prefix.split('.');
|
|
56
|
+
if (segs.length !== 3 || segs.some((s) => !/^[a-z0-9_-]+$/i.test(s))) {
|
|
57
|
+
throw new TypeError(`upgrade: migration topic prefix "${prefix}" must have 3 dot-separated segments`);
|
|
58
|
+
}
|
|
59
|
+
const out = {} as MigrationTopics;
|
|
60
|
+
for (const k of Object.keys(ACTIONS) as (keyof MigrationTopics)[]) out[k] = `${prefix}.${ACTIONS[k]}`;
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Default topics, from `prefix` when given, with each non-empty field of `override` on top. */
|
|
65
|
+
export function resolveTopics(prefix?: string, override?: Partial<MigrationTopics>): MigrationTopics {
|
|
66
|
+
const out = prefix !== undefined ? topicsFromPrefix(prefix) : { ...DEFAULT_MIGRATION_TOPICS };
|
|
67
|
+
for (const [k, v] of Object.entries(override ?? {})) {
|
|
68
|
+
if (v) out[k as keyof MigrationTopics] = v;
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Payload of run_started, run_completed and run_failed. */
|
|
74
|
+
export interface MigrationRunPayload {
|
|
75
|
+
tool: string;
|
|
76
|
+
to: string;
|
|
77
|
+
applied?: number;
|
|
78
|
+
schema?: string;
|
|
79
|
+
error?: string;
|
|
80
|
+
duration_ms?: number;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Payload of the per-migration events. `from` is the version before the
|
|
85
|
+
* step, `to` the step's version. For `reverted`, `from` is the version
|
|
86
|
+
* being attempted and `to` the stored version restored. For `baselined`,
|
|
87
|
+
* `from` is `""` and `to` the version the store was stamped at.
|
|
88
|
+
*/
|
|
89
|
+
export interface MigrationPayload {
|
|
90
|
+
tool: string;
|
|
91
|
+
schema: string;
|
|
92
|
+
from: string;
|
|
93
|
+
to: string;
|
|
94
|
+
/** failed: up, verify, record, final, canceled. */
|
|
95
|
+
stage?: string;
|
|
96
|
+
/** reverted: down, restore. */
|
|
97
|
+
method?: string;
|
|
98
|
+
/** verified by the final verify. */
|
|
99
|
+
final?: boolean;
|
|
100
|
+
error?: string;
|
|
101
|
+
duration_ms?: number;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Whole milliseconds since `start` (a `performance.now()` reading). */
|
|
105
|
+
export function millisSince(start: number): number {
|
|
106
|
+
return Math.max(0, Math.floor(performance.now() - start));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Publishes best-effort: a missing publisher is a no-op and a throwing one never fails a run. */
|
|
110
|
+
export function emit(pub: EventPublisher | undefined, topic: string, payload: object): void {
|
|
111
|
+
if (!pub || topic === '') return;
|
|
112
|
+
try {
|
|
113
|
+
pub.publish(createEvent(topic, PUBLISH_SOURCE, payload));
|
|
114
|
+
} catch {
|
|
115
|
+
// dropped, like Go
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
|
|
2
2
|
import * as os from 'os';
|
|
3
3
|
import * as fs from 'fs';
|
|
4
4
|
import * as path from 'path';
|
|
5
|
-
import { createChecker } from './
|
|
5
|
+
import { createChecker, UpgradeCheckError } from './index';
|
|
6
6
|
|
|
7
7
|
// ─── helpers ─────────────────────────────────────────────────────────────────
|
|
8
8
|
|
|
@@ -587,3 +587,104 @@ describe('createChecker: tagPrefix and includePrereleases', () => {
|
|
|
587
587
|
expect(out.value()).toContain('https://github.com/acme/mono/releases/tag/xray/v2.0.0');
|
|
588
588
|
});
|
|
589
589
|
});
|
|
590
|
+
|
|
591
|
+
describe('createChecker: check()', () => {
|
|
592
|
+
let tmpDir: string;
|
|
593
|
+
|
|
594
|
+
beforeEach(() => {
|
|
595
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'upgrade-check-'));
|
|
596
|
+
vi.restoreAllMocks();
|
|
597
|
+
});
|
|
598
|
+
|
|
599
|
+
afterEach(() => {
|
|
600
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
601
|
+
vi.restoreAllMocks();
|
|
602
|
+
});
|
|
603
|
+
|
|
604
|
+
const mk = (extra: Record<string, unknown> = {}) =>
|
|
605
|
+
createChecker({
|
|
606
|
+
name: 'my-tool',
|
|
607
|
+
currentVersion: '1.0.0',
|
|
608
|
+
owner: 'acme',
|
|
609
|
+
repo: 'my-tool',
|
|
610
|
+
stateDir: tmpDir,
|
|
611
|
+
...extra,
|
|
612
|
+
});
|
|
613
|
+
|
|
614
|
+
it('resolves update info when newer', async () => {
|
|
615
|
+
vi.spyOn(globalThis, 'fetch').mockResolvedValue(jsonResponse({ tag_name: 'v2.0.0' }));
|
|
616
|
+
expect(await mk().check()).toEqual({
|
|
617
|
+
current: '1.0.0',
|
|
618
|
+
latest: '2.0.0',
|
|
619
|
+
updateAvailable: true,
|
|
620
|
+
url: 'https://github.com/acme/my-tool/releases/latest',
|
|
621
|
+
});
|
|
622
|
+
});
|
|
623
|
+
|
|
624
|
+
it('resolves updateAvailable false when up to date', async () => {
|
|
625
|
+
vi.spyOn(globalThis, 'fetch').mockResolvedValue(jsonResponse({ tag_name: 'v1.0.0' }));
|
|
626
|
+
const r = await mk().check();
|
|
627
|
+
expect(r.updateAvailable).toBe(false);
|
|
628
|
+
expect(r.latest).toBe('1.0.0');
|
|
629
|
+
});
|
|
630
|
+
|
|
631
|
+
it('rejects with UpgradeCheckError on network failure', async () => {
|
|
632
|
+
const boom = new Error('offline');
|
|
633
|
+
vi.spyOn(globalThis, 'fetch').mockRejectedValue(boom);
|
|
634
|
+
const err = await mk().check().catch((e) => e);
|
|
635
|
+
expect(err).toBeInstanceOf(UpgradeCheckError);
|
|
636
|
+
expect(err.cause).toBe(boom);
|
|
637
|
+
});
|
|
638
|
+
|
|
639
|
+
it('rejects on HTTP error status', async () => {
|
|
640
|
+
vi.spyOn(globalThis, 'fetch').mockResolvedValue(jsonResponse({}, 500));
|
|
641
|
+
await expect(mk().check()).rejects.toBeInstanceOf(UpgradeCheckError);
|
|
642
|
+
});
|
|
643
|
+
|
|
644
|
+
it('rejects on malformed body', async () => {
|
|
645
|
+
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
|
646
|
+
new Response('not json', { status: 200 }),
|
|
647
|
+
);
|
|
648
|
+
await expect(mk().check()).rejects.toBeInstanceOf(UpgradeCheckError);
|
|
649
|
+
vi.spyOn(globalThis, 'fetch').mockResolvedValue(jsonResponse({ tag_name: 5 }));
|
|
650
|
+
await expect(mk().check()).rejects.toBeInstanceOf(UpgradeCheckError);
|
|
651
|
+
});
|
|
652
|
+
|
|
653
|
+
it('rejects when no release matches tagPrefix', async () => {
|
|
654
|
+
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
|
655
|
+
jsonResponse([{ tag_name: 'other/v9.0.0' }]),
|
|
656
|
+
);
|
|
657
|
+
await expect(mk({ tagPrefix: 'xray/v' }).check()).rejects.toBeInstanceOf(
|
|
658
|
+
UpgradeCheckError,
|
|
659
|
+
);
|
|
660
|
+
});
|
|
661
|
+
|
|
662
|
+
it('honours tagPrefix and links the exact release', async () => {
|
|
663
|
+
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
|
664
|
+
jsonResponse([{ tag_name: 'xray/v1.5.0' }, { tag_name: 'other/v9.0.0' }]),
|
|
665
|
+
);
|
|
666
|
+
const r = await mk({ tagPrefix: 'xray/v' }).check();
|
|
667
|
+
expect(r.latest).toBe('1.5.0');
|
|
668
|
+
expect(r.url).toBe('https://github.com/acme/my-tool/releases/tag/xray/v1.5.0');
|
|
669
|
+
});
|
|
670
|
+
|
|
671
|
+
it('serves from cache within TTL; cacheTTL 0 bypasses it', async () => {
|
|
672
|
+
const spy = vi
|
|
673
|
+
.spyOn(globalThis, 'fetch')
|
|
674
|
+
.mockImplementation(async () => jsonResponse({ tag_name: 'v2.0.0' }));
|
|
675
|
+
await mk().check();
|
|
676
|
+
await mk().check();
|
|
677
|
+
expect(spy).toHaveBeenCalledTimes(1);
|
|
678
|
+
await mk({ cacheTTL: 0 }).check();
|
|
679
|
+
expect(spy).toHaveBeenCalledTimes(2);
|
|
680
|
+
});
|
|
681
|
+
|
|
682
|
+
it('notifyIfAvailable still swallows what check() rejects', async () => {
|
|
683
|
+
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('offline'));
|
|
684
|
+
const out = new StringStream();
|
|
685
|
+
await expect(
|
|
686
|
+
mk().notifyIfAvailable(out as unknown as NodeJS.WritableStream),
|
|
687
|
+
).resolves.toBeUndefined();
|
|
688
|
+
expect(out.value()).toBe('');
|
|
689
|
+
});
|
|
690
|
+
});
|