@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,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs every agent-skill snippet under skills/<skill>/assets/snippets/<name>/
|
|
3
|
+
* and compares what it prints with <name>.expected. A snippet imports
|
|
4
|
+
* `@hop-top/kit/<sub>` as an adopter would; vitest.config.ts resolves that to
|
|
5
|
+
* src/, so no build is needed.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import { format } from "node:util";
|
|
12
|
+
import { describe, expect, it, vi } from "vitest";
|
|
13
|
+
|
|
14
|
+
const root = fileURLToPath(new URL("../skills", import.meta.url));
|
|
15
|
+
|
|
16
|
+
const snippets = readdirSync(root, { withFileTypes: true })
|
|
17
|
+
.filter((d) => d.isDirectory())
|
|
18
|
+
.flatMap((skill) => {
|
|
19
|
+
const dir = join(root, skill.name, "assets", "snippets");
|
|
20
|
+
if (!existsSync(dir)) return [];
|
|
21
|
+
return readdirSync(dir, { withFileTypes: true })
|
|
22
|
+
.filter((d) => d.isDirectory())
|
|
23
|
+
.map((d) => ({
|
|
24
|
+
id: `${skill.name}/${d.name}`,
|
|
25
|
+
source: join(dir, d.name, `${d.name}.ts`),
|
|
26
|
+
expected: join(dir, d.name, `${d.name}.expected`),
|
|
27
|
+
}));
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
/** Imports the snippet and returns what it wrote to stdout and console.log. */
|
|
31
|
+
async function run(source: string): Promise<string> {
|
|
32
|
+
const out: string[] = [];
|
|
33
|
+
const spy = vi.spyOn(process.stdout, "write").mockImplementation(((
|
|
34
|
+
chunk: string | Uint8Array,
|
|
35
|
+
) => {
|
|
36
|
+
out.push(String(chunk));
|
|
37
|
+
return true;
|
|
38
|
+
}) as typeof process.stdout.write);
|
|
39
|
+
const log = vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => {
|
|
40
|
+
out.push(format(...args) + "\n");
|
|
41
|
+
});
|
|
42
|
+
try {
|
|
43
|
+
await import(/* @vite-ignore */ source);
|
|
44
|
+
} finally {
|
|
45
|
+
spy.mockRestore();
|
|
46
|
+
log.mockRestore();
|
|
47
|
+
}
|
|
48
|
+
return out.join("");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
describe("skill snippets", () => {
|
|
52
|
+
it("finds at least one snippet", () => {
|
|
53
|
+
expect(snippets.length).toBeGreaterThan(0);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it.each(snippets)("$id matches its .expected", async ({ source, expected }) => {
|
|
57
|
+
expect(existsSync(source)).toBe(true);
|
|
58
|
+
expect(await run(source)).toBe(readFileSync(expected, "utf8"));
|
|
59
|
+
});
|
|
60
|
+
});
|
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
// migrator.json: the scenario types, their strict shape and the runner,
|
|
2
|
+
// modelled on the Go runner (recordingDriver, storingDriver, lockingDriver).
|
|
3
|
+
|
|
4
|
+
import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, chmodSync } from 'node:fs';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { basename, join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
import { expect } from 'vitest';
|
|
9
|
+
|
|
10
|
+
import type { Event } from '../../src/bus';
|
|
11
|
+
import type { Shape } from './conformance-support';
|
|
12
|
+
import {
|
|
13
|
+
BackupUnsupportedError,
|
|
14
|
+
Migrator,
|
|
15
|
+
Registry,
|
|
16
|
+
abortError,
|
|
17
|
+
defaultRegistry,
|
|
18
|
+
readVersionFile,
|
|
19
|
+
registerMigration,
|
|
20
|
+
resetRegistryForTest,
|
|
21
|
+
type Migration,
|
|
22
|
+
type MigratorOptions,
|
|
23
|
+
type SchemaDriver,
|
|
24
|
+
} from '../../src/upgrade/index';
|
|
25
|
+
|
|
26
|
+
const TOOL = 'conftool';
|
|
27
|
+
|
|
28
|
+
interface DriverCase {
|
|
29
|
+
name: string;
|
|
30
|
+
version?: string;
|
|
31
|
+
backup_fail?: string;
|
|
32
|
+
restore_fail?: string;
|
|
33
|
+
backup_unsupported?: boolean;
|
|
34
|
+
restore_unsupported?: boolean;
|
|
35
|
+
version_fail?: string;
|
|
36
|
+
set_version_fail?: string;
|
|
37
|
+
set_version_fail_for?: string;
|
|
38
|
+
stores_version?: boolean;
|
|
39
|
+
lock?: boolean;
|
|
40
|
+
lock_fail?: string;
|
|
41
|
+
lock_blocked?: boolean;
|
|
42
|
+
lock_sets_version?: string;
|
|
43
|
+
unlock_fail?: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
interface MigrationCase {
|
|
47
|
+
schema: string;
|
|
48
|
+
version: string;
|
|
49
|
+
fail?: string;
|
|
50
|
+
down?: boolean;
|
|
51
|
+
down_fail?: string;
|
|
52
|
+
verify?: boolean;
|
|
53
|
+
verify_fail?: string;
|
|
54
|
+
cancel?: boolean;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
interface EventCase {
|
|
58
|
+
topic: string;
|
|
59
|
+
payload: Record<string, unknown>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
interface Step {
|
|
63
|
+
op: string;
|
|
64
|
+
canceled?: boolean;
|
|
65
|
+
events?: EventCase[];
|
|
66
|
+
warnings?: string[];
|
|
67
|
+
error?: string | null;
|
|
68
|
+
calls?: string[];
|
|
69
|
+
history?: { schema: string; version: string }[];
|
|
70
|
+
versions?: Record<string, string>;
|
|
71
|
+
backups?: Record<string, string[]>;
|
|
72
|
+
stored?: Record<string, string>;
|
|
73
|
+
pre_run_versions?: Record<string, Record<string, string>>;
|
|
74
|
+
no_version_dir?: string[];
|
|
75
|
+
status?: { schema: string; current: string; target: string; pending: number; error: string | null }[];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface Scenario {
|
|
79
|
+
name: string;
|
|
80
|
+
target: string;
|
|
81
|
+
manual_rollback?: boolean;
|
|
82
|
+
retention?: number;
|
|
83
|
+
drivers: DriverCase[];
|
|
84
|
+
migrations: MigrationCase[];
|
|
85
|
+
backups?: Record<string, string[]>;
|
|
86
|
+
recorded_backups?: Record<string, Record<string, string>>;
|
|
87
|
+
locked_backups?: Record<string, string[]>;
|
|
88
|
+
baseline?: Record<string, { version?: string; error?: string }>;
|
|
89
|
+
final_verify?: boolean;
|
|
90
|
+
final_verify_fail?: string;
|
|
91
|
+
data_dir?: boolean;
|
|
92
|
+
registry?: string;
|
|
93
|
+
default_migrations?: MigrationCase[];
|
|
94
|
+
steps: Step[];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export interface MigratorFile {
|
|
98
|
+
scenarios: Scenario[];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const MIGRATION_SHAPE: Shape = {
|
|
102
|
+
schema: true,
|
|
103
|
+
version: true,
|
|
104
|
+
fail: true,
|
|
105
|
+
down: true,
|
|
106
|
+
down_fail: true,
|
|
107
|
+
verify: true,
|
|
108
|
+
verify_fail: true,
|
|
109
|
+
cancel: true,
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
export const MIGRATOR_SHAPE: Shape = {
|
|
113
|
+
scenarios: [
|
|
114
|
+
{
|
|
115
|
+
name: true,
|
|
116
|
+
target: true,
|
|
117
|
+
manual_rollback: true,
|
|
118
|
+
retention: true,
|
|
119
|
+
drivers: [
|
|
120
|
+
{
|
|
121
|
+
name: true,
|
|
122
|
+
version: true,
|
|
123
|
+
backup_fail: true,
|
|
124
|
+
restore_fail: true,
|
|
125
|
+
backup_unsupported: true,
|
|
126
|
+
restore_unsupported: true,
|
|
127
|
+
version_fail: true,
|
|
128
|
+
set_version_fail: true,
|
|
129
|
+
set_version_fail_for: true,
|
|
130
|
+
stores_version: true,
|
|
131
|
+
lock: true,
|
|
132
|
+
lock_fail: true,
|
|
133
|
+
lock_blocked: true,
|
|
134
|
+
lock_sets_version: true,
|
|
135
|
+
unlock_fail: true,
|
|
136
|
+
},
|
|
137
|
+
],
|
|
138
|
+
migrations: [MIGRATION_SHAPE],
|
|
139
|
+
backups: true,
|
|
140
|
+
recorded_backups: true,
|
|
141
|
+
locked_backups: true,
|
|
142
|
+
baseline: true,
|
|
143
|
+
final_verify: true,
|
|
144
|
+
final_verify_fail: true,
|
|
145
|
+
data_dir: true,
|
|
146
|
+
registry: true,
|
|
147
|
+
default_migrations: [MIGRATION_SHAPE],
|
|
148
|
+
steps: [
|
|
149
|
+
{
|
|
150
|
+
op: true,
|
|
151
|
+
canceled: true,
|
|
152
|
+
events: [{ topic: true, payload: { tool: true, to: true, applied: true, schema: true, error: true, from: true, stage: true, method: true, final: true } }],
|
|
153
|
+
warnings: [true],
|
|
154
|
+
error: true,
|
|
155
|
+
calls: [true],
|
|
156
|
+
history: [{ schema: true, version: true }],
|
|
157
|
+
versions: true,
|
|
158
|
+
backups: true,
|
|
159
|
+
stored: true,
|
|
160
|
+
pre_run_versions: true,
|
|
161
|
+
no_version_dir: [true],
|
|
162
|
+
status: [{ schema: true, current: true, target: true, pending: true, error: true }],
|
|
163
|
+
},
|
|
164
|
+
],
|
|
165
|
+
},
|
|
166
|
+
],
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
const failIf = (msg: string | undefined): void => {
|
|
170
|
+
if (msg) throw new Error(msg);
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
/** A recording driver: every state-changing call goes to `record`. */
|
|
174
|
+
function recordingDriver(dc: DriverCase, record: (e: string) => void): SchemaDriver {
|
|
175
|
+
let version = dc.version ?? '';
|
|
176
|
+
const name = dc.name;
|
|
177
|
+
const d: SchemaDriver & { lock?: SchemaDriver['lock']; storesVersion?: boolean } = {
|
|
178
|
+
name: () => name,
|
|
179
|
+
version() {
|
|
180
|
+
if (dc.lock) record(name + ' version');
|
|
181
|
+
if (dc.version_fail) throw new Error(dc.version_fail);
|
|
182
|
+
return version;
|
|
183
|
+
},
|
|
184
|
+
setVersion(v) {
|
|
185
|
+
record(`${name} set_version ${v}`);
|
|
186
|
+
if (dc.set_version_fail && (!dc.set_version_fail_for || dc.set_version_fail_for === v)) {
|
|
187
|
+
throw new Error(dc.set_version_fail);
|
|
188
|
+
}
|
|
189
|
+
version = v;
|
|
190
|
+
},
|
|
191
|
+
backup(dest) {
|
|
192
|
+
record(`${name} backup ${basename(dest)}`);
|
|
193
|
+
if (dc.backup_unsupported) throw new BackupUnsupportedError();
|
|
194
|
+
failIf(dc.backup_fail);
|
|
195
|
+
},
|
|
196
|
+
restore(src) {
|
|
197
|
+
record(`${name} restore ${basename(src)}`);
|
|
198
|
+
if (dc.restore_unsupported) throw new BackupUnsupportedError();
|
|
199
|
+
failIf(dc.restore_fail);
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
if (dc.stores_version) d.storesVersion = true;
|
|
203
|
+
if (dc.lock) {
|
|
204
|
+
d.lock = (signal) => {
|
|
205
|
+
record(name + ' lock');
|
|
206
|
+
if (dc.lock_blocked) {
|
|
207
|
+
if (signal?.aborted) throw abortError(signal);
|
|
208
|
+
throw new Error('lock would block forever: the step must set canceled');
|
|
209
|
+
}
|
|
210
|
+
failIf(dc.lock_fail);
|
|
211
|
+
if (dc.lock_sets_version) version = dc.lock_sets_version;
|
|
212
|
+
return () => {
|
|
213
|
+
record(name + ' unlock');
|
|
214
|
+
failIf(dc.unlock_fail);
|
|
215
|
+
};
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
return d;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const listDirs = (base: string, schema: string): string[] => {
|
|
222
|
+
try {
|
|
223
|
+
return readdirSync(join(base, 'backups', schema), { withFileTypes: true })
|
|
224
|
+
.filter((e) => e.isDirectory())
|
|
225
|
+
.map((e) => e.name)
|
|
226
|
+
.sort();
|
|
227
|
+
} catch {
|
|
228
|
+
return [];
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
const listPreRun = (base: string, schema: string): Record<string, string> => {
|
|
233
|
+
const dir = join(base, 'backups', schema);
|
|
234
|
+
const out: Record<string, string> = {};
|
|
235
|
+
let entries;
|
|
236
|
+
try {
|
|
237
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
238
|
+
} catch {
|
|
239
|
+
return out;
|
|
240
|
+
}
|
|
241
|
+
for (const e of entries) {
|
|
242
|
+
if (e.isDirectory() || !e.name.endsWith('.version')) continue;
|
|
243
|
+
out[e.name.slice(0, -'.version'.length)] = readFileSync(join(dir, e.name), 'utf8');
|
|
244
|
+
}
|
|
245
|
+
return out;
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
const exists = (p: string): boolean => {
|
|
249
|
+
try {
|
|
250
|
+
statSync(p);
|
|
251
|
+
return true;
|
|
252
|
+
} catch {
|
|
253
|
+
return false;
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
export async function runMigratorScenario(sc: Scenario): Promise<void> {
|
|
258
|
+
const tmp = mkdtempSync(join(tmpdir(), 'upgrade-conf-'));
|
|
259
|
+
const savedXdg = process.env['XDG_DATA_HOME'];
|
|
260
|
+
const cleanups: (() => void)[] = [];
|
|
261
|
+
resetRegistryForTest();
|
|
262
|
+
try {
|
|
263
|
+
process.env['XDG_DATA_HOME'] = join(tmp, 'xdg');
|
|
264
|
+
const xdgBase = join(tmp, 'xdg', 'hop', TOOL);
|
|
265
|
+
const base = sc.data_dir ? join(tmp, 'custom') : xdgBase;
|
|
266
|
+
|
|
267
|
+
const mkBackups = (m: Record<string, string[]> | undefined, locked: boolean): void => {
|
|
268
|
+
for (const [schema, dirs] of Object.entries(m ?? {})) {
|
|
269
|
+
mkdirSync(join(base, 'backups', schema), { recursive: true, mode: 0o750 });
|
|
270
|
+
for (const d of dirs) {
|
|
271
|
+
const dir = join(base, 'backups', schema, d);
|
|
272
|
+
if (!locked) {
|
|
273
|
+
mkdirSync(dir, { recursive: true, mode: 0o750 });
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
const inner = join(dir, 'locked');
|
|
277
|
+
mkdirSync(inner, { recursive: true, mode: 0o750 });
|
|
278
|
+
writeFileSync(join(inner, 'f'), '', { mode: 0o600 });
|
|
279
|
+
chmodSync(inner, 0o500);
|
|
280
|
+
cleanups.push(() => chmodSync(inner, 0o750));
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
for (const [schema, recorded] of Object.entries(sc.recorded_backups ?? {})) {
|
|
285
|
+
const dir = join(base, 'backups', schema);
|
|
286
|
+
mkdirSync(dir, { recursive: true, mode: 0o750 });
|
|
287
|
+
for (const [name, pre] of Object.entries(recorded)) {
|
|
288
|
+
mkdirSync(join(dir, name), { recursive: true, mode: 0o750 });
|
|
289
|
+
writeFileSync(join(dir, name + '.version'), pre, { mode: 0o600 });
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
mkBackups(sc.backups, false);
|
|
293
|
+
mkBackups(sc.locked_backups, true);
|
|
294
|
+
|
|
295
|
+
let calls: string[] = [];
|
|
296
|
+
const record = (e: string): void => void calls.push(e);
|
|
297
|
+
const ctl = new AbortController();
|
|
298
|
+
|
|
299
|
+
const build = (mc: MigrationCase): Migration => {
|
|
300
|
+
const mig: Migration = {
|
|
301
|
+
version: mc.version,
|
|
302
|
+
schema: mc.schema,
|
|
303
|
+
up() {
|
|
304
|
+
record(`${mc.schema} up ${mc.version}`);
|
|
305
|
+
if (mc.cancel) ctl.abort();
|
|
306
|
+
failIf(mc.fail);
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
if (mc.down || mc.down_fail) {
|
|
310
|
+
mig.down = () => {
|
|
311
|
+
record(`${mc.schema} down ${mc.version}`);
|
|
312
|
+
failIf(mc.down_fail);
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
if (mc.verify || mc.verify_fail) {
|
|
316
|
+
mig.verify = () => {
|
|
317
|
+
record(`${mc.schema} verify ${mc.version}`);
|
|
318
|
+
failIf(mc.verify_fail);
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
return mig;
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
let reg = defaultRegistry();
|
|
325
|
+
const opts: MigratorOptions = {};
|
|
326
|
+
if (sc.registry === 'own') {
|
|
327
|
+
reg = new Registry();
|
|
328
|
+
opts.registry = reg;
|
|
329
|
+
for (const mc of sc.default_migrations ?? []) registerMigration(build(mc));
|
|
330
|
+
}
|
|
331
|
+
for (const mc of sc.migrations) reg.register(build(mc));
|
|
332
|
+
if (sc.manual_rollback) opts.manualRollback = true;
|
|
333
|
+
if (sc.retention) opts.backupRetention = sc.retention;
|
|
334
|
+
if (sc.data_dir) opts.dataDir = base;
|
|
335
|
+
if (sc.final_verify || sc.final_verify_fail) {
|
|
336
|
+
opts.verify = (schema, version) => {
|
|
337
|
+
record(`${schema} final_verify ${version}`);
|
|
338
|
+
failIf(sc.final_verify_fail);
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
if (sc.baseline) {
|
|
342
|
+
const baseline = sc.baseline;
|
|
343
|
+
opts.baseline = (schema) => {
|
|
344
|
+
record(schema + ' baseline');
|
|
345
|
+
const b = baseline[schema] ?? {};
|
|
346
|
+
failIf(b.error);
|
|
347
|
+
return b.version ?? '';
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
let events: EventCase[] = [];
|
|
351
|
+
let warnings: string[] = [];
|
|
352
|
+
opts.publisher = {
|
|
353
|
+
publish(e: Event) {
|
|
354
|
+
expect(e.source).toBe('core.upgrade');
|
|
355
|
+
const payload = { ...(e.payload as Record<string, unknown>) };
|
|
356
|
+
if ('duration_ms' in payload) {
|
|
357
|
+
const d = payload['duration_ms'];
|
|
358
|
+
expect(Number.isInteger(d) && (d as number) >= 0, `${e.topic}: duration_ms = ${String(d)}`).toBe(true);
|
|
359
|
+
delete payload['duration_ms'];
|
|
360
|
+
}
|
|
361
|
+
events.push({ topic: e.topic, payload });
|
|
362
|
+
},
|
|
363
|
+
};
|
|
364
|
+
opts.warn = (m) => void warnings.push(m);
|
|
365
|
+
|
|
366
|
+
const m = new Migrator(TOOL, sc.target, opts);
|
|
367
|
+
for (const dc of sc.drivers) m.addDriver(recordingDriver(dc, record));
|
|
368
|
+
|
|
369
|
+
for (const [i, st] of sc.steps.entries()) {
|
|
370
|
+
const at = `step ${i}`;
|
|
371
|
+
calls = [];
|
|
372
|
+
events = [];
|
|
373
|
+
warnings = [];
|
|
374
|
+
let signal = ctl.signal;
|
|
375
|
+
if (st.canceled) {
|
|
376
|
+
const c = new AbortController();
|
|
377
|
+
c.abort();
|
|
378
|
+
signal = c.signal;
|
|
379
|
+
}
|
|
380
|
+
let err: unknown;
|
|
381
|
+
try {
|
|
382
|
+
if (st.op === 'run') await m.run(signal);
|
|
383
|
+
else if (st.op === 'rollback_latest') await m.rollbackLatest();
|
|
384
|
+
else if (st.op === 'status') {
|
|
385
|
+
const got = (await m.status()).map((s) => ({
|
|
386
|
+
schema: s.schema,
|
|
387
|
+
current: s.current,
|
|
388
|
+
target: s.target,
|
|
389
|
+
pending: s.pending,
|
|
390
|
+
error: s.error ? s.error.message : null,
|
|
391
|
+
}));
|
|
392
|
+
expect(st.status, `${at}: status op without status`).toBeDefined();
|
|
393
|
+
expect(got, at).toEqual(st.status);
|
|
394
|
+
} else throw new Error(`${at}: unknown op ${st.op}`);
|
|
395
|
+
} catch (e) {
|
|
396
|
+
err = e;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
if (st.error === null || st.error === undefined) {
|
|
400
|
+
expect(err, `${at}: unexpected error ${String((err as Error)?.message)}`).toBeUndefined();
|
|
401
|
+
} else {
|
|
402
|
+
expect(err, `${at}: no error, want ${st.error}`).toBeDefined();
|
|
403
|
+
expect((err as Error).message, at).toBe(st.error);
|
|
404
|
+
}
|
|
405
|
+
if (st.calls) expect(calls, `${at}: calls`).toEqual(st.calls);
|
|
406
|
+
if (st.history) expect(m.history(), `${at}: history`).toEqual(st.history);
|
|
407
|
+
if (st.events) expect(events, `${at}: events`).toEqual(st.events);
|
|
408
|
+
if (st.warnings) {
|
|
409
|
+
expect(warnings.length, `${at}: logged ${JSON.stringify(warnings)}, want prefixes ${JSON.stringify(st.warnings)}`).toBe(st.warnings.length);
|
|
410
|
+
st.warnings.forEach((w, j) => expect(warnings[j].startsWith(w), `${at}: logged ${warnings[j]}, want prefix ${w}`).toBe(true));
|
|
411
|
+
}
|
|
412
|
+
for (const [schema, want] of Object.entries(st.versions ?? {})) {
|
|
413
|
+
expect(await readVersionFile(base, schema), `${at}: ${schema} version file`).toBe(want);
|
|
414
|
+
}
|
|
415
|
+
for (const [schema, want] of Object.entries(st.backups ?? {})) {
|
|
416
|
+
expect(listDirs(base, schema), `${at}: ${schema} backups`).toEqual(want);
|
|
417
|
+
}
|
|
418
|
+
if (st.stored) {
|
|
419
|
+
const got = new Map((await m.status()).map((s) => [s.schema, s.current]));
|
|
420
|
+
for (const [schema, want] of Object.entries(st.stored)) {
|
|
421
|
+
expect(got.get(schema), `${at}: ${schema} stored version`).toBe(want);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
for (const [schema, want] of Object.entries(st.pre_run_versions ?? {})) {
|
|
425
|
+
expect(listPreRun(base, schema), `${at}: ${schema} pre-run versions`).toEqual(want);
|
|
426
|
+
}
|
|
427
|
+
for (const schema of st.no_version_dir ?? []) {
|
|
428
|
+
expect(exists(join(base, schema)), `${at}: ${schema} has a version dir`).toBe(false);
|
|
429
|
+
}
|
|
430
|
+
if (sc.data_dir) expect(exists(xdgBase), `${at}: XDG data dir touched despite dataDir`).toBe(false);
|
|
431
|
+
}
|
|
432
|
+
} finally {
|
|
433
|
+
for (const c of cleanups) c();
|
|
434
|
+
if (savedXdg === undefined) delete process.env['XDG_DATA_HOME'];
|
|
435
|
+
else process.env['XDG_DATA_HOME'] = savedXdg;
|
|
436
|
+
resetRegistryForTest();
|
|
437
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
438
|
+
}
|
|
439
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Shared by the conformance runners: where the corpus lives and the strict
|
|
2
|
+
// shape check that makes an unknown field fail the run.
|
|
3
|
+
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
import { dirname, join, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
export function corpusDir(): string {
|
|
9
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
10
|
+
for (let i = 0; i < 10; i++) {
|
|
11
|
+
const cand = join(dir, 'contracts', 'upgrade-v1');
|
|
12
|
+
if (existsSync(join(cand, 'versions.json'))) return cand;
|
|
13
|
+
dir = resolve(dir, '..');
|
|
14
|
+
}
|
|
15
|
+
throw new Error('contracts/upgrade-v1 not found above ' + dirname(fileURLToPath(import.meta.url)));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const DIR = corpusDir();
|
|
19
|
+
|
|
20
|
+
// ─── strict loading ───────────────────────────────────────────────────
|
|
21
|
+
|
|
22
|
+
export interface Shape {
|
|
23
|
+
[key: string]: Shape | true | readonly [Shape | true];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function strict(value: unknown, shape: Shape, where: string): void {
|
|
27
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
28
|
+
throw new Error(`${where}: not an object`);
|
|
29
|
+
}
|
|
30
|
+
for (const [key, val] of Object.entries(value as Record<string, unknown>)) {
|
|
31
|
+
const spec = shape[key];
|
|
32
|
+
if (spec === undefined) throw new Error(`${where}: unknown field "${key}"`);
|
|
33
|
+
if (spec === true) continue;
|
|
34
|
+
if (Array.isArray(spec)) {
|
|
35
|
+
if (!Array.isArray(val)) throw new Error(`${where}.${key}: not an array`);
|
|
36
|
+
const item = spec[0] as Shape | true;
|
|
37
|
+
val.forEach((v, i) => {
|
|
38
|
+
if (item !== true) strict(v, item, `${where}.${key}[${i}]`);
|
|
39
|
+
});
|
|
40
|
+
} else {
|
|
41
|
+
strict(val, spec as Shape, `${where}.${key}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Shared by the driver tests: a Migrator over a failing second migration,
|
|
2
|
+
// and a hand-built tar.gz writer for archives `tar` itself would not make.
|
|
3
|
+
|
|
4
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { gzipSync } from 'node:zlib';
|
|
8
|
+
|
|
9
|
+
import * as tar from 'tar';
|
|
10
|
+
|
|
11
|
+
/** Makes a temp dir; the returned function removes it. */
|
|
12
|
+
export function tempDir(prefix = 'upgrade-driver-'): { dir: string; cleanup: () => void } {
|
|
13
|
+
const dir = mkdtempSync(join(tmpdir(), prefix));
|
|
14
|
+
return { dir, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface RawMember {
|
|
18
|
+
path: string;
|
|
19
|
+
type?: 'File' | 'Directory' | 'SymbolicLink' | 'Link' | 'FIFO' | 'CharacterDevice';
|
|
20
|
+
body?: string;
|
|
21
|
+
linkpath?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Writes a gzip'd tar of exactly these members, names unchecked. */
|
|
25
|
+
export function writeRawTarGz(file: string, members: RawMember[]): void {
|
|
26
|
+
const blocks: Buffer[] = [];
|
|
27
|
+
for (const m of members) {
|
|
28
|
+
const body = Buffer.from(m.body ?? '');
|
|
29
|
+
const head = Buffer.alloc(512);
|
|
30
|
+
new tar.Header({
|
|
31
|
+
path: m.path,
|
|
32
|
+
type: m.type ?? 'File',
|
|
33
|
+
mode: 0o644,
|
|
34
|
+
size: body.length,
|
|
35
|
+
linkpath: m.linkpath,
|
|
36
|
+
}).encode(head, 0);
|
|
37
|
+
blocks.push(head);
|
|
38
|
+
if (body.length > 0) {
|
|
39
|
+
blocks.push(body, Buffer.alloc((512 - (body.length % 512)) % 512));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
blocks.push(Buffer.alloc(1024));
|
|
43
|
+
writeFileSync(file, gzipSync(Buffer.concat(blocks)));
|
|
44
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// A throwaway Postgres 16 container for the Postgres driver's integration
|
|
2
|
+
// tests: a unique name, a random loopback port, removed on stop. A missing
|
|
3
|
+
// or failing Docker makes start() throw, so the suite fails instead of
|
|
4
|
+
// skipping.
|
|
5
|
+
|
|
6
|
+
import { execFileSync, spawnSync } from 'node:child_process';
|
|
7
|
+
import { randomBytes } from 'node:crypto';
|
|
8
|
+
|
|
9
|
+
import { Client } from 'pg';
|
|
10
|
+
|
|
11
|
+
export interface PgContainer {
|
|
12
|
+
name: string;
|
|
13
|
+
/** Connection config of the container's `testdb`. */
|
|
14
|
+
config: { host: string; port: number; user: string; password: string; database: string };
|
|
15
|
+
stop(): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const IMAGE = 'postgres:16-alpine';
|
|
19
|
+
const READY = 'database system is ready to accept connections';
|
|
20
|
+
|
|
21
|
+
const docker = (...args: string[]): string =>
|
|
22
|
+
execFileSync('docker', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
|
|
23
|
+
|
|
24
|
+
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
|
|
25
|
+
|
|
26
|
+
export async function startPostgres(): Promise<PgContainer> {
|
|
27
|
+
const name = `kit-ts-pg-upgrade-${process.pid}-${randomBytes(3).toString('hex')}`;
|
|
28
|
+
try {
|
|
29
|
+
docker(
|
|
30
|
+
'run', '-d', '--rm', '--name', name,
|
|
31
|
+
'-e', 'POSTGRES_USER=test', '-e', 'POSTGRES_PASSWORD=test', '-e', 'POSTGRES_DB=testdb',
|
|
32
|
+
'-p', '127.0.0.1::5432', IMAGE,
|
|
33
|
+
);
|
|
34
|
+
} catch (e) {
|
|
35
|
+
throw new Error(`postgres container: ${(e as Error).message} (docker is required for these tests)`);
|
|
36
|
+
}
|
|
37
|
+
const stop = (): void => {
|
|
38
|
+
spawnSync('docker', ['rm', '-f', name], { stdio: 'ignore' });
|
|
39
|
+
};
|
|
40
|
+
try {
|
|
41
|
+
const port = Number(docker('port', name, '5432/tcp').split('\n')[0].split(':').pop());
|
|
42
|
+
const config = { host: '127.0.0.1', port, user: 'test', password: 'test', database: 'testdb' };
|
|
43
|
+
// The image restarts the server once after initdb: ready is the second line.
|
|
44
|
+
for (let i = 0; i < 240; i++) {
|
|
45
|
+
const logs = spawnSync('docker', ['logs', name], { encoding: 'utf8' });
|
|
46
|
+
const n = ((logs.stdout ?? '') + (logs.stderr ?? '')).split(READY).length - 1;
|
|
47
|
+
if (n >= 2) {
|
|
48
|
+
const c = new Client(config);
|
|
49
|
+
try {
|
|
50
|
+
await c.connect();
|
|
51
|
+
await c.end();
|
|
52
|
+
return { name, config, stop };
|
|
53
|
+
} catch {
|
|
54
|
+
// not accepting yet
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
await sleep(500);
|
|
58
|
+
}
|
|
59
|
+
throw new Error('postgres container did not become ready in 120s');
|
|
60
|
+
} catch (e) {
|
|
61
|
+
stop();
|
|
62
|
+
throw e;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Child process of the Postgres race test: one Migrator over its own
|
|
2
|
+
// connection pool. Applies three migrations, each appending one line to a
|
|
3
|
+
// shared file, so the parent can count how often each ran. Starts when the
|
|
4
|
+
// parent sends "go".
|
|
5
|
+
|
|
6
|
+
import { appendFileSync } from 'node:fs';
|
|
7
|
+
|
|
8
|
+
import { Pool } from 'pg';
|
|
9
|
+
|
|
10
|
+
import { Migrator } from '../../src/upgrade/migrator';
|
|
11
|
+
import { Registry } from '../../src/upgrade/migration';
|
|
12
|
+
import { openPostgresDriver } from '../../src/upgrade/drivers/postgres';
|
|
13
|
+
|
|
14
|
+
const { PGCFG, TABLE, SCHEMA, COUNTS, DATA_DIR } = process.env as Record<string, string>;
|
|
15
|
+
|
|
16
|
+
async function main(): Promise<void> {
|
|
17
|
+
const pool = new Pool({ ...JSON.parse(PGCFG), max: 3 });
|
|
18
|
+
const reg = new Registry();
|
|
19
|
+
for (const v of ['1.1.0', '1.2.0', '1.3.0']) {
|
|
20
|
+
reg.register({
|
|
21
|
+
version: v,
|
|
22
|
+
schema: SCHEMA,
|
|
23
|
+
up: async () => {
|
|
24
|
+
appendFileSync(COUNTS, `${process.pid} ${v}\n`);
|
|
25
|
+
await new Promise((r) => setTimeout(r, 60)); // widen the race window
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
const m = new Migrator('racetest', '1.3.0', { registry: reg, dataDir: DATA_DIR });
|
|
30
|
+
m.addDriver(await openPostgresDriver({ db: pool, connect: () => pool.connect(), table: TABLE, name: SCHEMA }));
|
|
31
|
+
await new Promise<void>((resolve) => process.once('message', () => resolve()));
|
|
32
|
+
process.send?.('started');
|
|
33
|
+
try {
|
|
34
|
+
await m.run();
|
|
35
|
+
process.send?.('ok');
|
|
36
|
+
} catch (e) {
|
|
37
|
+
process.send?.(`error ${(e as Error).message}`);
|
|
38
|
+
}
|
|
39
|
+
await pool.end();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
main().then(
|
|
43
|
+
() => process.exit(0),
|
|
44
|
+
(e) => {
|
|
45
|
+
process.send?.(`error ${(e as Error).message}`);
|
|
46
|
+
process.exit(1);
|
|
47
|
+
},
|
|
48
|
+
);
|