@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,395 @@
|
|
|
1
|
+
// Integration tests for the Postgres driver against a Postgres 16
|
|
2
|
+
// container started from this file (Docker is required: a missing Docker
|
|
3
|
+
// fails the run). Run with `make test-ts-upgrade-integration`.
|
|
4
|
+
|
|
5
|
+
import { fork } from 'node:child_process';
|
|
6
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { tmpdir } from 'node:os';
|
|
8
|
+
import { join, resolve } from 'node:path';
|
|
9
|
+
|
|
10
|
+
import { buildSync } from 'esbuild';
|
|
11
|
+
import { Client, Pool } from 'pg';
|
|
12
|
+
import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest';
|
|
13
|
+
|
|
14
|
+
import { startPostgres, type PgContainer } from '../../../test/upgrade/pg-container';
|
|
15
|
+
import { isBackupUnsupported, isCanceled, isNotRestored } from '../errors';
|
|
16
|
+
import { Registry } from '../migration';
|
|
17
|
+
import { Migrator } from '../migrator';
|
|
18
|
+
import { openPostgresDriver, type PostgresDriver } from './postgres';
|
|
19
|
+
|
|
20
|
+
let pg: PgContainer;
|
|
21
|
+
let seq = 0;
|
|
22
|
+
const cleanups: Array<() => Promise<void> | void> = [];
|
|
23
|
+
const warnings: string[] = [];
|
|
24
|
+
|
|
25
|
+
beforeAll(async () => {
|
|
26
|
+
pg = await startPostgres();
|
|
27
|
+
}, 180_000);
|
|
28
|
+
|
|
29
|
+
afterAll(() => pg?.stop());
|
|
30
|
+
|
|
31
|
+
afterEach(async () => {
|
|
32
|
+
while (cleanups.length) await cleanups.pop()!();
|
|
33
|
+
warnings.length = 0;
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const table = (): string => `v_${process.pid}_${++seq}`;
|
|
37
|
+
|
|
38
|
+
function pool(max = 4): Pool {
|
|
39
|
+
const p = new Pool({ ...pg.config, max });
|
|
40
|
+
cleanups.push(() => p.end());
|
|
41
|
+
return p;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function raw(): Promise<Client> {
|
|
45
|
+
const c = new Client(pg.config);
|
|
46
|
+
await c.connect();
|
|
47
|
+
cleanups.push(() => c.end());
|
|
48
|
+
return c;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function driver(p: Pool, t: string, name = 'app'): Promise<PostgresDriver> {
|
|
52
|
+
return openPostgresDriver({ db: p, connect: () => p.connect(), table: t, name });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// The key text the Go driver computes, written out on purpose: these tests
|
|
56
|
+
// must break if the TypeScript key ever drifts from Go's.
|
|
57
|
+
const goKey = (t: string, name: string): string => `kit-upgrade:${t}:${name}`;
|
|
58
|
+
|
|
59
|
+
/** Whether a separate session can take the session lock for `key` right now. */
|
|
60
|
+
async function otherCanLock(key: string): Promise<boolean> {
|
|
61
|
+
const c = await raw();
|
|
62
|
+
const r = await c.query('SELECT pg_try_advisory_lock(hashtextextended($1, 0)) AS ok', [key]);
|
|
63
|
+
const ok = r.rows[0].ok as boolean;
|
|
64
|
+
if (ok) await c.query('SELECT pg_advisory_unlock(hashtextextended($1, 0))', [key]);
|
|
65
|
+
return ok;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function registry(schema: string, steps: Array<[string, () => Promise<void> | void, (() => void) | undefined]>) {
|
|
69
|
+
const reg = new Registry();
|
|
70
|
+
for (const [version, up, down] of steps) reg.register({ version, schema, up, ...(down ? { down } : {}) });
|
|
71
|
+
return reg;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function migrator(
|
|
75
|
+
reg: Registry,
|
|
76
|
+
opts: { manual?: boolean; baseline?: () => string; verify?: () => void } = {},
|
|
77
|
+
): Migrator {
|
|
78
|
+
const dir = mkdtempSync(join(tmpdir(), 'kit-ts-pg-'));
|
|
79
|
+
cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
|
|
80
|
+
return new Migrator('pgtest', '9.9.9', {
|
|
81
|
+
registry: reg,
|
|
82
|
+
dataDir: dir,
|
|
83
|
+
manualRollback: opts.manual,
|
|
84
|
+
baseline: opts.baseline,
|
|
85
|
+
verify: opts.verify,
|
|
86
|
+
warn: (m) => warnings.push(m),
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
describe('version table', () => {
|
|
91
|
+
it('round-trips a version and upserts', async () => {
|
|
92
|
+
const p = pool();
|
|
93
|
+
const t = table();
|
|
94
|
+
const d = await driver(p, t);
|
|
95
|
+
expect(await d.version()).toBe('');
|
|
96
|
+
await d.setVersion('1.0.0');
|
|
97
|
+
expect(await d.version()).toBe('1.0.0');
|
|
98
|
+
await d.setVersion('1.1.0');
|
|
99
|
+
expect(await d.version()).toBe('1.1.0');
|
|
100
|
+
const other = await driver(p, t, 'other');
|
|
101
|
+
expect(await other.version()).toBe('');
|
|
102
|
+
await other.setVersion('7');
|
|
103
|
+
expect(await d.version()).toBe('1.1.0');
|
|
104
|
+
const rows = await p.query(`SELECT count(*)::int AS n FROM ${t}`);
|
|
105
|
+
expect(rows.rows[0].n).toBe(2);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('creates the table once under concurrent opens', async () => {
|
|
109
|
+
const p = pool(8);
|
|
110
|
+
const t = table();
|
|
111
|
+
await Promise.all(Array.from({ length: 6 }, () => driver(p, t)));
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it('never closes the callers pool', async () => {
|
|
115
|
+
const p = pool();
|
|
116
|
+
const t = table();
|
|
117
|
+
const d = await driver(p, t);
|
|
118
|
+
const m = migrator(registry('app', [['1.0.0', () => {}, undefined]]));
|
|
119
|
+
m.addDriver(d);
|
|
120
|
+
await m.run();
|
|
121
|
+
expect((await p.query('SELECT 1 AS one')).rows[0].one).toBe(1);
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
describe('Migrator over the driver', () => {
|
|
126
|
+
it('two real processes racing one database apply each migration once', async () => {
|
|
127
|
+
const work = mkdtempSync(join(tmpdir(), 'kit-ts-pg-race-'));
|
|
128
|
+
cleanups.push(() => rmSync(work, { recursive: true, force: true }));
|
|
129
|
+
const bundle = join(work, 'worker.cjs');
|
|
130
|
+
buildSync({
|
|
131
|
+
entryPoints: [resolve(__dirname, '../../../test/upgrade/pg-race-worker.ts')],
|
|
132
|
+
bundle: true,
|
|
133
|
+
platform: 'node',
|
|
134
|
+
format: 'cjs',
|
|
135
|
+
external: ['pg-native'],
|
|
136
|
+
outfile: bundle,
|
|
137
|
+
logLevel: 'silent',
|
|
138
|
+
});
|
|
139
|
+
const t = table();
|
|
140
|
+
const counts = join(work, 'counts');
|
|
141
|
+
writeFileSync(counts, '');
|
|
142
|
+
const env = {
|
|
143
|
+
...process.env,
|
|
144
|
+
PGCFG: JSON.stringify(pg.config),
|
|
145
|
+
TABLE: t,
|
|
146
|
+
SCHEMA: 'app',
|
|
147
|
+
COUNTS: counts,
|
|
148
|
+
DATA_DIR: work,
|
|
149
|
+
};
|
|
150
|
+
const kids = [0, 1].map(() => fork(bundle, [], { env, stdio: ['ignore', 'inherit', 'inherit', 'ipc'] }));
|
|
151
|
+
cleanups.push(() => kids.forEach((k) => k.kill()));
|
|
152
|
+
const results = kids.map(
|
|
153
|
+
(k) =>
|
|
154
|
+
new Promise<string>((resolveKid, reject) => {
|
|
155
|
+
k.on('message', (m) => {
|
|
156
|
+
if (m === 'ok' || String(m).startsWith('error')) resolveKid(String(m));
|
|
157
|
+
});
|
|
158
|
+
k.on('error', reject);
|
|
159
|
+
k.on('exit', (code) => code !== 0 && reject(new Error(`worker exited ${code}`)));
|
|
160
|
+
}),
|
|
161
|
+
);
|
|
162
|
+
// Both are connected and have the table before either starts.
|
|
163
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
164
|
+
kids.forEach((k) => k.send('go'));
|
|
165
|
+
expect(await Promise.all(results)).toEqual(['ok', 'ok']);
|
|
166
|
+
|
|
167
|
+
const lines = readFileSync(counts, 'utf8').trim().split('\n');
|
|
168
|
+
for (const v of ['1.1.0', '1.2.0', '1.3.0']) {
|
|
169
|
+
expect(lines.filter((l) => l.endsWith(` ${v}`))).toHaveLength(1);
|
|
170
|
+
}
|
|
171
|
+
expect(new Set(lines.map((l) => l.split(' ')[0])).size).toBe(1); // one process did all the work
|
|
172
|
+
expect(await (await driver(pool(), t)).version()).toBe('1.3.0');
|
|
173
|
+
}, 60_000);
|
|
174
|
+
|
|
175
|
+
it('releases the lock after a failed run: a second session acquires at once', async () => {
|
|
176
|
+
const p = pool();
|
|
177
|
+
const t = table();
|
|
178
|
+
const d = await driver(p, t);
|
|
179
|
+
// A failed final verify is rolled back by the Downs.
|
|
180
|
+
const reg = registry('app', [
|
|
181
|
+
['1.1.0', () => {}, () => {}],
|
|
182
|
+
['1.2.0', () => {}, () => {}],
|
|
183
|
+
]);
|
|
184
|
+
const m2 = migrator(reg, { verify: () => { throw new Error('boom'); } });
|
|
185
|
+
m2.addDriver(d);
|
|
186
|
+
await expect(m2.run()).rejects.toThrow('boom');
|
|
187
|
+
expect(await otherCanLock(goKey(t, 'app'))).toBe(true);
|
|
188
|
+
expect(await d.version()).toBe(''); // both steps undone by their Down
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
it('a failed up is not downed: not restored at the last step, lock released', async () => {
|
|
192
|
+
const p = pool();
|
|
193
|
+
const t = table();
|
|
194
|
+
const d = await driver(p, t);
|
|
195
|
+
const downs: string[] = [];
|
|
196
|
+
const m = migrator(
|
|
197
|
+
registry('app', [
|
|
198
|
+
['1.1.0', () => {}, () => void downs.push('1.1.0')],
|
|
199
|
+
['1.2.0', () => { throw new Error('boom'); }, () => void downs.push('1.2.0')],
|
|
200
|
+
]),
|
|
201
|
+
);
|
|
202
|
+
m.addDriver(d);
|
|
203
|
+
const err = await m.run().then(() => undefined, (e: unknown) => e as Error);
|
|
204
|
+
expect(err?.message).toContain('up 1.2.0 failed: boom');
|
|
205
|
+
expect(isNotRestored(err)).toBe(true);
|
|
206
|
+
expect(downs).toEqual([]);
|
|
207
|
+
expect(await otherCanLock(goKey(t, 'app'))).toBe(true);
|
|
208
|
+
expect(await d.version()).toBe('1.1.0');
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
it('a failed migration with no Down is not restored and keeps the last step', async () => {
|
|
212
|
+
const p = pool();
|
|
213
|
+
const t = table();
|
|
214
|
+
const d = await driver(p, t);
|
|
215
|
+
await d.setVersion('1.0.0');
|
|
216
|
+
const m = migrator(
|
|
217
|
+
registry('app', [
|
|
218
|
+
['1.1.0', () => {}, undefined],
|
|
219
|
+
['1.2.0', () => { throw new Error('boom'); }, undefined],
|
|
220
|
+
]),
|
|
221
|
+
);
|
|
222
|
+
m.addDriver(d);
|
|
223
|
+
const err = await m.run().then(() => undefined, (e: unknown) => e);
|
|
224
|
+
expect(isNotRestored(err)).toBe(true);
|
|
225
|
+
expect(isBackupUnsupported(err)).toBe(true);
|
|
226
|
+
expect(await d.version()).toBe('1.1.0');
|
|
227
|
+
expect(await otherCanLock(goKey(t, 'app'))).toBe(true);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it('manual rollbackLatest finds no backup, restores nothing and unlocks', async () => {
|
|
231
|
+
const p = pool();
|
|
232
|
+
const t = table();
|
|
233
|
+
const d = await driver(p, t);
|
|
234
|
+
await d.setVersion('1.0.0');
|
|
235
|
+
const m = migrator(
|
|
236
|
+
registry('app', [
|
|
237
|
+
['1.1.0', () => {}, undefined],
|
|
238
|
+
['1.2.0', () => { throw new Error('boom'); }, undefined],
|
|
239
|
+
]),
|
|
240
|
+
{ manual: true },
|
|
241
|
+
);
|
|
242
|
+
m.addDriver(d);
|
|
243
|
+
await expect(m.run()).rejects.toThrow('boom');
|
|
244
|
+
const err = await m.rollbackLatest().then(() => undefined, (e: unknown) => e);
|
|
245
|
+
expect(String((err as Error).message)).toContain('no backups found');
|
|
246
|
+
expect(isNotRestored(err)).toBe(true);
|
|
247
|
+
expect(await d.version()).toBe('1.1.0');
|
|
248
|
+
expect(await otherCanLock(goKey(t, 'app'))).toBe(true);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it('baselines a pre-existing table and runs an additive column migration', async () => {
|
|
252
|
+
const p = pool();
|
|
253
|
+
const t = table();
|
|
254
|
+
const widgets = `widgets_${process.pid}_${seq}`;
|
|
255
|
+
await p.query(`CREATE TABLE ${widgets} (id INT PRIMARY KEY)`);
|
|
256
|
+
await p.query(`INSERT INTO ${widgets} (id) VALUES (1), (2)`);
|
|
257
|
+
const d = await driver(p, t);
|
|
258
|
+
const m = migrator(
|
|
259
|
+
registry('app', [
|
|
260
|
+
['1.0.0', () => { throw new Error('baseline schema must not run again'); }, undefined],
|
|
261
|
+
['1.1.0', async () => void (await p.query(`ALTER TABLE ${widgets} ADD COLUMN color TEXT NOT NULL DEFAULT 'red'`)), undefined],
|
|
262
|
+
]),
|
|
263
|
+
{ baseline: () => '1.0.0' },
|
|
264
|
+
);
|
|
265
|
+
m.addDriver(d);
|
|
266
|
+
await m.run();
|
|
267
|
+
expect(await d.version()).toBe('1.1.0');
|
|
268
|
+
const r = await p.query(`SELECT id, color FROM ${widgets} ORDER BY id`);
|
|
269
|
+
expect(r.rows).toEqual([{ id: 1, color: 'red' }, { id: 2, color: 'red' }]);
|
|
270
|
+
expect(m.history().map((a) => a.version)).toEqual(['1.1.0']);
|
|
271
|
+
});
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
describe('lock', () => {
|
|
275
|
+
it('pooled client: unlock runs before the client goes back to the pool', async () => {
|
|
276
|
+
const p = pool(3);
|
|
277
|
+
const t = table();
|
|
278
|
+
const d = await driver(p, t);
|
|
279
|
+
const unlock = await d.lock();
|
|
280
|
+
expect(await otherCanLock(goKey(t, 'app'))).toBe(false);
|
|
281
|
+
await unlock();
|
|
282
|
+
// Returned to the pool, still connected: the session lock must be gone,
|
|
283
|
+
// or the next user of that pooled connection inherits it for ever.
|
|
284
|
+
expect(p.idleCount).toBeGreaterThan(0);
|
|
285
|
+
expect(await otherCanLock(goKey(t, 'app'))).toBe(true);
|
|
286
|
+
// The pool reuses that very connection: it holds no lock.
|
|
287
|
+
const again = await p.connect();
|
|
288
|
+
const held = await again.query(
|
|
289
|
+
"SELECT count(*)::int AS n FROM pg_locks WHERE locktype = 'advisory' AND pid = pg_backend_pid()",
|
|
290
|
+
);
|
|
291
|
+
expect(held.rows[0].n).toBe(0);
|
|
292
|
+
again.release();
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
it('a lock excludes a second run until it is unlocked', async () => {
|
|
296
|
+
const p = pool(4);
|
|
297
|
+
const t = table();
|
|
298
|
+
const a = await driver(p, t);
|
|
299
|
+
const b = await driver(pool(4), t);
|
|
300
|
+
const unlock = await a.lock();
|
|
301
|
+
const ac = new AbortController();
|
|
302
|
+
setTimeout(() => ac.abort(), 250);
|
|
303
|
+
await expect(b.lock(ac.signal)).rejects.toSatisfy(isCanceled);
|
|
304
|
+
let got = false;
|
|
305
|
+
const waiter = b.lock().then(async (un) => {
|
|
306
|
+
got = true;
|
|
307
|
+
await un();
|
|
308
|
+
});
|
|
309
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
310
|
+
expect(got).toBe(false);
|
|
311
|
+
await unlock();
|
|
312
|
+
await waiter;
|
|
313
|
+
expect(got).toBe(true);
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
it('an aborted wait holds nothing and returns no connection with a lock', async () => {
|
|
317
|
+
const p = pool(3);
|
|
318
|
+
const t = table();
|
|
319
|
+
const d = await driver(p, t);
|
|
320
|
+
const holder = await raw();
|
|
321
|
+
await holder.query('SELECT pg_advisory_lock(hashtextextended($1, 0))', [goKey(t, 'app')]);
|
|
322
|
+
|
|
323
|
+
const ac = new AbortController();
|
|
324
|
+
const began = Date.now();
|
|
325
|
+
setTimeout(() => ac.abort(), 300);
|
|
326
|
+
const err = await d.lock(ac.signal).then(() => undefined, (e: unknown) => e);
|
|
327
|
+
expect(isCanceled(err)).toBe(true);
|
|
328
|
+
expect((err as Error).message).toBe('context canceled');
|
|
329
|
+
expect(Date.now() - began).toBeGreaterThanOrEqual(250);
|
|
330
|
+
expect(p.totalCount).toBe(p.idleCount); // nothing checked out
|
|
331
|
+
const locks = await holder.query(
|
|
332
|
+
"SELECT count(*)::int AS n FROM pg_locks WHERE locktype = 'advisory' AND granted AND pid <> pg_backend_pid()",
|
|
333
|
+
);
|
|
334
|
+
expect(locks.rows[0].n).toBe(0);
|
|
335
|
+
const waiting = await holder.query(
|
|
336
|
+
"SELECT count(*)::int AS n FROM pg_locks WHERE locktype = 'advisory' AND NOT granted",
|
|
337
|
+
);
|
|
338
|
+
expect(waiting.rows[0].n).toBe(0);
|
|
339
|
+
|
|
340
|
+
// Once the holder lets go, the next lock is granted.
|
|
341
|
+
await holder.query('SELECT pg_advisory_unlock(hashtextextended($1, 0))', [goKey(t, 'app')]);
|
|
342
|
+
const unlock = await d.lock();
|
|
343
|
+
await unlock();
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
it('a Go-style session on the same table and schema excludes the driver, and the reverse', async () => {
|
|
347
|
+
const p = pool(3);
|
|
348
|
+
const t = table();
|
|
349
|
+
const d = await driver(p, t);
|
|
350
|
+
const key = goKey(t, 'app');
|
|
351
|
+
|
|
352
|
+
// Go holds: a blocking pg_advisory_lock on the key text, hashed server side.
|
|
353
|
+
const goSession = await raw();
|
|
354
|
+
await goSession.query('SELECT pg_advisory_lock(hashtextextended($1, 0))', [key]);
|
|
355
|
+
const ac = new AbortController();
|
|
356
|
+
setTimeout(() => ac.abort(), 300);
|
|
357
|
+
await expect(d.lock(ac.signal)).rejects.toSatisfy(isCanceled);
|
|
358
|
+
await goSession.query('SELECT pg_advisory_unlock(hashtextextended($1, 0))', [key]);
|
|
359
|
+
|
|
360
|
+
// TypeScript holds: Go's blocking statement cannot be granted; the lock
|
|
361
|
+
// sits on exactly the 64-bit key the server derives from the Go text.
|
|
362
|
+
const unlock = await d.lock();
|
|
363
|
+
const probe = await raw();
|
|
364
|
+
const k = await probe.query('SELECT hashtextextended($1, 0) AS k', [key]);
|
|
365
|
+
const big = BigInt.asUintN(64, BigInt(k.rows[0].k as string));
|
|
366
|
+
const classid = Number(big >> 32n);
|
|
367
|
+
const objid = Number(big & 0xffffffffn);
|
|
368
|
+
const lk = await probe.query(
|
|
369
|
+
"SELECT classid::bigint AS classid, objid::bigint AS objid, objsubid, mode, granted FROM pg_locks WHERE locktype = 'advisory'",
|
|
370
|
+
);
|
|
371
|
+
expect(lk.rows).toEqual([{ classid: String(classid), objid: String(objid), objsubid: 1, mode: 'ExclusiveLock', granted: true }]);
|
|
372
|
+
await probe.query("SET lock_timeout = '300ms'");
|
|
373
|
+
await expect(probe.query('SELECT pg_advisory_lock(hashtextextended($1, 0))', [key])).rejects.toMatchObject({ code: '55P03' });
|
|
374
|
+
expect((await probe.query('SELECT pg_try_advisory_lock(hashtextextended($1, 0)) AS ok', [key])).rows[0].ok).toBe(false);
|
|
375
|
+
await unlock();
|
|
376
|
+
expect((await probe.query('SELECT pg_try_advisory_lock(hashtextextended($1, 0)) AS ok', [key])).rows[0].ok).toBe(true);
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
it('a pool of one is refused at lock time, and a run reports it instead of hanging', async () => {
|
|
380
|
+
const one = pool(1);
|
|
381
|
+
const t = table();
|
|
382
|
+
const d = await driver(one, t);
|
|
383
|
+
await expect(d.lock()).rejects.toThrow(/at least two connections/);
|
|
384
|
+
const m = migrator(registry('app', [['1.0.0', () => {}, undefined]]));
|
|
385
|
+
m.addDriver(d);
|
|
386
|
+
await expect(m.run()).rejects.toThrow(/migrate app: lock: .*at least two connections/);
|
|
387
|
+
// The pool is untouched and usable.
|
|
388
|
+
expect((await one.query('SELECT 1 AS one')).rows[0].one).toBe(1);
|
|
389
|
+
// Two connections is enough.
|
|
390
|
+
const two = pool(2);
|
|
391
|
+
const m2 = migrator(registry('app', [['1.0.0', () => {}, undefined]]));
|
|
392
|
+
m2.addDriver(await driver(two, t));
|
|
393
|
+
await m2.run();
|
|
394
|
+
});
|
|
395
|
+
});
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// Unit tests for the Postgres driver that need no database: a fake client
|
|
2
|
+
// records the SQL and stands in for the server.
|
|
3
|
+
|
|
4
|
+
import { describe, expect, it } from 'vitest';
|
|
5
|
+
|
|
6
|
+
import type { SchemaDriver } from '../driver';
|
|
7
|
+
import { isBackupUnsupported, isCanceled } from '../errors';
|
|
8
|
+
import {
|
|
9
|
+
PostgresDriver,
|
|
10
|
+
SQL_LOCK,
|
|
11
|
+
SQL_TRY_LOCK,
|
|
12
|
+
SQL_UNLOCK,
|
|
13
|
+
SQL_XACT_LOCK,
|
|
14
|
+
createTableSql,
|
|
15
|
+
ddlKey,
|
|
16
|
+
lockKey,
|
|
17
|
+
openPostgresDriver,
|
|
18
|
+
upsertSql,
|
|
19
|
+
validateTable,
|
|
20
|
+
versionSql,
|
|
21
|
+
type PgLockClient,
|
|
22
|
+
type PgQueryable,
|
|
23
|
+
type PgResult,
|
|
24
|
+
} from './postgres';
|
|
25
|
+
|
|
26
|
+
interface Call {
|
|
27
|
+
text: string;
|
|
28
|
+
params?: unknown[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
class FakeClient implements PgLockClient {
|
|
32
|
+
calls: Call[] = [];
|
|
33
|
+
released: Array<boolean | Error | undefined> = [];
|
|
34
|
+
/** Answers per statement text; default is no rows. */
|
|
35
|
+
answers = new Map<string, (params?: unknown[]) => PgResult | Promise<PgResult>>();
|
|
36
|
+
async query(text: string, params?: unknown[]): Promise<PgResult> {
|
|
37
|
+
this.calls.push({ text, params });
|
|
38
|
+
const a = this.answers.get(text);
|
|
39
|
+
return a ? a(params) : { rows: [] };
|
|
40
|
+
}
|
|
41
|
+
release(destroy?: boolean | Error): void {
|
|
42
|
+
this.released.push(destroy);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const rows = (v: unknown): PgResult => ({ rows: [{ col: v }] });
|
|
47
|
+
|
|
48
|
+
function driverOver(db: PgQueryable, client: PgLockClient, name?: string): Promise<PostgresDriver> {
|
|
49
|
+
return openPostgresDriver({ db, connect: async () => client, table: 'schema_versions', name: name ?? 'app' });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Compile-time: the driver is a SchemaDriver the Migrator accepts.
|
|
53
|
+
export const _asSchemaDriver = (d: PostgresDriver): SchemaDriver => d;
|
|
54
|
+
|
|
55
|
+
describe('validateTable', () => {
|
|
56
|
+
const ok = ['schema_versions', '_t', 'T1', 'a'.repeat(64)];
|
|
57
|
+
const bad = ['', '1abc', 'a-b', 'a b', 'a.b', 'a;drop table x', 'a'.repeat(65), '"quoted"', 'naïve'];
|
|
58
|
+
it.each(ok)('accepts %s', (n) => expect(() => validateTable(n)).not.toThrow());
|
|
59
|
+
it.each(bad)('rejects %j with the Go message', (n) => {
|
|
60
|
+
expect(() => validateTable(n)).toThrow(`invalid table name: ${JSON.stringify(n)}`);
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
describe('SQL text and keys (pinned to the Go driver)', () => {
|
|
65
|
+
it('has the shared statements', () => {
|
|
66
|
+
expect(SQL_LOCK).toBe('SELECT pg_advisory_lock(hashtextextended($1, 0))');
|
|
67
|
+
expect(SQL_UNLOCK).toBe('SELECT pg_advisory_unlock(hashtextextended($1, 0))');
|
|
68
|
+
expect(SQL_XACT_LOCK).toBe('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))');
|
|
69
|
+
expect(SQL_TRY_LOCK).toBe('SELECT pg_try_advisory_lock(hashtextextended($1, 0))');
|
|
70
|
+
expect(createTableSql('t')).toBe(
|
|
71
|
+
"CREATE TABLE IF NOT EXISTS t (schema_name TEXT PRIMARY KEY, version TEXT NOT NULL DEFAULT '')",
|
|
72
|
+
);
|
|
73
|
+
expect(versionSql('t')).toBe('SELECT version FROM t WHERE schema_name = $1');
|
|
74
|
+
expect(upsertSql('t')).toBe(
|
|
75
|
+
'INSERT INTO t (schema_name, version) VALUES ($1, $2) ' +
|
|
76
|
+
'ON CONFLICT (schema_name) DO UPDATE SET version = EXCLUDED.version',
|
|
77
|
+
);
|
|
78
|
+
});
|
|
79
|
+
it('builds the lock key text', () => {
|
|
80
|
+
expect(lockKey('schema_versions', 'app')).toBe('kit-upgrade:schema_versions:app');
|
|
81
|
+
expect(ddlKey('schema_versions')).toBe('kit-upgrade:schema_versions:ddl');
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
describe('openPostgresDriver', () => {
|
|
86
|
+
it('validates the table before any I/O', async () => {
|
|
87
|
+
let connected = false;
|
|
88
|
+
const db: PgQueryable = { query: async () => ({ rows: [] }) };
|
|
89
|
+
await expect(
|
|
90
|
+
openPostgresDriver({ db, connect: async () => ((connected = true), new FakeClient()), table: 'a-b' }),
|
|
91
|
+
).rejects.toThrow('invalid table name: "a-b"');
|
|
92
|
+
expect(connected).toBe(false);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('creates the table in a transaction under the DDL lock, then releases the client', async () => {
|
|
96
|
+
const c = new FakeClient();
|
|
97
|
+
const d = await driverOver({ query: async () => ({ rows: [] }) }, c);
|
|
98
|
+
expect(c.calls.map((x) => x.text)).toEqual([
|
|
99
|
+
'BEGIN',
|
|
100
|
+
SQL_XACT_LOCK,
|
|
101
|
+
createTableSql('schema_versions'),
|
|
102
|
+
'COMMIT',
|
|
103
|
+
]);
|
|
104
|
+
expect(c.calls[1].params).toEqual(['kit-upgrade:schema_versions:ddl']);
|
|
105
|
+
expect(c.released).toEqual([undefined]);
|
|
106
|
+
expect(d.name()).toBe('app');
|
|
107
|
+
expect(d.storesVersion).toBe(true);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('defaults the schema name to postgres', async () => {
|
|
111
|
+
const d = await openPostgresDriver({
|
|
112
|
+
db: { query: async () => ({ rows: [] }) },
|
|
113
|
+
connect: async () => new FakeClient(),
|
|
114
|
+
table: 't',
|
|
115
|
+
});
|
|
116
|
+
expect(d.name()).toBe('postgres');
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it('rolls back and wraps a failed DDL', async () => {
|
|
120
|
+
const c = new FakeClient();
|
|
121
|
+
c.answers.set(createTableSql('schema_versions'), () => Promise.reject(new Error('boom')));
|
|
122
|
+
await expect(driverOver({ query: async () => ({ rows: [] }) }, c)).rejects.toThrow(
|
|
123
|
+
'postgres upgrade: migrate: boom',
|
|
124
|
+
);
|
|
125
|
+
expect(c.calls.at(-1)?.text).toBe('ROLLBACK');
|
|
126
|
+
expect(c.released).toEqual([undefined]);
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
describe('version, setVersion, backup', () => {
|
|
131
|
+
it('reads "" for no row, the stored value otherwise, and upserts', async () => {
|
|
132
|
+
const seen: Call[] = [];
|
|
133
|
+
let row: unknown[] = [];
|
|
134
|
+
const db: PgQueryable = {
|
|
135
|
+
query: async (text, params) => {
|
|
136
|
+
seen.push({ text, params });
|
|
137
|
+
return { rows: row as PgResult['rows'] };
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
const d = await driverOver(db, new FakeClient());
|
|
141
|
+
expect(await d.version()).toBe('');
|
|
142
|
+
row = [{ version: '1.2.0' }];
|
|
143
|
+
expect(await d.version()).toBe('1.2.0');
|
|
144
|
+
await d.setVersion('1.3.0');
|
|
145
|
+
expect(seen[0]).toEqual({ text: versionSql('schema_versions'), params: ['app'] });
|
|
146
|
+
expect(seen[2]).toEqual({ text: upsertSql('schema_versions'), params: ['app', '1.3.0'] });
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it('wraps a failed read', async () => {
|
|
150
|
+
const db: PgQueryable = { query: () => Promise.reject(new Error('down')) };
|
|
151
|
+
const d = await driverOver(db, new FakeClient());
|
|
152
|
+
await expect(d.version()).rejects.toThrow('postgres upgrade: version: down');
|
|
153
|
+
await expect(d.setVersion('1')).rejects.toThrow('postgres upgrade: set version: down');
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('reports backup and restore unsupported', async () => {
|
|
157
|
+
const d = await driverOver({ query: async () => ({ rows: [] }) }, new FakeClient());
|
|
158
|
+
await expect(d.backup('/x')).rejects.toSatisfy(isBackupUnsupported);
|
|
159
|
+
await expect(d.restore('/x')).rejects.toSatisfy(isBackupUnsupported);
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
describe('lock', () => {
|
|
164
|
+
const db: PgQueryable = { query: async () => ({ rows: [] }) };
|
|
165
|
+
|
|
166
|
+
async function lockable(answer: (p?: unknown[]) => PgResult | Promise<PgResult>) {
|
|
167
|
+
const ddl = new FakeClient();
|
|
168
|
+
const lockClient = new FakeClient();
|
|
169
|
+
lockClient.answers.set(SQL_TRY_LOCK, answer);
|
|
170
|
+
lockClient.answers.set(SQL_UNLOCK, () => rows(true));
|
|
171
|
+
let n = 0;
|
|
172
|
+
const d = await openPostgresDriver({
|
|
173
|
+
db,
|
|
174
|
+
connect: async () => (n++ === 0 ? ddl : lockClient),
|
|
175
|
+
table: 'schema_versions',
|
|
176
|
+
name: 'app',
|
|
177
|
+
});
|
|
178
|
+
return { d, lockClient };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
it('takes the key, then unlocks on the same client before releasing it', async () => {
|
|
182
|
+
const { d, lockClient } = await lockable(() => rows(true));
|
|
183
|
+
const unlock = await d.lock();
|
|
184
|
+
expect(lockClient.calls).toEqual([{ text: SQL_TRY_LOCK, params: ['kit-upgrade:schema_versions:app'] }]);
|
|
185
|
+
expect(lockClient.released).toEqual([]);
|
|
186
|
+
await unlock();
|
|
187
|
+
await unlock();
|
|
188
|
+
expect(lockClient.calls.map((c) => c.text)).toEqual([SQL_TRY_LOCK, SQL_UNLOCK]);
|
|
189
|
+
expect(lockClient.calls[1].params).toEqual(['kit-upgrade:schema_versions:app']);
|
|
190
|
+
expect(lockClient.released).toEqual([undefined]);
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
it('destroys the client when unlock answers false or fails', async () => {
|
|
194
|
+
for (const bad of [() => rows(false), () => Promise.reject(new Error('gone'))]) {
|
|
195
|
+
const { d, lockClient } = await lockable(() => rows(true));
|
|
196
|
+
lockClient.answers.set(SQL_UNLOCK, bad);
|
|
197
|
+
const unlock = await d.lock();
|
|
198
|
+
await expect(unlock()).rejects.toThrow('postgres upgrade: unlock:');
|
|
199
|
+
expect(lockClient.released).toEqual([true]);
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it('refuses a pool of one before connecting', async () => {
|
|
204
|
+
let connects = 0;
|
|
205
|
+
const one: PgQueryable = { query: async () => ({ rows: [] }), options: { max: 1 } };
|
|
206
|
+
const d = await openPostgresDriver({
|
|
207
|
+
db: one,
|
|
208
|
+
connect: async () => (connects++, new FakeClient()),
|
|
209
|
+
table: 't',
|
|
210
|
+
});
|
|
211
|
+
const before = connects;
|
|
212
|
+
await expect(d.lock()).rejects.toThrow(/at least two connections/);
|
|
213
|
+
expect(connects).toBe(before);
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
it('aborted wait rejects with the abort error and destroys the client', async () => {
|
|
217
|
+
const { d, lockClient } = await lockable(() => rows(false));
|
|
218
|
+
const ac = new AbortController();
|
|
219
|
+
const p = d.lock(ac.signal);
|
|
220
|
+
setTimeout(() => ac.abort(), 120);
|
|
221
|
+
const err = await p.then(() => undefined, (e: unknown) => e);
|
|
222
|
+
expect(isCanceled(err)).toBe(true);
|
|
223
|
+
expect((err as Error).message).toBe('context canceled');
|
|
224
|
+
expect(lockClient.released).toEqual([true]);
|
|
225
|
+
expect(lockClient.calls.every((c) => c.text === SQL_TRY_LOCK)).toBe(true);
|
|
226
|
+
expect(lockClient.calls.length).toBeGreaterThan(1);
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it('a signal already aborted connects to nothing', async () => {
|
|
230
|
+
const { d, lockClient } = await lockable(() => rows(true));
|
|
231
|
+
const ac = new AbortController();
|
|
232
|
+
ac.abort();
|
|
233
|
+
await expect(d.lock(ac.signal)).rejects.toSatisfy(isCanceled);
|
|
234
|
+
expect(lockClient.calls).toEqual([]);
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it('a lock won as the abort lands is destroyed, not returned', async () => {
|
|
238
|
+
const ac = new AbortController();
|
|
239
|
+
const { d, lockClient } = await lockable(() => {
|
|
240
|
+
ac.abort();
|
|
241
|
+
return rows(true);
|
|
242
|
+
});
|
|
243
|
+
await expect(d.lock(ac.signal)).rejects.toSatisfy(isCanceled);
|
|
244
|
+
expect(lockClient.released).toEqual([true]);
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
it('wraps a connect failure', async () => {
|
|
248
|
+
let n = 0;
|
|
249
|
+
const d = await openPostgresDriver({
|
|
250
|
+
db,
|
|
251
|
+
connect: async () => {
|
|
252
|
+
if (n++ === 0) return new FakeClient();
|
|
253
|
+
throw new Error('refused');
|
|
254
|
+
},
|
|
255
|
+
table: 't',
|
|
256
|
+
});
|
|
257
|
+
await expect(d.lock()).rejects.toThrow('postgres upgrade: lock: refused');
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it('ends a standalone client (no release) through end()', async () => {
|
|
261
|
+
let ended = 0;
|
|
262
|
+
const standalone: PgLockClient = {
|
|
263
|
+
query: async (text) => (text === SQL_UNLOCK || text === SQL_TRY_LOCK ? rows(true) : { rows: [] }),
|
|
264
|
+
end: async () => void ended++,
|
|
265
|
+
};
|
|
266
|
+
const d = await openPostgresDriver({ db, connect: async () => standalone, table: 't' });
|
|
267
|
+
ended = 0; // the DDL client was ended too
|
|
268
|
+
const unlock = await d.lock();
|
|
269
|
+
await unlock();
|
|
270
|
+
expect(ended).toBe(1);
|
|
271
|
+
});
|
|
272
|
+
});
|