@tryghost/mg-context 0.11.9 → 0.11.10-0
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/README.md +73 -832
- package/build/index.d.ts +10 -4
- package/build/index.js +5 -2
- package/build/index.js.map +1 -1
- package/build/lib/AuthorContext.d.ts +3 -3
- package/build/lib/AuthorContext.js +32 -34
- package/build/lib/AuthorContext.js.map +1 -1
- package/build/lib/MigrateBase.js +2 -2
- package/build/lib/MigrateBase.js.map +1 -1
- package/build/lib/MigrateContext.d.ts +139 -36
- package/build/lib/MigrateContext.js +606 -324
- package/build/lib/MigrateContext.js.map +1 -1
- package/build/lib/PostContext.d.ts +72 -16
- package/build/lib/PostContext.js +191 -123
- package/build/lib/PostContext.js.map +1 -1
- package/build/lib/SourceRecords.d.ts +80 -0
- package/build/lib/SourceRecords.js +385 -0
- package/build/lib/SourceRecords.js.map +1 -0
- package/build/lib/TagContext.d.ts +1 -1
- package/build/lib/TagContext.js +35 -37
- package/build/lib/TagContext.js.map +1 -1
- package/build/lib/database.d.ts +47 -11
- package/build/lib/database.js +189 -24
- package/build/lib/database.js.map +1 -1
- package/build/lib/db-helpers.d.ts +1 -5
- package/build/lib/db-helpers.js +7 -37
- package/build/lib/db-helpers.js.map +1 -1
- package/build/lib/export-filename.d.ts +1 -0
- package/build/lib/export-filename.js +11 -0
- package/build/lib/export-filename.js.map +1 -0
- package/build/lib/ghost-csv.d.ts +10 -0
- package/build/lib/ghost-csv.js +55 -0
- package/build/lib/ghost-csv.js.map +1 -0
- package/build/lib/ghost-json.d.ts +4 -0
- package/build/lib/ghost-json.js +108 -0
- package/build/lib/ghost-json.js.map +1 -0
- package/build/lib/ghost-schema.d.ts +58 -0
- package/build/lib/ghost-schema.js +61 -0
- package/build/lib/ghost-schema.js.map +1 -0
- package/build/lib/json.d.ts +8 -0
- package/build/lib/json.js +40 -0
- package/build/lib/json.js.map +1 -0
- package/build/lib/migration-report.d.ts +3 -0
- package/build/lib/migration-report.js +41 -0
- package/build/lib/migration-report.js.map +1 -0
- package/build/lib/source-schema.d.ts +1 -0
- package/build/lib/source-schema.js +44 -0
- package/build/lib/source-schema.js.map +1 -0
- package/build/test/fixtures/mg-context-v2.d.ts +5 -0
- package/build/test/fixtures/mg-context-v2.js +58 -0
- package/build/test/fixtures/mg-context-v2.js.map +1 -0
- package/build/test/ghost-csv.test.d.ts +1 -0
- package/build/test/ghost-csv.test.js +333 -0
- package/build/test/ghost-csv.test.js.map +1 -0
- package/build/test/ghost-schema.test.d.ts +1 -0
- package/build/test/ghost-schema.test.js +38 -0
- package/build/test/ghost-schema.test.js.map +1 -0
- package/build/test/migrate-base.test.js +0 -6
- package/build/test/migrate-base.test.js.map +1 -1
- package/build/test/migrate-context.test.js +1094 -250
- package/build/test/migrate-context.test.js.map +1 -1
- package/build/test/package-exports.test.d.ts +1 -0
- package/build/test/package-exports.test.js +50 -0
- package/build/test/package-exports.test.js.map +1 -0
- package/build/test/post-context.test.js +36 -151
- package/build/test/post-context.test.js.map +1 -1
- package/build/test/source-records.test.d.ts +1 -0
- package/build/test/source-records.test.js +625 -0
- package/build/test/source-records.test.js.map +1 -0
- package/build/test/stream-export.test.d.ts +1 -0
- package/build/test/stream-export.test.js +401 -0
- package/build/test/stream-export.test.js.map +1 -0
- package/package.json +10 -7
|
@@ -0,0 +1,625 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { describe, it } from 'node:test';
|
|
3
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
7
|
+
import { MigrateContext, PostContext, TagContext, AuthorContext } from '../index.js';
|
|
8
|
+
import { createDatabase, queueDatabaseEvent } from '../lib/database.js';
|
|
9
|
+
const raw = (key, content = 'Original 🚀 & <b>text</b>') => ({
|
|
10
|
+
kind: 'post',
|
|
11
|
+
key,
|
|
12
|
+
content,
|
|
13
|
+
format: 'text'
|
|
14
|
+
});
|
|
15
|
+
async function context(t, persistent = false) {
|
|
16
|
+
const directory = await mkdtemp(join(tmpdir(), 'mg-source-'));
|
|
17
|
+
const instance = new MigrateContext(persistent ? { dbPath: join(directory, 'context.sqlite') } : { storage: 'memory' });
|
|
18
|
+
await instance.init();
|
|
19
|
+
t.after(async () => {
|
|
20
|
+
await instance.close();
|
|
21
|
+
await rm(directory, { recursive: true, force: true });
|
|
22
|
+
});
|
|
23
|
+
return instance;
|
|
24
|
+
}
|
|
25
|
+
async function collect(input) {
|
|
26
|
+
const values = [];
|
|
27
|
+
for await (const value of input) {
|
|
28
|
+
values.push(value);
|
|
29
|
+
}
|
|
30
|
+
return values;
|
|
31
|
+
}
|
|
32
|
+
function post(ctx, slug = 'post') {
|
|
33
|
+
const value = new PostContext({ lookupKey: slug });
|
|
34
|
+
value.set('title', slug);
|
|
35
|
+
value.set('slug', slug);
|
|
36
|
+
value.set('created_at', new Date('2026-01-01T00:00:00Z'));
|
|
37
|
+
value.save(ctx.db);
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
describe('shared source records', () => {
|
|
41
|
+
it('requires initialization and explicitly rejects removed options', async () => {
|
|
42
|
+
const uninitialized = new MigrateContext();
|
|
43
|
+
assert.throws(() => uninitialized.sources, /not initialized/);
|
|
44
|
+
assert.throws(() => new MigrateContext({ contentIdentity: { source: 'x' } }), /removed/);
|
|
45
|
+
for (const field of ['source', 'sourceContent', 'sourceMeta', 'meta']) {
|
|
46
|
+
assert.throws(() => new PostContext({ [field]: {} }), /removed/);
|
|
47
|
+
}
|
|
48
|
+
await uninitialized.close();
|
|
49
|
+
const database = createDatabase(':memory:');
|
|
50
|
+
queueDatabaseEvent(database, { type: 'unused', payload: {} });
|
|
51
|
+
database.db.close();
|
|
52
|
+
});
|
|
53
|
+
it('distinguishes absent and completed empty ingestion across reopening', async (t) => {
|
|
54
|
+
const ctx = await context(t, true);
|
|
55
|
+
assert.equal(ctx.sources.hasCompletedIngestion, false);
|
|
56
|
+
assert.equal(ctx.sources.currentIngestion, null);
|
|
57
|
+
assert.equal(ctx.sources.count(), 0);
|
|
58
|
+
assert.equal(ctx.sources.get('post', 'absent'), null);
|
|
59
|
+
assert.equal(ctx.sources.getById(1), null);
|
|
60
|
+
assert.deepEqual(await collect(ctx.sources.records()), []);
|
|
61
|
+
const metadata = { label: 'caller-owned', nested: { version: 2 } };
|
|
62
|
+
const info = await ctx.sources.ingest({ metadata }, () => { });
|
|
63
|
+
assert.deepEqual(info.metadata, metadata);
|
|
64
|
+
metadata.nested.version = 3;
|
|
65
|
+
assert.equal(ctx.sources.hasCompletedIngestion, true);
|
|
66
|
+
assert.equal(ctx.sources.count(), 0);
|
|
67
|
+
assert.equal(ctx.hasContent(), false);
|
|
68
|
+
assert.ok(info.completedAt);
|
|
69
|
+
await ctx.close();
|
|
70
|
+
await ctx.init();
|
|
71
|
+
assert.equal(ctx.sources.hasCompletedIngestion, true);
|
|
72
|
+
assert.deepEqual(ctx.sources.currentIngestion.metadata, { label: 'caller-owned', nested: { version: 2 } });
|
|
73
|
+
await assert.rejects(ctx.sources.ingest({}, () => { }), /explicitly request replacement/);
|
|
74
|
+
});
|
|
75
|
+
it('stores opaque records of any kind and closes the staging write API', async (t) => {
|
|
76
|
+
const ctx = await context(t);
|
|
77
|
+
let handle;
|
|
78
|
+
await ctx.sources.ingest({}, stage => {
|
|
79
|
+
handle = stage;
|
|
80
|
+
assert.equal(ctx.sources.count(), 0);
|
|
81
|
+
const first = stage.put({ ...raw('1'), metadata: { file: 'a.xml', line: 3 } });
|
|
82
|
+
stage.put({ kind: 'attachment', key: '1', content: '{bad JSON}', format: 'json' });
|
|
83
|
+
stage.put(raw(null, ''));
|
|
84
|
+
stage.put(raw());
|
|
85
|
+
assert.equal(stage.count(), 4);
|
|
86
|
+
assert.equal(stage.count('post'), 3);
|
|
87
|
+
assert.deepEqual(stage.getById(first.id), first);
|
|
88
|
+
first.metadata.line = 99;
|
|
89
|
+
assert.equal(stage.get('post', '1').metadata.line, 3);
|
|
90
|
+
});
|
|
91
|
+
assert.equal(ctx.sources.count(), 4);
|
|
92
|
+
assert.equal(ctx.sources.count('attachment'), 1);
|
|
93
|
+
assert.equal(ctx.sources.get('attachment', '1').content, '{bad JSON}');
|
|
94
|
+
assert.deepEqual((await collect(ctx.sources.records({ kind: 'post', batchSize: 1 }))).map(row => row.key), ['1', null, null]);
|
|
95
|
+
assert.deepEqual(await collect(ctx.sources.records({ kind: 'missing' })), []);
|
|
96
|
+
assert.equal(ctx.sources.get('post', '1').content, raw().content);
|
|
97
|
+
assert.throws(() => handle.put(raw('closed')), /closed/);
|
|
98
|
+
assert.throws(() => handle.count(), /closed/);
|
|
99
|
+
});
|
|
100
|
+
it('requires explicit duplicate resolution and preserves canonical IDs and ordering', async (t) => {
|
|
101
|
+
const ctx = await context(t);
|
|
102
|
+
await ctx.sources.ingest({}, stage => {
|
|
103
|
+
const original = stage.put(raw('same'));
|
|
104
|
+
assert.throws(() => stage.put(raw('same', 'ignored')), /Duplicate source/);
|
|
105
|
+
assert.equal(stage.put(raw('same', 'ignored'), { onDuplicate: 'keep' }).id, original.id);
|
|
106
|
+
assert.equal(stage.get('post', 'same').content, raw().content);
|
|
107
|
+
const replacement = stage.put({ ...raw('same', 'new'), format: 'markdown', metadata: { revision: 2 } }, { onDuplicate: 'replace' });
|
|
108
|
+
assert.equal(replacement.id, original.id);
|
|
109
|
+
assert.equal(stage.get('post', 'same').format, 'markdown');
|
|
110
|
+
assert.deepEqual(replacement.metadata, { revision: 2 });
|
|
111
|
+
assert.throws(() => stage.put(raw('other'), { onDuplicate: 'newest' }), /Unknown source duplicate policy/);
|
|
112
|
+
});
|
|
113
|
+
assert.equal(ctx.sources.count(), 1);
|
|
114
|
+
assert.equal(ctx.sources.get('post', 'same').content, 'new');
|
|
115
|
+
});
|
|
116
|
+
it('validates records and JSON metadata without interpreting payload formats', async (t) => {
|
|
117
|
+
const ctx = await context(t);
|
|
118
|
+
const cycle = {};
|
|
119
|
+
cycle.self = cycle;
|
|
120
|
+
const sparse = [];
|
|
121
|
+
sparse.length = 2;
|
|
122
|
+
await ctx.sources.ingest({}, stage => {
|
|
123
|
+
for (const invalid of [
|
|
124
|
+
null,
|
|
125
|
+
{ ...raw(), kind: '' },
|
|
126
|
+
{ ...raw(), format: ' ' },
|
|
127
|
+
{ ...raw(), content: 3 },
|
|
128
|
+
{ ...raw(), key: '' },
|
|
129
|
+
{ ...raw(), key: 3 }
|
|
130
|
+
]) {
|
|
131
|
+
assert.throws(() => stage.put(invalid), /Source records require/);
|
|
132
|
+
}
|
|
133
|
+
for (const metadata of [
|
|
134
|
+
null,
|
|
135
|
+
[],
|
|
136
|
+
'x',
|
|
137
|
+
{ bad: undefined },
|
|
138
|
+
{ bad: NaN },
|
|
139
|
+
{ bad: BigInt(1) },
|
|
140
|
+
{ bad: new Date() },
|
|
141
|
+
cycle,
|
|
142
|
+
{ sparse }
|
|
143
|
+
]) {
|
|
144
|
+
assert.throws(() => stage.put({ ...raw(), metadata }), /Metadata/);
|
|
145
|
+
}
|
|
146
|
+
const shared = { yes: true };
|
|
147
|
+
stage.put({
|
|
148
|
+
...raw(),
|
|
149
|
+
metadata: { one: shared, two: shared, values: [null, false, 1, 'x'], empty: Object.create(null) }
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
assert.equal(ctx.sources.count(), 1);
|
|
153
|
+
for (const batchSize of [0, 1.2, Infinity]) {
|
|
154
|
+
await assert.rejects(collect(ctx.sources.records({ batchSize })), /positive/);
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
it('writes bounded committed batches without keeping transactions open during input waits', async (t) => {
|
|
158
|
+
const ctx = await context(t, true);
|
|
159
|
+
await ctx.sources.ingest({}, async (stage) => {
|
|
160
|
+
const shared = { label: 'before' };
|
|
161
|
+
async function* input() {
|
|
162
|
+
yield { ...raw('1', 'a'), metadata: shared };
|
|
163
|
+
shared.label = 'after';
|
|
164
|
+
assert.equal(ctx.db.inTransaction, false);
|
|
165
|
+
yield raw('2', 'b');
|
|
166
|
+
assert.equal(stage.count(), 2);
|
|
167
|
+
yield raw('3', 'x'.repeat(100));
|
|
168
|
+
assert.equal(stage.count(), 3);
|
|
169
|
+
yield raw('4', 'x');
|
|
170
|
+
}
|
|
171
|
+
assert.equal(await stage.write(input(), { batchSize: 2, maxBatchBytes: 60 }), 4);
|
|
172
|
+
assert.equal(stage.get('post', '1').metadata.label, 'before');
|
|
173
|
+
await stage.write([raw('5', 'x'), raw('6', 'x')], { batchSize: 20, maxBatchBytes: 15 });
|
|
174
|
+
assert.equal(await stage.write([]), 0);
|
|
175
|
+
for (const options of [{ batchSize: 0 }, { maxBatchBytes: 0 }]) {
|
|
176
|
+
await assert.rejects(stage.write([], options), /positive/);
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
await ctx.sources.ingest({ replace: true }, async (stage) => {
|
|
180
|
+
await stage.write([raw()]);
|
|
181
|
+
});
|
|
182
|
+
assert.equal(ctx.sources.count(), 1);
|
|
183
|
+
});
|
|
184
|
+
it('detaches prepared records when a parser reuses its input object', async (t) => {
|
|
185
|
+
const ctx = await context(t);
|
|
186
|
+
const input = { ...raw('first', 'first body'), metadata: { nested: { label: 'first' } } };
|
|
187
|
+
await ctx.sources.ingest({}, async (stage) => {
|
|
188
|
+
function* records() {
|
|
189
|
+
yield input;
|
|
190
|
+
input.key = 'second';
|
|
191
|
+
input.content = 'second body';
|
|
192
|
+
input.metadata.nested.label = 'second';
|
|
193
|
+
yield input;
|
|
194
|
+
input.metadata.nested.label = 'after ingestion';
|
|
195
|
+
}
|
|
196
|
+
await stage.write(records());
|
|
197
|
+
});
|
|
198
|
+
assert.equal(ctx.sources.get('post', 'first').content, 'first body');
|
|
199
|
+
assert.deepEqual(ctx.sources.get('post', 'first').metadata, { nested: { label: 'first' } });
|
|
200
|
+
assert.equal(ctx.sources.get('post', 'second').content, 'second body');
|
|
201
|
+
assert.deepEqual(ctx.sources.get('post', 'second').metadata, { nested: { label: 'second' } });
|
|
202
|
+
});
|
|
203
|
+
it('preserves originals, mapped content, and links after a failed replacement', async (t) => {
|
|
204
|
+
const ctx = await context(t);
|
|
205
|
+
await ctx.sources.ingest({}, stage => {
|
|
206
|
+
stage.put(raw('old'));
|
|
207
|
+
});
|
|
208
|
+
const original = post(ctx);
|
|
209
|
+
const record = ctx.sources.get('post', 'old');
|
|
210
|
+
ctx.sources.link(record.id, { type: 'post', id: original.dbId });
|
|
211
|
+
ctx.recordDiagnostic('mapping:kept', {}, record.id);
|
|
212
|
+
await assert.rejects(ctx.sources.ingest({ replace: true }, async (stage) => {
|
|
213
|
+
assert.equal(ctx.sources.get('post', 'old').id, record.id);
|
|
214
|
+
await stage.write([raw('new')], { batchSize: 1 });
|
|
215
|
+
stage.recordDiagnostic('source:warning', { reason: 'data' }, stage.get('post', 'new').id);
|
|
216
|
+
throw new Error('input failed');
|
|
217
|
+
}), /input failed/);
|
|
218
|
+
assert.equal(ctx.sources.count(), 1);
|
|
219
|
+
assert.equal(ctx.sources.get('post', 'new'), null);
|
|
220
|
+
assert.equal((await ctx.getAllPosts())[0].ghostId, original.ghostId);
|
|
221
|
+
assert.equal((await collect(ctx.sources.recordsFor({ type: 'post', id: original.dbId }))).length, 1);
|
|
222
|
+
const events = await collect(ctx.streamDiagnostics({ phase: 'ingestion' }));
|
|
223
|
+
assert.deepEqual(events.map(event => event.type), ['source:warning', 'source:failed']);
|
|
224
|
+
assert.equal((await collect(ctx.streamDiagnostics({ ingestionId: events[0].ingestionId, batchSize: 1 }))).length, 2);
|
|
225
|
+
assert.equal(ctx.getMigrationReport().summary['mapping:kept'], 1);
|
|
226
|
+
await ctx.sources.ingest({ replace: true }, stage => {
|
|
227
|
+
stage.put(raw('new'));
|
|
228
|
+
});
|
|
229
|
+
assert.equal(ctx.hasContent(), false);
|
|
230
|
+
assert.equal(ctx.sources.getById(record.id), null);
|
|
231
|
+
assert.equal(ctx.getMigrationReport().summary['mapping:kept'], undefined);
|
|
232
|
+
assert.equal((await collect(ctx.streamDiagnostics())).length, 2);
|
|
233
|
+
});
|
|
234
|
+
it('rolls back a failed promotion without discarding the active generation', async (t) => {
|
|
235
|
+
const ctx = await context(t);
|
|
236
|
+
await ctx.sources.ingest({}, stage => {
|
|
237
|
+
stage.put(raw('old'));
|
|
238
|
+
});
|
|
239
|
+
const original = post(ctx);
|
|
240
|
+
ctx.db.db.exec("CREATE TRIGGER fail_promote BEFORE UPDATE OF status ON SourceIngestions WHEN NEW.status = 'complete' BEGIN SELECT RAISE(ABORT, 'promotion failed'); END;");
|
|
241
|
+
await assert.rejects(ctx.sources.ingest({ replace: true }, stage => {
|
|
242
|
+
stage.put(raw('new'));
|
|
243
|
+
}), /promotion failed/);
|
|
244
|
+
assert.ok(ctx.sources.get('post', 'old'));
|
|
245
|
+
assert.equal((await ctx.getAllPosts())[0].ghostId, original.ghostId);
|
|
246
|
+
ctx.db.db.exec('DROP TRIGGER fail_promote;');
|
|
247
|
+
});
|
|
248
|
+
it('discards interrupted staging on the next attempt while retaining its diagnostics', async (t) => {
|
|
249
|
+
const ctx = await context(t, true);
|
|
250
|
+
await ctx.sources.ingest({}, stage => {
|
|
251
|
+
stage.put(raw('old'));
|
|
252
|
+
});
|
|
253
|
+
ctx.db.db.exec("INSERT INTO SourceIngestions(status, metadata, started_at) VALUES ('staging', '{}', 'interrupted');");
|
|
254
|
+
const id = ctx.db.db.prepare("SELECT id FROM SourceIngestions WHERE status = 'staging'").get().id;
|
|
255
|
+
ctx.db.db
|
|
256
|
+
.prepare("INSERT INTO SourceRecords(ingestion_id, kind, content, format, metadata) VALUES (?, 'post', 'partial', 'text', '{}')")
|
|
257
|
+
.run(id);
|
|
258
|
+
ctx.db.db
|
|
259
|
+
.prepare("INSERT INTO MigrationEvents(type, details, created_at, phase, ingestion_id) VALUES ('source:warning', '{}', 'then', 'ingestion', ?)")
|
|
260
|
+
.run(id);
|
|
261
|
+
await ctx.close();
|
|
262
|
+
await ctx.init();
|
|
263
|
+
assert.equal(ctx.sources.count(), 1);
|
|
264
|
+
await ctx.sources.ingest({ replace: true }, stage => {
|
|
265
|
+
assert.equal(stage.count(), 0);
|
|
266
|
+
stage.put(raw('fresh'));
|
|
267
|
+
});
|
|
268
|
+
assert.equal(ctx.db.db.prepare('SELECT COUNT(*) AS n FROM SourceRecords').get().n, 1);
|
|
269
|
+
assert.deepEqual((await collect(ctx.streamDiagnostics({ ingestionId: id }))).map(row => row.type), ['source:warning', 'source:failed']);
|
|
270
|
+
});
|
|
271
|
+
it('closes resources and invalidates ingestion handles even if the callback outlives the context', async (t) => {
|
|
272
|
+
const ctx = await context(t, true);
|
|
273
|
+
let handle;
|
|
274
|
+
await assert.rejects(ctx.sources.ingest({}, async (stage) => {
|
|
275
|
+
handle = stage;
|
|
276
|
+
stage.put(raw('partial'));
|
|
277
|
+
await ctx.close();
|
|
278
|
+
}), /closed during ingestion/);
|
|
279
|
+
assert.throws(() => handle.put(raw('late')), /closed/);
|
|
280
|
+
await ctx.close();
|
|
281
|
+
await ctx.init();
|
|
282
|
+
assert.equal(ctx.sources.hasCompletedIngestion, false);
|
|
283
|
+
assert.equal(ctx.getMigrationReport().summary['source:failed'], 1);
|
|
284
|
+
});
|
|
285
|
+
it('guards overlapping lifecycles and invalid ingestion arguments', async (t) => {
|
|
286
|
+
const ctx = await context(t);
|
|
287
|
+
await assert.rejects(ctx.sources.ingest({ replace: 1 }, () => { }), /boolean/);
|
|
288
|
+
await assert.rejects(ctx.sources.ingest({}, null), /callback/);
|
|
289
|
+
await assert.rejects(ctx.sources.ingest({ metadata: [] }, () => { }), /Metadata/);
|
|
290
|
+
await ctx.transaction(async () => {
|
|
291
|
+
await assert.rejects(ctx.sources.ingest({}, () => { }), /mapped transaction/);
|
|
292
|
+
});
|
|
293
|
+
await ctx.sources.ingest({}, async (stage) => {
|
|
294
|
+
const item = stage.put(raw('1'));
|
|
295
|
+
await assert.rejects(ctx.sources.ingest({}, () => { }), /cannot overlap/);
|
|
296
|
+
assert.throws(() => ctx.reset(), /cannot overlap/);
|
|
297
|
+
await assert.rejects(ctx.rebuildMappedContent(() => { }), /cannot overlap/);
|
|
298
|
+
assert.throws(() => stage.recordDiagnostic(''), /Diagnostic requires/);
|
|
299
|
+
assert.throws(() => stage.recordDiagnostic('source:bad', {}, item.id + 1), /Diagnostic requires/);
|
|
300
|
+
stage.recordDiagnostic('source:ok');
|
|
301
|
+
});
|
|
302
|
+
assert.throws(() => ctx.recordDiagnostic(''), /Diagnostic requires/);
|
|
303
|
+
assert.throws(() => ctx.recordDiagnostic('bad', {}, 9999), /Diagnostic requires/);
|
|
304
|
+
ctx.recordDiagnostic('mapping:ok');
|
|
305
|
+
await assert.rejects(collect(ctx.streamDiagnostics({ batchSize: 0 })), /positive/);
|
|
306
|
+
});
|
|
307
|
+
it('supports many-to-many typed provenance and cascading mapped cleanup', async (t) => {
|
|
308
|
+
const ctx = await context(t);
|
|
309
|
+
await ctx.sources.ingest({}, stage => {
|
|
310
|
+
stage.put(raw('1'));
|
|
311
|
+
stage.put(raw('2'));
|
|
312
|
+
});
|
|
313
|
+
const [first, second] = await collect(ctx.sources.records());
|
|
314
|
+
const mapped = post(ctx);
|
|
315
|
+
const tag = new TagContext({ name: 'Tag', slug: 'tag' });
|
|
316
|
+
tag.save(ctx.db);
|
|
317
|
+
const author = new AuthorContext({ name: 'Author', slug: 'author', email: 'a@example.com' });
|
|
318
|
+
author.save(ctx.db);
|
|
319
|
+
const entities = [
|
|
320
|
+
{ type: 'post', id: mapped.dbId },
|
|
321
|
+
{ type: 'tag', id: tag.dbId },
|
|
322
|
+
{ type: 'author', id: author.dbId }
|
|
323
|
+
];
|
|
324
|
+
for (const entity of entities) {
|
|
325
|
+
ctx.sources.link(first.id, entity);
|
|
326
|
+
ctx.sources.link(first.id, entity);
|
|
327
|
+
}
|
|
328
|
+
ctx.sources.link(second.id, entities[0]);
|
|
329
|
+
assert.deepEqual(await collect(ctx.sources.entitiesFor(first.id, { batchSize: 1 })), entities);
|
|
330
|
+
assert.equal((await collect(ctx.sources.recordsFor(entities[0], { batchSize: 1 }))).length, 2);
|
|
331
|
+
ctx.sources.unlink(second.id, entities[0]);
|
|
332
|
+
assert.equal((await collect(ctx.sources.recordsFor(entities[0]))).length, 1);
|
|
333
|
+
assert.throws(() => ctx.sources.link(999, entities[0]), /completed source record/);
|
|
334
|
+
assert.throws(() => ctx.sources.link(first.id, { type: 'file', id: 1 }), /existing post/);
|
|
335
|
+
assert.throws(() => ctx.sources.link(first.id, { type: 'post', id: 999 }), /existing post/);
|
|
336
|
+
await assert.rejects(collect(ctx.sources.entitiesFor(first.id, { batchSize: 0 })), /positive/);
|
|
337
|
+
await assert.rejects(collect(ctx.sources.recordsFor(entities[0], { batchSize: 0 })), /positive/);
|
|
338
|
+
ctx.db.db.prepare('DELETE FROM Posts WHERE id = ?').run(mapped.dbId);
|
|
339
|
+
ctx.db.db.prepare('DELETE FROM Tags WHERE id = ?').run(tag.dbId);
|
|
340
|
+
ctx.db.db.prepare('DELETE FROM Authors WHERE id = ?').run(author.dbId);
|
|
341
|
+
assert.deepEqual(await collect(ctx.sources.entitiesFor(first.id)), []);
|
|
342
|
+
});
|
|
343
|
+
it('rebuilds from originals on every call and restores mapped data on unexpected errors', async (t) => {
|
|
344
|
+
const ctx = await context(t);
|
|
345
|
+
await ctx.sources.ingest({}, stage => {
|
|
346
|
+
stage.put(raw('1'));
|
|
347
|
+
stage.recordDiagnostic('source:kept');
|
|
348
|
+
});
|
|
349
|
+
let generation = 0;
|
|
350
|
+
async function map() {
|
|
351
|
+
await ctx.rebuildMappedContent(async () => {
|
|
352
|
+
for await (const record of ctx.sources.records()) {
|
|
353
|
+
const value = post(ctx, `mapped-${++generation}`);
|
|
354
|
+
ctx.sources.link(record.id, { type: 'post', id: value.dbId });
|
|
355
|
+
ctx.addLink('/old', `/${value.data.slug}`);
|
|
356
|
+
ctx.recordDiagnostic('mapped', { generation }, record.id);
|
|
357
|
+
}
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
await map();
|
|
361
|
+
await map();
|
|
362
|
+
const [before] = await ctx.getAllPosts();
|
|
363
|
+
assert.equal(before.data.slug, 'mapped-2');
|
|
364
|
+
assert.equal(ctx.findLink('/old'), '/mapped-2');
|
|
365
|
+
assert.equal(ctx.getMigrationReport().summary.mapped, 1);
|
|
366
|
+
assert.equal(ctx.getMigrationReport().summary['source:kept'], 1);
|
|
367
|
+
await assert.rejects(ctx.rebuildMappedContent(async () => {
|
|
368
|
+
post(ctx, 'bad');
|
|
369
|
+
throw new Error('mapper bug');
|
|
370
|
+
}), /mapper bug/);
|
|
371
|
+
assert.equal((await ctx.getAllPosts())[0].ghostId, before.ghostId);
|
|
372
|
+
await ctx.transaction(async () => {
|
|
373
|
+
await assert.rejects(ctx.rebuildMappedContent(() => {
|
|
374
|
+
post(ctx, 'nested-bad');
|
|
375
|
+
throw new Error('nested failure');
|
|
376
|
+
}), /nested failure/);
|
|
377
|
+
assert.equal((await ctx.getAllPosts())[0].ghostId, before.ghostId);
|
|
378
|
+
});
|
|
379
|
+
await ctx.rebuildMappedContent(async () => {
|
|
380
|
+
await assert.rejects(ctx.savepoint(async () => {
|
|
381
|
+
post(ctx, 'invalid');
|
|
382
|
+
throw new Error('known data');
|
|
383
|
+
}), /known data/);
|
|
384
|
+
assert.equal(await ctx.savepoint(() => 42), 42);
|
|
385
|
+
post(ctx, 'valid');
|
|
386
|
+
});
|
|
387
|
+
assert.deepEqual((await ctx.getAllPosts()).map(value => value.data.slug), ['valid']);
|
|
388
|
+
assert.equal(await ctx.savepoint(() => 'outside'), 'outside');
|
|
389
|
+
ctx.resetMappedContent();
|
|
390
|
+
assert.equal(ctx.hasContent(), false);
|
|
391
|
+
assert.equal(ctx.sources.count(), 1);
|
|
392
|
+
assert.equal(ctx.getMigrationReport().summary['source:kept'], 1);
|
|
393
|
+
ctx.reset();
|
|
394
|
+
assert.equal(ctx.sources.hasCompletedIngestion, false);
|
|
395
|
+
assert.deepEqual(ctx.getMigrationReport().events, []);
|
|
396
|
+
});
|
|
397
|
+
it('rejects old and experimental layouts without modifying their data', async (t) => {
|
|
398
|
+
const directory = await mkdtemp(join(tmpdir(), 'mg-schema-'));
|
|
399
|
+
t.after(() => rm(directory, { recursive: true, force: true }));
|
|
400
|
+
for (const version of [2, 3, 4, 5]) {
|
|
401
|
+
const path = join(directory, `${version}.sqlite`);
|
|
402
|
+
const db = new DatabaseSync(path);
|
|
403
|
+
db.exec(`CREATE TABLE Posts(id INTEGER PRIMARY KEY, source_content TEXT); PRAGMA user_version = ${version}; INSERT INTO Posts VALUES(1, 'retained');`);
|
|
404
|
+
db.close();
|
|
405
|
+
const ctx = new MigrateContext({ dbPath: path });
|
|
406
|
+
await assert.rejects(ctx.init(), /rebuild the database/);
|
|
407
|
+
const verify = new DatabaseSync(path);
|
|
408
|
+
assert.equal(verify.prepare('SELECT source_content FROM Posts').get().source_content, 'retained');
|
|
409
|
+
verify.close();
|
|
410
|
+
}
|
|
411
|
+
});
|
|
412
|
+
it('rejects incomplete version-five layouts before creating any persistent objects', async (t) => {
|
|
413
|
+
const directory = await mkdtemp(join(tmpdir(), 'mg-incomplete-schema-'));
|
|
414
|
+
t.after(() => rm(directory, { recursive: true, force: true }));
|
|
415
|
+
for (const version of [0, 5]) {
|
|
416
|
+
const path = join(directory, `${version}.sqlite`);
|
|
417
|
+
const db = new DatabaseSync(path);
|
|
418
|
+
db.exec(`CREATE TABLE SourceRecords(id INTEGER PRIMARY KEY, content TEXT);
|
|
419
|
+
INSERT INTO SourceRecords VALUES(1, 'retained'); PRAGMA user_version = ${version};`);
|
|
420
|
+
const before = db.prepare('SELECT type, name, sql FROM sqlite_master ORDER BY name').all();
|
|
421
|
+
db.close();
|
|
422
|
+
const ctx = new MigrateContext({ dbPath: path });
|
|
423
|
+
await assert.rejects(ctx.init(), /rebuild the database/);
|
|
424
|
+
const verified = new DatabaseSync(path);
|
|
425
|
+
assert.deepEqual(verified.prepare('SELECT type, name, sql FROM sqlite_master ORDER BY name').all(), before);
|
|
426
|
+
assert.equal(verified.prepare('SELECT content FROM SourceRecords').get().content, 'retained');
|
|
427
|
+
verified.close();
|
|
428
|
+
}
|
|
429
|
+
});
|
|
430
|
+
it('rejects missing or altered constraints, indexes, and triggers without changing rows or layout', async (t) => {
|
|
431
|
+
const directory = await mkdtemp(join(tmpdir(), 'mg-constraint-schema-'));
|
|
432
|
+
t.after(() => rm(directory, { recursive: true, force: true }));
|
|
433
|
+
const changes = [
|
|
434
|
+
'DROP TABLE SourceEntityLinks; CREATE TABLE SourceEntityLinks(source_record_id INTEGER, entity_type TEXT, entity_id INTEGER);',
|
|
435
|
+
'DROP INDEX idx_source_active; CREATE INDEX idx_source_active ON SourceIngestions(status);',
|
|
436
|
+
'DROP INDEX idx_source_key;',
|
|
437
|
+
'DROP TRIGGER source_post_deleted;',
|
|
438
|
+
'ALTER TABLE SourceRecords ADD COLUMN aliases TEXT;'
|
|
439
|
+
];
|
|
440
|
+
for (const [index, change] of changes.entries()) {
|
|
441
|
+
const path = join(directory, `${index}.sqlite`);
|
|
442
|
+
const ctx = new MigrateContext({ dbPath: path });
|
|
443
|
+
await ctx.init();
|
|
444
|
+
await ctx.sources.ingest({}, stage => {
|
|
445
|
+
stage.put(raw('retained'));
|
|
446
|
+
});
|
|
447
|
+
await ctx.close();
|
|
448
|
+
const db = new DatabaseSync(path);
|
|
449
|
+
db.exec(change);
|
|
450
|
+
const before = db.prepare('SELECT type, name, sql FROM sqlite_master ORDER BY name').all();
|
|
451
|
+
const original = db.prepare('SELECT * FROM SourceRecords').all();
|
|
452
|
+
db.close();
|
|
453
|
+
await assert.rejects(ctx.init(), /Incompatible experimental database layout; rebuild/);
|
|
454
|
+
const verified = new DatabaseSync(path);
|
|
455
|
+
assert.deepEqual(verified.prepare('SELECT type, name, sql FROM sqlite_master ORDER BY name').all(), before);
|
|
456
|
+
assert.deepEqual(verified.prepare('SELECT * FROM SourceRecords').all(), original);
|
|
457
|
+
verified.close();
|
|
458
|
+
}
|
|
459
|
+
});
|
|
460
|
+
it('supports explicit reset-on-open without requiring a source identity', async (t) => {
|
|
461
|
+
const ctx = await context(t, true);
|
|
462
|
+
await ctx.sources.ingest({}, stage => {
|
|
463
|
+
stage.put(raw('old'));
|
|
464
|
+
});
|
|
465
|
+
post(ctx);
|
|
466
|
+
const path = ctx.databasePath;
|
|
467
|
+
await ctx.close();
|
|
468
|
+
const reset = new MigrateContext({ dbPath: path, resetContent: true });
|
|
469
|
+
await reset.init();
|
|
470
|
+
assert.equal(reset.sources.hasCompletedIngestion, false);
|
|
471
|
+
assert.equal(reset.hasContent(), false);
|
|
472
|
+
assert.throws(() => reset.reset({}), /no longer accepts options/);
|
|
473
|
+
await reset.close();
|
|
474
|
+
});
|
|
475
|
+
it('rejects invalid filtered iteration limits and detects source replacement during iteration', async (t) => {
|
|
476
|
+
const ctx = await context(t);
|
|
477
|
+
await assert.rejects(collect(ctx.streamPosts({ batchSize: 0, filter: { tag: { slug: 'tag' } } })), /positive/);
|
|
478
|
+
await ctx.sources.ingest({}, stage => {
|
|
479
|
+
stage.put(raw('1'));
|
|
480
|
+
stage.put(raw('2'));
|
|
481
|
+
});
|
|
482
|
+
const iterator = ctx.sources.records({ batchSize: 1 });
|
|
483
|
+
await iterator.next();
|
|
484
|
+
await ctx.sources.ingest({ replace: true }, stage => {
|
|
485
|
+
stage.put(raw('3'));
|
|
486
|
+
});
|
|
487
|
+
await assert.rejects(iterator.next(), /changed during iteration/);
|
|
488
|
+
});
|
|
489
|
+
it('invalidates handles when storage fails while discarding a failed attempt', async (t) => {
|
|
490
|
+
const ctx = await context(t);
|
|
491
|
+
let handle;
|
|
492
|
+
ctx.db.db.exec("CREATE TRIGGER fail_discard BEFORE DELETE ON SourceRecords BEGIN SELECT RAISE(ABORT, 'discard failed'); END;");
|
|
493
|
+
await assert.rejects(ctx.sources.ingest({}, stage => {
|
|
494
|
+
handle = stage;
|
|
495
|
+
stage.put(raw('partial'));
|
|
496
|
+
throw new Error('input failed');
|
|
497
|
+
}), /discard failed/);
|
|
498
|
+
assert.throws(() => handle.put(raw('closed')), /closed/);
|
|
499
|
+
ctx.db.db.exec('DROP TRIGGER fail_discard;');
|
|
500
|
+
await ctx.sources.ingest({}, () => { });
|
|
501
|
+
assert.equal(ctx.sources.count(), 0);
|
|
502
|
+
});
|
|
503
|
+
it('invalidates buffered iterators after completion or replacement', async (t) => {
|
|
504
|
+
const ctx = await context(t);
|
|
505
|
+
let iterator;
|
|
506
|
+
await ctx.sources.ingest({}, async (stage) => {
|
|
507
|
+
stage.put(raw('1'));
|
|
508
|
+
stage.put(raw('2'));
|
|
509
|
+
iterator = stage.records();
|
|
510
|
+
await iterator.next();
|
|
511
|
+
});
|
|
512
|
+
await assert.rejects(iterator.next(), /closed/);
|
|
513
|
+
const completed = ctx.sources.records();
|
|
514
|
+
await completed.next();
|
|
515
|
+
await ctx.sources.ingest({ replace: true }, () => { });
|
|
516
|
+
await assert.rejects(completed.next(), /changed during iteration/);
|
|
517
|
+
});
|
|
518
|
+
it('invalidates buffered provenance iterators after replacement or closure', async (t) => {
|
|
519
|
+
for (const close of [false, true]) {
|
|
520
|
+
const ctx = await context(t);
|
|
521
|
+
await ctx.sources.ingest({}, stage => {
|
|
522
|
+
stage.put(raw('1'));
|
|
523
|
+
stage.put(raw('2'));
|
|
524
|
+
});
|
|
525
|
+
const first = ctx.sources.get('post', '1');
|
|
526
|
+
const second = ctx.sources.get('post', '2');
|
|
527
|
+
const mapped = { type: 'post', id: post(ctx).dbId };
|
|
528
|
+
const other = { type: 'post', id: post(ctx, 'other').dbId };
|
|
529
|
+
ctx.sources.link(first.id, mapped);
|
|
530
|
+
ctx.sources.link(first.id, other);
|
|
531
|
+
ctx.sources.link(second.id, mapped);
|
|
532
|
+
const records = ctx.sources.recordsFor(mapped);
|
|
533
|
+
const entities = ctx.sources.entitiesFor(first.id);
|
|
534
|
+
await records.next();
|
|
535
|
+
await entities.next();
|
|
536
|
+
if (close) {
|
|
537
|
+
await ctx.close();
|
|
538
|
+
}
|
|
539
|
+
else {
|
|
540
|
+
await ctx.sources.ingest({ replace: true }, () => { });
|
|
541
|
+
}
|
|
542
|
+
const expected = close ? /closed/ : /changed during iteration/;
|
|
543
|
+
await assert.rejects(records.next(), expected);
|
|
544
|
+
await assert.rejects(entities.next(), expected);
|
|
545
|
+
}
|
|
546
|
+
});
|
|
547
|
+
it('blocks mapped writes through public APIs while replacement ingestion is running', async (t) => {
|
|
548
|
+
const ctx = await context(t);
|
|
549
|
+
await ctx.sources.ingest({}, stage => {
|
|
550
|
+
stage.put(raw('old'));
|
|
551
|
+
});
|
|
552
|
+
const mapped = post(ctx);
|
|
553
|
+
const source = ctx.sources.get('post', 'old');
|
|
554
|
+
const entity = { type: 'post', id: mapped.dbId };
|
|
555
|
+
ctx.sources.link(source.id, entity);
|
|
556
|
+
await assert.rejects(ctx.sources.ingest({ replace: true }, async (stage) => {
|
|
557
|
+
stage.put(raw('new'));
|
|
558
|
+
mapped.set('title', 'Must not persist');
|
|
559
|
+
for (const write of [
|
|
560
|
+
() => mapped.save(ctx.db),
|
|
561
|
+
() => new TagContext({ name: 'Bad', slug: 'bad' }).save(ctx.db),
|
|
562
|
+
() => new AuthorContext({ name: 'Bad', slug: 'bad', email: 'b@example.com' }).save(ctx.db),
|
|
563
|
+
() => ctx.updatePostData(mapped.dbId, { title: 'bad' }),
|
|
564
|
+
() => ctx.addLink('/old', '/bad'),
|
|
565
|
+
() => ctx.sources.link(source.id, entity),
|
|
566
|
+
() => ctx.sources.unlink(source.id, entity),
|
|
567
|
+
() => ctx.recordDiagnostic('mapping:bad')
|
|
568
|
+
]) {
|
|
569
|
+
assert.throws(write, /cannot overlap/);
|
|
570
|
+
}
|
|
571
|
+
await assert.rejects(ctx.prepareForExport(), /cannot overlap/);
|
|
572
|
+
throw new Error('input failed');
|
|
573
|
+
}), /input failed/);
|
|
574
|
+
assert.equal((await ctx.getAllPosts())[0].data.title, 'post');
|
|
575
|
+
assert.equal(ctx.findLink('/old'), null);
|
|
576
|
+
assert.equal((await collect(ctx.sources.entitiesFor(source.id))).length, 1);
|
|
577
|
+
});
|
|
578
|
+
it('always closes SQLite and invalidates source handles when close cleanup fails', async (t) => {
|
|
579
|
+
const ctx = await context(t, true);
|
|
580
|
+
const sources = ctx.sources;
|
|
581
|
+
let handle;
|
|
582
|
+
await assert.rejects(sources.ingest({}, async (stage) => {
|
|
583
|
+
handle = stage;
|
|
584
|
+
stage.put(raw('partial'));
|
|
585
|
+
ctx.db.db.exec("CREATE TRIGGER fail_close BEFORE DELETE ON SourceRecords BEGIN SELECT RAISE(ABORT, 'close cleanup failed'); END;");
|
|
586
|
+
await ctx.close();
|
|
587
|
+
}), /close cleanup failed/);
|
|
588
|
+
assert.throws(() => ctx.db, /not initialized/);
|
|
589
|
+
assert.throws(() => handle.put(raw('late')), /closed/);
|
|
590
|
+
await ctx.close();
|
|
591
|
+
await ctx.init();
|
|
592
|
+
ctx.db.db.exec('DROP TRIGGER fail_close;');
|
|
593
|
+
assert.throws(() => sources.count(), /closed/);
|
|
594
|
+
await assert.rejects(sources.ingest({}, () => { }), /closed/);
|
|
595
|
+
await ctx.sources.ingest({}, () => { });
|
|
596
|
+
assert.equal(ctx.sources.hasCompletedIngestion, true);
|
|
597
|
+
});
|
|
598
|
+
it('closes a newly opened database if schema initialization fails', async (t) => {
|
|
599
|
+
const execute = DatabaseSync.prototype.exec;
|
|
600
|
+
const close = DatabaseSync.prototype.close;
|
|
601
|
+
let closures = 0;
|
|
602
|
+
t.mock.method(DatabaseSync.prototype, 'exec', function (sql) {
|
|
603
|
+
if (sql.includes('CREATE TABLE IF NOT EXISTS Posts')) {
|
|
604
|
+
throw new Error('storage initialization failed');
|
|
605
|
+
}
|
|
606
|
+
return execute.call(this, sql);
|
|
607
|
+
});
|
|
608
|
+
t.mock.method(DatabaseSync.prototype, 'close', function () {
|
|
609
|
+
closures += 1;
|
|
610
|
+
return close.call(this);
|
|
611
|
+
});
|
|
612
|
+
const ctx = new MigrateContext();
|
|
613
|
+
await assert.rejects(ctx.init(), /storage initialization failed/);
|
|
614
|
+
assert.equal(closures, 1);
|
|
615
|
+
assert.throws(() => ctx.db, /not initialized/);
|
|
616
|
+
await ctx.close();
|
|
617
|
+
});
|
|
618
|
+
it('rejects altered version-five layouts as well as earlier experimental schemas', async (t) => {
|
|
619
|
+
const ctx = await context(t, true);
|
|
620
|
+
ctx.db.db.exec('ALTER TABLE Posts ADD COLUMN source_content TEXT;');
|
|
621
|
+
await ctx.close();
|
|
622
|
+
await assert.rejects(ctx.init(), /Incompatible experimental/);
|
|
623
|
+
});
|
|
624
|
+
});
|
|
625
|
+
//# sourceMappingURL=source-records.test.js.map
|