@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,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory JSON document migrator, ported from Go `upgrade.MigrateDocument`.
|
|
3
|
+
* A document is a JSON object with an integer version at `versionField`
|
|
4
|
+
* (dotted path). Steps move it `from -> to`; the chain follows versions, not
|
|
5
|
+
* the order of steps. No I/O; the caller's input is never modified.
|
|
6
|
+
*
|
|
7
|
+
* Same shape as Go with two TypeScript differences: JSON numbers are JS
|
|
8
|
+
* numbers (integers past 2^53 lose exactness), and the re-encoded document
|
|
9
|
+
* keeps key insertion order where Go sorts keys.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** A decoded JSON object. */
|
|
13
|
+
export type JsonObject = { [key: string]: unknown };
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Moves a document from version `from` to `to` (to > from). `apply` gets a
|
|
17
|
+
* private copy and may mutate it in place; it returns the migrated document.
|
|
18
|
+
* The version field is set to `to` after `apply`, so `apply` need not touch it.
|
|
19
|
+
*/
|
|
20
|
+
export interface DocStep {
|
|
21
|
+
from: number;
|
|
22
|
+
to: number;
|
|
23
|
+
apply(doc: JsonObject): JsonObject;
|
|
24
|
+
/** Optional; runs on `apply`'s result. Throw to fail the step. */
|
|
25
|
+
verify?(doc: JsonObject): void;
|
|
26
|
+
note?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface DocOptions {
|
|
30
|
+
/** Dotted path of the integer version; `version` when empty. */
|
|
31
|
+
versionField?: string;
|
|
32
|
+
/** The version this build writes; 0 or absent means the highest `to`. */
|
|
33
|
+
latest?: number;
|
|
34
|
+
/** Read a missing or non-integer version as 0 instead of failing. */
|
|
35
|
+
missingIsZero?: boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface DocApplied {
|
|
39
|
+
from: number;
|
|
40
|
+
to: number;
|
|
41
|
+
note: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Says what the migration did. */
|
|
45
|
+
export interface DocReport {
|
|
46
|
+
from: number;
|
|
47
|
+
to: number;
|
|
48
|
+
applied: DocApplied[];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Why a document migration failed. */
|
|
52
|
+
export type DocKind = 'newer' | 'version' | 'gap' | 'step' | 'verify' | 'invalid';
|
|
53
|
+
|
|
54
|
+
/** Every failure of the document migrator; `kind` says which. `cause` is the step's own error, when there is one. */
|
|
55
|
+
export class DocError extends Error {
|
|
56
|
+
readonly kind: DocKind;
|
|
57
|
+
constructor(kind: DocKind, message: string, cause?: unknown) {
|
|
58
|
+
super(message, cause === undefined ? undefined : { cause });
|
|
59
|
+
this.name = 'DocError';
|
|
60
|
+
this.kind = kind;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const isObject = (v: unknown): v is JsonObject =>
|
|
65
|
+
v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
66
|
+
|
|
67
|
+
const own = (o: object, k: string): boolean => Object.prototype.hasOwnProperty.call(o, k);
|
|
68
|
+
|
|
69
|
+
const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e));
|
|
70
|
+
|
|
71
|
+
/** An integer literal fits Go's int: no fraction, no exponent. */
|
|
72
|
+
function isIntegerLiteral(src: string): boolean {
|
|
73
|
+
return /^-?\d+$/.test(src) && Number.isSafeInteger(Number(src));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
interface Parsed {
|
|
77
|
+
doc: JsonObject;
|
|
78
|
+
/** Source text of each number, by holder object and key. */
|
|
79
|
+
literals: Map<object, Map<string, string>>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
type Reviver = (this: unknown, key: string, value: unknown, ctx?: { source?: string }) => unknown;
|
|
83
|
+
|
|
84
|
+
function decode(text: string): Parsed {
|
|
85
|
+
const literals = new Map<object, Map<string, string>>();
|
|
86
|
+
const reviver: Reviver = function (key, value, ctx) {
|
|
87
|
+
if (typeof value === 'number' && ctx?.source !== undefined && this !== null && typeof this === 'object') {
|
|
88
|
+
let m = literals.get(this);
|
|
89
|
+
if (!m) literals.set(this, (m = new Map()));
|
|
90
|
+
m.set(key, ctx.source);
|
|
91
|
+
}
|
|
92
|
+
return value;
|
|
93
|
+
};
|
|
94
|
+
let v: unknown;
|
|
95
|
+
try {
|
|
96
|
+
v = JSON.parse(text, reviver as Parameters<typeof JSON.parse>[1]);
|
|
97
|
+
} catch (e) {
|
|
98
|
+
throw new DocError('invalid', `parse document: ${errText(e)}`, e);
|
|
99
|
+
}
|
|
100
|
+
if (!isObject(v)) throw new DocError('invalid', 'document is not a JSON object');
|
|
101
|
+
return { doc: v, literals };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The integer literal at `path`, if there is one. */
|
|
105
|
+
function docVersion(doc: JsonObject, path: string, literals?: Parsed['literals']): number | undefined {
|
|
106
|
+
let holder: unknown = undefined;
|
|
107
|
+
let cur: unknown = doc;
|
|
108
|
+
let key = '';
|
|
109
|
+
for (const seg of path.split('.')) {
|
|
110
|
+
if (!isObject(cur) || !own(cur, seg)) return undefined;
|
|
111
|
+
holder = cur;
|
|
112
|
+
key = seg;
|
|
113
|
+
cur = cur[seg];
|
|
114
|
+
}
|
|
115
|
+
if (typeof cur !== 'number') return undefined;
|
|
116
|
+
const src = literals?.get(holder as object)?.get(key) ?? String(cur);
|
|
117
|
+
return isIntegerLiteral(src) ? cur : undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function setDocVersion(doc: JsonObject, path: string, v: number): void {
|
|
121
|
+
const segs = path.split('.');
|
|
122
|
+
let cur = doc;
|
|
123
|
+
for (const seg of segs.slice(0, -1)) {
|
|
124
|
+
let next = cur[seg];
|
|
125
|
+
if (!isObject(next)) {
|
|
126
|
+
next = {};
|
|
127
|
+
cur[seg] = next;
|
|
128
|
+
}
|
|
129
|
+
cur = next as JsonObject;
|
|
130
|
+
}
|
|
131
|
+
cur[segs[segs.length - 1]] = v;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Runs the chain on `doc`, which it owns. */
|
|
135
|
+
function run(doc: JsonObject, steps: DocStep[], opts: DocOptions, literals?: Parsed['literals']): { doc: JsonObject; report: DocReport } {
|
|
136
|
+
const field = opts.versionField || 'version';
|
|
137
|
+
let cur = docVersion(doc, field, literals);
|
|
138
|
+
if (cur === undefined) {
|
|
139
|
+
if (!opts.missingIsZero) {
|
|
140
|
+
throw new DocError('version', `document has no integer version at "${field}"`);
|
|
141
|
+
}
|
|
142
|
+
cur = 0;
|
|
143
|
+
}
|
|
144
|
+
let latest = opts.latest ?? 0;
|
|
145
|
+
if (latest === 0) for (const s of steps) latest = Math.max(latest, s.to);
|
|
146
|
+
const report: DocReport = { from: cur, to: cur, applied: [] };
|
|
147
|
+
for (const s of steps) {
|
|
148
|
+
if (s.to <= s.from) {
|
|
149
|
+
throw new DocError('invalid', `migration ${s.from} -> ${s.to} does not move forward`);
|
|
150
|
+
}
|
|
151
|
+
if (s.to > latest) {
|
|
152
|
+
throw new DocError('invalid', `migration ${s.from} -> ${s.to} goes past the latest known ${latest}`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (cur > latest) {
|
|
156
|
+
throw new DocError('newer', `document version ${cur} is newer than the latest known ${latest}`);
|
|
157
|
+
}
|
|
158
|
+
while (cur < latest) {
|
|
159
|
+
const step = steps.find((s) => s.from === cur);
|
|
160
|
+
if (!step) {
|
|
161
|
+
throw new DocError('gap', `no migration from version ${cur} (highest target is ${latest}); chain has a gap`);
|
|
162
|
+
}
|
|
163
|
+
let out: JsonObject | null | undefined;
|
|
164
|
+
try {
|
|
165
|
+
out = step.apply(doc);
|
|
166
|
+
} catch (e) {
|
|
167
|
+
throw new DocError('step', `migration ${step.from} -> ${step.to}: ${errText(e)}`, e);
|
|
168
|
+
}
|
|
169
|
+
if (!isObject(out)) {
|
|
170
|
+
throw new DocError('step', `migration ${step.from} -> ${step.to} returned nil map`);
|
|
171
|
+
}
|
|
172
|
+
if (step.verify) {
|
|
173
|
+
try {
|
|
174
|
+
step.verify(out);
|
|
175
|
+
} catch (e) {
|
|
176
|
+
throw new DocError('verify', `migration ${step.from} -> ${step.to}: verify: ${errText(e)}`, e);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
doc = out;
|
|
180
|
+
setDocVersion(doc, field, step.to);
|
|
181
|
+
cur = step.to;
|
|
182
|
+
report.to = cur;
|
|
183
|
+
report.applied.push({ from: step.from, to: step.to, note: step.note ?? '' });
|
|
184
|
+
}
|
|
185
|
+
return { doc, report };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Migrates one JSON document given as text or UTF-8 bytes. When it is
|
|
190
|
+
* already at the latest version the input is returned as it is, byte for
|
|
191
|
+
* byte; otherwise the result is re-encoded. The result has the type of the
|
|
192
|
+
* input. Throws {@link DocError}; the input is untouched either way.
|
|
193
|
+
*/
|
|
194
|
+
export function migrateDocument<T extends string | Uint8Array>(
|
|
195
|
+
doc: T,
|
|
196
|
+
steps: DocStep[],
|
|
197
|
+
opts: DocOptions = {},
|
|
198
|
+
): { doc: T; report: DocReport } {
|
|
199
|
+
let text: string;
|
|
200
|
+
try {
|
|
201
|
+
text = typeof doc === 'string' ? doc : new TextDecoder('utf-8', { fatal: true }).decode(doc);
|
|
202
|
+
} catch (e) {
|
|
203
|
+
throw new DocError('invalid', `parse document: ${errText(e)}`, e);
|
|
204
|
+
}
|
|
205
|
+
const parsed = decode(text);
|
|
206
|
+
const { doc: out, report } = run(parsed.doc, steps, opts, parsed.literals);
|
|
207
|
+
if (report.applied.length === 0) return { doc, report };
|
|
208
|
+
const encoded = JSON.stringify(out);
|
|
209
|
+
return { doc: (typeof doc === 'string' ? encoded : new TextEncoder().encode(encoded)) as T, report };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* {@link migrateDocument} on a decoded document. The caller's object is
|
|
214
|
+
* never modified; steps work on a deep copy. Throws {@link DocError}.
|
|
215
|
+
*/
|
|
216
|
+
export function migrateDocumentValue(
|
|
217
|
+
doc: JsonObject,
|
|
218
|
+
steps: DocStep[],
|
|
219
|
+
opts: DocOptions = {},
|
|
220
|
+
): { doc: JsonObject; report: DocReport } {
|
|
221
|
+
let copy: JsonObject;
|
|
222
|
+
try {
|
|
223
|
+
copy = structuredClone(doc);
|
|
224
|
+
} catch (e) {
|
|
225
|
+
throw new DocError('invalid', `copy document: ${errText(e)}`, e);
|
|
226
|
+
}
|
|
227
|
+
if (!isObject(copy)) throw new DocError('invalid', 'document is not a JSON object');
|
|
228
|
+
return run(copy, steps, opts);
|
|
229
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The seam between the Migrator and a data store, ported from Go
|
|
3
|
+
* `core/upgrade` `SchemaDriver`.
|
|
4
|
+
*
|
|
5
|
+
* Every method may return a value or a Promise: a driver for a server
|
|
6
|
+
* database is async, one over `better-sqlite3` or a file is sync, and the
|
|
7
|
+
* Migrator awaits either. Capabilities are optional members the Migrator
|
|
8
|
+
* detects by shape, so a later driver adds one without any change to the
|
|
9
|
+
* Migrator: `lock` (a method) and `storesVersion` (a flag).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
13
|
+
|
|
14
|
+
/** Releases a lock taken by {@link SchemaDriver.lock}. */
|
|
15
|
+
export type Unlock = () => MaybePromise<void>;
|
|
16
|
+
|
|
17
|
+
export interface SchemaDriver {
|
|
18
|
+
/** The schema identifier, matched against `Migration.schema`. */
|
|
19
|
+
name(): string;
|
|
20
|
+
|
|
21
|
+
/** The applied version, or `""` when none is stored. */
|
|
22
|
+
version(): MaybePromise<string>;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Records a version: after each applied migration, and the earlier one
|
|
26
|
+
* again after a rollback or restore. For a driver without
|
|
27
|
+
* `storesVersion`, called after the Migrator wrote the version file.
|
|
28
|
+
*/
|
|
29
|
+
setVersion(version: string): MaybePromise<void>;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Copies the current state into the existing directory `dest`. Resolve
|
|
33
|
+
* only when it really did; throw {@link BackupUnsupportedError} (or an
|
|
34
|
+
* error whose cause chain has one) when it cannot; any other throw is a
|
|
35
|
+
* failure that stops the run.
|
|
36
|
+
*/
|
|
37
|
+
backup(dest: string): MaybePromise<void>;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Replaces the current state from the backup directory `src`. Same
|
|
41
|
+
* contract as `backup`: resolve only when it really restored.
|
|
42
|
+
*/
|
|
43
|
+
restore(src: string): MaybePromise<void>;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Optional, for a store several processes can migrate at once. The
|
|
47
|
+
* Migrator calls it before it reads the version and holds the lock for
|
|
48
|
+
* the whole run of that schema (version read, baseline, backup, every
|
|
49
|
+
* `up`, every version record, rollback, prune), then calls the returned
|
|
50
|
+
* unlock, on every path.
|
|
51
|
+
*
|
|
52
|
+
* Wait until the lock is acquired or `signal` aborts; in the second
|
|
53
|
+
* case reject with `abortError(signal)` and hold nothing. A rejection
|
|
54
|
+
* fails the schema before anything else (`lock: <message>`, no unlock).
|
|
55
|
+
* An unlock failure is only a warning. `RollbackLatest` locks too;
|
|
56
|
+
* `status` never does.
|
|
57
|
+
*/
|
|
58
|
+
lock?(signal?: AbortSignal): MaybePromise<Unlock>;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Optional: `true` when the driver keeps its version itself (a database
|
|
62
|
+
* table). The Migrator then calls only `setVersion` to record a version
|
|
63
|
+
* and writes no version file; `version()` is the one authority.
|
|
64
|
+
*/
|
|
65
|
+
readonly storesVersion?: boolean;
|
|
66
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# drivers
|
|
2
|
+
|
|
3
|
+
## What it answers
|
|
4
|
+
|
|
5
|
+
Where a schema's data and version live, and how it is backed up, restored and locked, for the `Migrator`. Each driver is a `SchemaDriver`; migration logic stays in `../`. Ported from Go `go/core/upgrade/driver`. Every driver is its own subpath import, so importing `@hop-top/kit/upgrade` never loads a database client, `tar` or `better-sqlite3`.
|
|
6
|
+
|
|
7
|
+
## Use it when
|
|
8
|
+
|
|
9
|
+
| Backend | Import | Constructor | Version lives in | Backup / restore |
|
|
10
|
+
|---------|--------|-------------|------------------|------------------|
|
|
11
|
+
| config files | `@hop-top/kit/upgrade/drivers/configfile` | `new ConfigFileDriver(paths, { name?, dataDir?, tool? })` | version file | copies each file to and from `dest` |
|
|
12
|
+
| a directory | `@hop-top/kit/upgrade/drivers/fsdir` | `new FsDirDriver(name, dirPath, { dataDir?, tool? })` | version file | `<name>.tar.gz`; restore extracts to a temp dir, then swaps (loads `tar`) |
|
|
13
|
+
| a SQLite file | `@hop-top/kit/upgrade/drivers/sqlite` | `new SqliteDriver(dbPath, { name?, db?, dataDir?, tool? })` | version file | `VACUUM INTO` (WAL-safe); restore swaps the file and drops `-wal`, `-shm`, `-journal` (loads `better-sqlite3`) |
|
|
14
|
+
| Postgres | `@hop-top/kit/upgrade/drivers/postgres` | `await openPostgresDriver({ db, connect, table, name? })` over your `pg` Pool | table row (`storesVersion`); advisory `lock` | both throw `BackupUnsupportedError`; back up outside kit |
|
|
15
|
+
|
|
16
|
+
- file-backed drivers read the Migrator's version file: give them the Migrator's `dataDir`
|
|
17
|
+
- `SqliteDriver` with `db`: backup runs on your `Database` and never closes it; `restore` throws `BackupUnsupportedError`, so a failed `up`, or a failure with a missing `down`, ends not restored; path-only mode restores the file
|
|
18
|
+
- pick Postgres when the schema lives in a shared database that several installs or a Go and a TypeScript tool migrate
|
|
19
|
+
|
|
20
|
+
## Quick start
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { Migrator } from '@hop-top/kit/upgrade';
|
|
24
|
+
import { SqliteDriver } from '@hop-top/kit/upgrade/drivers/sqlite';
|
|
25
|
+
|
|
26
|
+
const m = new Migrator('mytool', '1.2.0', { dataDir });
|
|
27
|
+
m.addDriver(new SqliteDriver('/data/app.db', { name: 'app', dataDir, db }));
|
|
28
|
+
await m.run();
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Contract
|
|
32
|
+
|
|
33
|
+
- `name()` must equal `Migration.schema`. Postgres defaults to `postgres`; its table matches `^[a-zA-Z_][a-zA-Z0-9_]{0,63}$`.
|
|
34
|
+
- Archive layout of `fsdir` is Go's: members relative to the directory, `.` for the directory itself. Either port restores the other's. A restore refuses absolute names, `..`, links, devices and other special members (`path traversal blocked`); a backup refuses a symbolic link.
|
|
35
|
+
- `SqliteDriver.lock` holds `BEGIN EXCLUSIVE` on `.lock.db` in `<data dir>/<schema>/`, retrying every 50 ms without blocking the event loop until acquired or `signal` aborts. Node has no `flock`: this does NOT exclude the Go, Python or Rust drivers, which flock `.lock`.
|
|
36
|
+
- `VACUUM INTO` cannot run in a transaction: a backup on a handle with one open fails with a clear error. Path-only restore needs no open handle on the file.
|
|
37
|
+
- Postgres: kit imports no Postgres client. `db` needs `query(text, params)`; `connect` returns a dedicated client (`pool.connect()`, or a connected `Client`) that holds the lock for the whole run. The pool needs at least two connections: `options.max === 1` is refused at lock time. No transaction-mode pooler in front.
|
|
38
|
+
- Tests: `*.integration.test.ts` need `better-sqlite3` or Postgres 16 in Docker and run under `make test-ts-upgrade-integration`; the rest run under `make test-ts-sdk`.
|
|
39
|
+
|
|
40
|
+
## Neighbours
|
|
41
|
+
|
|
42
|
+
- [`../README.md`](../README.md): `Migrator`, `SchemaDriver`; Go reference: [`go/core/upgrade/driver`](../../../../../go/core/upgrade/driver/README.md)
|
|
43
|
+
- [`go/core/upgrade/driver/postgres`](../../../../../go/core/upgrade/driver/postgres/README.md): the driver the Postgres one interoperates with.
|
|
44
|
+
|
|
45
|
+
## See also
|
|
46
|
+
|
|
47
|
+
- [`docs/adopters/reference/ts-api-reference.md`](../../../../../docs/adopters/reference/ts-api-reference.md)
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
|
5
|
+
|
|
6
|
+
import { tempDir } from '../../../test/upgrade/driver-support';
|
|
7
|
+
import { Migrator, Registry, isNotRestored, readVersionFile, type SchemaDriver } from '../index';
|
|
8
|
+
import { ConfigFileDriver, backupFileName } from './configfile';
|
|
9
|
+
|
|
10
|
+
let tmp: ReturnType<typeof tempDir>;
|
|
11
|
+
beforeEach(() => {
|
|
12
|
+
tmp = tempDir();
|
|
13
|
+
});
|
|
14
|
+
afterEach(() => tmp.cleanup());
|
|
15
|
+
|
|
16
|
+
describe('ConfigFileDriver', () => {
|
|
17
|
+
it('names the schema "config" unless told otherwise', () => {
|
|
18
|
+
const asDriver: SchemaDriver = new ConfigFileDriver([]); // the fit the class does not declare
|
|
19
|
+
expect(asDriver.name()).toBe('config');
|
|
20
|
+
expect(new ConfigFileDriver([], { name: 'app' }).name()).toBe('app');
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('backs a file up and restores it', async () => {
|
|
24
|
+
const cfg = join(tmp.dir, 'config.yaml');
|
|
25
|
+
writeFileSync(cfg, 'key: value');
|
|
26
|
+
const d = new ConfigFileDriver([cfg]);
|
|
27
|
+
const backup = join(tmp.dir, 'backup');
|
|
28
|
+
await d.backup(backup);
|
|
29
|
+
expect(readFileSync(join(backup, backupFileName(cfg)), 'utf8')).toBe('key: value');
|
|
30
|
+
|
|
31
|
+
writeFileSync(cfg, 'key: changed');
|
|
32
|
+
await d.restore(backup);
|
|
33
|
+
expect(readFileSync(cfg, 'utf8')).toBe('key: value');
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('keeps same-named files in different directories apart', async () => {
|
|
37
|
+
mkdirSync(join(tmp.dir, 'a'));
|
|
38
|
+
mkdirSync(join(tmp.dir, 'b'));
|
|
39
|
+
const a = join(tmp.dir, 'a', 'config.yaml');
|
|
40
|
+
const b = join(tmp.dir, 'b', 'config.yaml');
|
|
41
|
+
writeFileSync(a, 'a');
|
|
42
|
+
writeFileSync(b, 'b');
|
|
43
|
+
const backup = join(tmp.dir, 'backup');
|
|
44
|
+
await new ConfigFileDriver([a, b]).backup(backup);
|
|
45
|
+
expect(readFileSync(join(backup, backupFileName(a)), 'utf8')).toBe('a');
|
|
46
|
+
expect(readFileSync(join(backup, backupFileName(b)), 'utf8')).toBe('b');
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('flattens a path like Go: separators become underscores', () => {
|
|
50
|
+
expect(backupFileName('/etc/foo/config.yaml')).toBe('_etc_foo_config.yaml');
|
|
51
|
+
expect(backupFileName('/etc//foo/./config.yaml/')).toBe('_etc_foo_config.yaml');
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('skips a missing file on backup and a file absent from the backup on restore', async () => {
|
|
55
|
+
const d = new ConfigFileDriver([join(tmp.dir, 'nope.yaml')]);
|
|
56
|
+
const backup = join(tmp.dir, 'backup');
|
|
57
|
+
await d.backup(backup);
|
|
58
|
+
await d.restore(backup);
|
|
59
|
+
expect(existsSync(join(tmp.dir, 'nope.yaml'))).toBe(false);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('reads the version file under dataDir', async () => {
|
|
63
|
+
mkdirSync(join(tmp.dir, 'config'));
|
|
64
|
+
writeFileSync(join(tmp.dir, 'config', 'version'), '2.0.0\n');
|
|
65
|
+
expect(await new ConfigFileDriver([], { dataDir: tmp.dir }).version()).toBe('2.0.0');
|
|
66
|
+
expect(await new ConfigFileDriver([], { dataDir: join(tmp.dir, 'none') }).version()).toBe('');
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
describe('through the Migrator', () => {
|
|
71
|
+
it('restores the file when a later migration fails and the earlier one has no down', async () => {
|
|
72
|
+
const data = join(tmp.dir, 'data');
|
|
73
|
+
const cfg = join(tmp.dir, 'config.yaml');
|
|
74
|
+
mkdirSync(join(data, 'config'), { recursive: true });
|
|
75
|
+
writeFileSync(join(data, 'config', 'version'), '1.0.0');
|
|
76
|
+
writeFileSync(cfg, 'v: 1');
|
|
77
|
+
|
|
78
|
+
const reg = new Registry();
|
|
79
|
+
reg.register({ version: '1.1.0', schema: 'config', up: () => writeFileSync(cfg, 'v: 2') });
|
|
80
|
+
reg.register({
|
|
81
|
+
version: '1.2.0',
|
|
82
|
+
schema: 'config',
|
|
83
|
+
up: () => {
|
|
84
|
+
throw new Error('simulated failure');
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
const m = new Migrator('tool', '1.2.0', { registry: reg, dataDir: data, warn: () => {} });
|
|
88
|
+
m.addDriver(new ConfigFileDriver([cfg], { dataDir: data }));
|
|
89
|
+
|
|
90
|
+
const err = await m.run().then(
|
|
91
|
+
() => undefined,
|
|
92
|
+
(e: unknown) => e as Error,
|
|
93
|
+
);
|
|
94
|
+
expect(err?.message).toContain('simulated failure');
|
|
95
|
+
expect(isNotRestored(err)).toBe(false);
|
|
96
|
+
expect(readFileSync(cfg, 'utf8')).toBe('v: 1');
|
|
97
|
+
expect(await readVersionFile(data, 'config')).toBe('1.0.0');
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it('applies every migration and keeps the new content on success', async () => {
|
|
101
|
+
const data = join(tmp.dir, 'data');
|
|
102
|
+
const cfg = join(tmp.dir, 'config.yaml');
|
|
103
|
+
writeFileSync(cfg, 'v: 1');
|
|
104
|
+
const reg = new Registry();
|
|
105
|
+
reg.register({ version: '1.0.0', schema: 'config', up: () => writeFileSync(cfg, 'v: 2') });
|
|
106
|
+
const m = new Migrator('tool', '1.0.0', { registry: reg, dataDir: data });
|
|
107
|
+
m.addDriver(new ConfigFileDriver([cfg], { dataDir: data }));
|
|
108
|
+
await m.run();
|
|
109
|
+
expect(readFileSync(cfg, 'utf8')).toBe('v: 2');
|
|
110
|
+
expect(readFileSync(join(data, 'backups', 'config', 'pre-1.0.0', backupFileName(cfg)), 'utf8')).toBe('v: 1');
|
|
111
|
+
});
|
|
112
|
+
});
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A {@link SchemaDriver} for configuration files, ported from Go
|
|
3
|
+
* `core/upgrade/driver/configfile`: backup copies each managed file into
|
|
4
|
+
* the backup directory, restore copies them back. The version lives in
|
|
5
|
+
* the Migrator's version file.
|
|
6
|
+
*
|
|
7
|
+
* @packageDocumentation
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { promises as fs } from 'node:fs';
|
|
11
|
+
import * as path from 'node:path';
|
|
12
|
+
|
|
13
|
+
import { versionOf, type DriverOptions } from './version';
|
|
14
|
+
|
|
15
|
+
/** Options of a {@link ConfigFileDriver}. */
|
|
16
|
+
export interface ConfigFileOptions extends DriverOptions {
|
|
17
|
+
/** The schema name (default `"config"`). */
|
|
18
|
+
name?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const isMissing = (e: unknown): boolean => (e as NodeJS.ErrnoException).code === 'ENOENT';
|
|
22
|
+
const msg = (e: unknown): string => (e instanceof Error ? e.message : String(e));
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The backup file name of a managed path: the cleaned path with every
|
|
26
|
+
* separator turned into `_` (`/etc/foo/config.yaml` becomes
|
|
27
|
+
* `_etc_foo_config.yaml`), so two files named alike never collide.
|
|
28
|
+
*/
|
|
29
|
+
export function backupFileName(p: string): string {
|
|
30
|
+
let clean = path.normalize(p);
|
|
31
|
+
if (clean.length > 1 && clean.endsWith(path.sep)) clean = clean.slice(0, -1);
|
|
32
|
+
return clean.split(path.sep).join('_');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Backs up and restores one or more configuration files.
|
|
37
|
+
*
|
|
38
|
+
* A `SchemaDriver`; not declared with `implements` so the bundled declarations
|
|
39
|
+
* keep `SchemaDriver` out of a chunk shared with the root barrel (the tests
|
|
40
|
+
* check the fit).
|
|
41
|
+
*/
|
|
42
|
+
export class ConfigFileDriver {
|
|
43
|
+
private readonly schema: string;
|
|
44
|
+
private readonly paths: readonly string[];
|
|
45
|
+
private readonly opts: DriverOptions;
|
|
46
|
+
|
|
47
|
+
constructor(paths: readonly string[], options: ConfigFileOptions = {}) {
|
|
48
|
+
this.paths = [...paths];
|
|
49
|
+
this.schema = options.name ?? 'config';
|
|
50
|
+
this.opts = { dataDir: options.dataDir, tool: options.tool };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
name(): string {
|
|
54
|
+
return this.schema;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
version(): Promise<string> {
|
|
58
|
+
return versionOf(this.opts, this.schema);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The Migrator writes the version file; nothing to do here. */
|
|
62
|
+
setVersion(): void {}
|
|
63
|
+
|
|
64
|
+
/** Copies each managed file into `dest`; a file that does not exist is skipped. */
|
|
65
|
+
async backup(dest: string): Promise<void> {
|
|
66
|
+
try {
|
|
67
|
+
await fs.mkdir(dest, { recursive: true, mode: 0o750 });
|
|
68
|
+
} catch (e) {
|
|
69
|
+
throw new Error(`create backup dir: ${msg(e)}`, { cause: e });
|
|
70
|
+
}
|
|
71
|
+
for (const p of this.paths) {
|
|
72
|
+
const name = backupFileName(p);
|
|
73
|
+
try {
|
|
74
|
+
await copyFile(p, path.join(dest, name));
|
|
75
|
+
} catch (e) {
|
|
76
|
+
if (isMissing(e)) continue;
|
|
77
|
+
throw new Error(`backup ${name}: ${msg(e)}`, { cause: e });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Copies each backed-up file back to its place; a file absent from `src` is skipped. */
|
|
83
|
+
async restore(src: string): Promise<void> {
|
|
84
|
+
for (const p of this.paths) {
|
|
85
|
+
const name = backupFileName(p);
|
|
86
|
+
const file = path.join(src, name);
|
|
87
|
+
try {
|
|
88
|
+
await fs.stat(file);
|
|
89
|
+
} catch (e) {
|
|
90
|
+
if (isMissing(e)) continue;
|
|
91
|
+
throw new Error(`restore ${name}: ${msg(e)}`, { cause: e });
|
|
92
|
+
}
|
|
93
|
+
try {
|
|
94
|
+
await copyFile(file, p);
|
|
95
|
+
} catch (e) {
|
|
96
|
+
throw new Error(`restore ${name}: ${msg(e)}`, { cause: e });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Copies `src` over `dst`, creating `dst`'s directory. An existing `dst` keeps its mode. */
|
|
103
|
+
async function copyFile(src: string, dst: string): Promise<void> {
|
|
104
|
+
const data = await fs.readFile(src);
|
|
105
|
+
await fs.mkdir(path.dirname(dst), { recursive: true, mode: 0o750 });
|
|
106
|
+
await fs.writeFile(dst, data);
|
|
107
|
+
}
|