@bastani/atomic 0.9.82 → 0.9.83
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 +20 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +2 -16
- package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +2 -16
- package/dist/builtin/workflows/src/index.js +2 -16
- package/dist/builtin/workflows/src/local-worker-entry.mjs +2 -16
- package/dist/cli/storage-command.d.ts +11 -1
- package/dist/cli/storage-command.d.ts.map +1 -1
- package/dist/cli/storage-command.js +102 -4
- package/dist/cli/storage-command.js.map +1 -1
- package/dist/core/storage/journal-adoption.d.ts +48 -0
- package/dist/core/storage/journal-adoption.d.ts.map +1 -1
- package/dist/core/storage/journal-adoption.js +41 -1
- package/dist/core/storage/journal-adoption.js.map +1 -1
- package/dist/core/storage/journal-transfer.d.ts +126 -0
- package/dist/core/storage/journal-transfer.d.ts.map +1 -0
- package/dist/core/storage/journal-transfer.js +690 -0
- package/dist/core/storage/journal-transfer.js.map +1 -0
- package/docs/reference/cli.md +4 -0
- package/docs/storage.md +54 -0
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
|
@@ -0,0 +1,690 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Workflow runs as versioned JSONL files (#4716): `exportWorkflowRuns` writes each run of a local workflow journal to
|
|
3
|
+
* `<dir>/<runId>.jsonl`, and `importWorkflowRuns` restores such files into one. The journal stays the working store;
|
|
4
|
+
* the files are the form runs take at rest, so a host that persists only files can carry them between machines.
|
|
5
|
+
*
|
|
6
|
+
* Line 1 of a file is the run's header: the row of the journal's runs table. Every later line is one row of its
|
|
7
|
+
* events table, in sequence order, with its payload as a JSON value instead of JSON text. Leases, local-worker pool
|
|
8
|
+
* state and worktree snapshot blobs are not exported: they belong to the machine that wrote them.
|
|
9
|
+
*/
|
|
10
|
+
import { randomUUID } from "node:crypto";
|
|
11
|
+
import { existsSync } from "node:fs";
|
|
12
|
+
import { mkdir, open, readdir, readFile, rename, rm } from "node:fs/promises";
|
|
13
|
+
import { join, resolve } from "node:path";
|
|
14
|
+
import { closeEach, withCleanup } from "./cleanup.js";
|
|
15
|
+
import { StorageError } from "./errors.js";
|
|
16
|
+
import { discoverLegacyJournal, ensureRunJournalSchema, legacyDefaultJournalPath, runJournalTables, } from "./journal-adoption.js";
|
|
17
|
+
import { isFinishedJournalStatus, JOURNAL_CATALOG_FILE, JournalCatalog, } from "./journal-catalog.js";
|
|
18
|
+
import { openNodeSqliteDatabase } from "./node-sqlite.js";
|
|
19
|
+
import { RUN_EVENT_TYPES, RUN_JOURNAL_SCHEMA_VERSION } from "./run-journal.js";
|
|
20
|
+
/** The `type` of an export file's header line. */
|
|
21
|
+
export const WORKFLOW_RUN_EXPORT_TYPE = "atomic.workflow-run";
|
|
22
|
+
/** The export format version this Atomic writes and reads. */
|
|
23
|
+
export const WORKFLOW_RUN_EXPORT_VERSION = 1;
|
|
24
|
+
/** The file name extension of an exported run; import reads every file with it and ignores the rest. */
|
|
25
|
+
export const WORKFLOW_RUN_EXPORT_EXTENSION = ".jsonl";
|
|
26
|
+
/**
|
|
27
|
+
* A lease renewed this recently belongs to a process that may still be running the run on this machine, so an import
|
|
28
|
+
* does not add events to that run. It matches the window in which the workflows runtime treats a running run's owner
|
|
29
|
+
* as live.
|
|
30
|
+
*/
|
|
31
|
+
export const WORKFLOW_RUN_IMPORT_LIVE_LEASE_MS = 120_000;
|
|
32
|
+
/** An export or import that could not be done; an import that fails this way changed nothing. */
|
|
33
|
+
export class WorkflowRunTransferError extends StorageError {
|
|
34
|
+
name = "WorkflowRunTransferError";
|
|
35
|
+
path;
|
|
36
|
+
line;
|
|
37
|
+
runId;
|
|
38
|
+
reason;
|
|
39
|
+
constructor(init) {
|
|
40
|
+
super(`${init.path}${init.line === undefined ? "" : `:${init.line}`}: ${init.reason}`, { cause: init.cause });
|
|
41
|
+
this.path = init.path;
|
|
42
|
+
this.line = init.line;
|
|
43
|
+
this.runId = init.runId;
|
|
44
|
+
this.reason = init.reason;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export function isWorkflowRunTransferError(value) {
|
|
48
|
+
if (value instanceof WorkflowRunTransferError)
|
|
49
|
+
return true;
|
|
50
|
+
return (typeof value === "object" && value !== null && value.name === "WorkflowRunTransferError");
|
|
51
|
+
}
|
|
52
|
+
const STORE_NOW = "CAST(unixepoch('subsec') * 1000 AS INTEGER)";
|
|
53
|
+
const TRANSFER_TRANSACTION = { lockWaitMs: 10 * 60_000 };
|
|
54
|
+
const EVENT_TYPES = new Set(Object.values(RUN_EVENT_TYPES));
|
|
55
|
+
const HEADER_FIELDS = ["type", "version", "runId", "name", "cwd", "createdAt", "status", "events", "header"];
|
|
56
|
+
const EVENT_FIELDS = ["type", "seq", "epoch", "key", "at", "payload"];
|
|
57
|
+
/** The file an exported run is written to in `directory`. */
|
|
58
|
+
export function workflowRunExportFile(directory, runId) {
|
|
59
|
+
return join(directory, `${encodeURIComponent(runId)}${WORKFLOW_RUN_EXPORT_EXTENSION}`);
|
|
60
|
+
}
|
|
61
|
+
function storageLocation(storage) {
|
|
62
|
+
return storage.kind === "store" ? storage.directory : storage.path;
|
|
63
|
+
}
|
|
64
|
+
function parseStored(text, path, runId, what) {
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(text);
|
|
67
|
+
}
|
|
68
|
+
catch (cause) {
|
|
69
|
+
throw new WorkflowRunTransferError({
|
|
70
|
+
path,
|
|
71
|
+
runId,
|
|
72
|
+
reason: `run ${runId} has ${what} that is not valid JSON`,
|
|
73
|
+
cause: cause,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** A run and its events as the lines of its export file, newline-terminated. */
|
|
78
|
+
function exportText(run, events, path) {
|
|
79
|
+
const header = parseStored(run.header_json, path, run.run_id, "a header");
|
|
80
|
+
if (!isObject(header))
|
|
81
|
+
throw new WorkflowRunTransferError({
|
|
82
|
+
path,
|
|
83
|
+
runId: run.run_id,
|
|
84
|
+
reason: `run ${run.run_id} has a header that is not an object`,
|
|
85
|
+
});
|
|
86
|
+
const lines = [
|
|
87
|
+
JSON.stringify({
|
|
88
|
+
type: WORKFLOW_RUN_EXPORT_TYPE,
|
|
89
|
+
version: WORKFLOW_RUN_EXPORT_VERSION,
|
|
90
|
+
runId: run.run_id,
|
|
91
|
+
name: run.name,
|
|
92
|
+
cwd: run.cwd,
|
|
93
|
+
createdAt: Number(run.created_at),
|
|
94
|
+
status: run.status,
|
|
95
|
+
events: events.length,
|
|
96
|
+
header,
|
|
97
|
+
}),
|
|
98
|
+
];
|
|
99
|
+
for (const event of events)
|
|
100
|
+
lines.push(JSON.stringify({
|
|
101
|
+
type: event.type,
|
|
102
|
+
seq: Number(event.seq),
|
|
103
|
+
epoch: Number(event.epoch),
|
|
104
|
+
key: event.key,
|
|
105
|
+
at: Number(event.at),
|
|
106
|
+
payload: parseStored(event.payload, path, run.run_id, `event ${event.seq} with a payload`),
|
|
107
|
+
}));
|
|
108
|
+
return `${lines.join("\n")}\n`;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Writes `content` to `file` through a temporary file in the same directory that is flushed and then renamed over it,
|
|
112
|
+
* so `file` holds either its earlier content or all of `content`. A file that already holds `content` is left alone.
|
|
113
|
+
*/
|
|
114
|
+
async function writeAtomically(file, content) {
|
|
115
|
+
const existing = await readFile(file, "utf8").catch(() => undefined);
|
|
116
|
+
if (existing === content)
|
|
117
|
+
return "unchanged";
|
|
118
|
+
const temporary = join(resolve(file, ".."), `.${randomUUID()}.tmp`);
|
|
119
|
+
try {
|
|
120
|
+
const handle = await open(temporary, "wx");
|
|
121
|
+
await withCleanup(async () => {
|
|
122
|
+
await handle.writeFile(content, "utf8");
|
|
123
|
+
await handle.sync();
|
|
124
|
+
}, () => handle.close());
|
|
125
|
+
await rename(temporary, file);
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
await rm(temporary, { force: true }).catch(() => undefined);
|
|
129
|
+
throw new WorkflowRunTransferError({
|
|
130
|
+
path: file,
|
|
131
|
+
reason: `cannot write the export file: ${error.message}`,
|
|
132
|
+
cause: error,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
return "written";
|
|
136
|
+
}
|
|
137
|
+
async function hasTables(executor, t) {
|
|
138
|
+
const rows = await executor.all("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (?, ?, ?)", t.meta, t.runs, t.events);
|
|
139
|
+
return rows.length === 3;
|
|
140
|
+
}
|
|
141
|
+
async function schemaVersion(executor, t) {
|
|
142
|
+
const rows = await executor.all(`SELECT schema_version FROM ${t.meta}`);
|
|
143
|
+
return rows.length === 1 ? rows[0].schema_version : undefined;
|
|
144
|
+
}
|
|
145
|
+
/** Opens a journal file for an export and begins its read transaction; undefined, with the reason, when it cannot. */
|
|
146
|
+
async function openExportSource(path, t, shardId) {
|
|
147
|
+
if (!existsSync(path))
|
|
148
|
+
return { path, reason: "the journal file no longer exists" };
|
|
149
|
+
let database;
|
|
150
|
+
try {
|
|
151
|
+
database = await openNodeSqliteDatabase(path, { readOnly: true });
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
return { path, reason: `the journal file cannot be opened: ${error.message}` };
|
|
155
|
+
}
|
|
156
|
+
try {
|
|
157
|
+
await database.exec("BEGIN");
|
|
158
|
+
if (!(await hasTables(database, t))) {
|
|
159
|
+
await database.exec("COMMIT");
|
|
160
|
+
await database.close();
|
|
161
|
+
return { path, reason: "it has no workflow runs in the current journal format" };
|
|
162
|
+
}
|
|
163
|
+
const version = await schemaVersion(database, t);
|
|
164
|
+
if (version !== RUN_JOURNAL_SCHEMA_VERSION) {
|
|
165
|
+
await database.exec("COMMIT");
|
|
166
|
+
await database.close();
|
|
167
|
+
return { path, reason: `unsupported journal schema version ${String(version)}` };
|
|
168
|
+
}
|
|
169
|
+
const runs = await database.all(`SELECT * FROM ${t.runs} ORDER BY run_id`);
|
|
170
|
+
return { path, database, runs, ...(shardId === undefined ? {} : { shardId }) };
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
await database.close().catch(() => undefined);
|
|
174
|
+
return { path, reason: `the journal file cannot be read: ${error.message}` };
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Adopts the default journal of Atomic before the journal store, as opening the store does, so its runs are exported
|
|
179
|
+
* and compared like every other run; whether the store has a catalog.
|
|
180
|
+
*/
|
|
181
|
+
async function adoptLegacyJournal(directory) {
|
|
182
|
+
if (existsSync(legacyDefaultJournalPath(directory))) {
|
|
183
|
+
const catalog = await JournalCatalog.open(directory);
|
|
184
|
+
await withCleanup(async () => {
|
|
185
|
+
await discoverLegacyJournal(catalog, legacyDefaultJournalPath(directory));
|
|
186
|
+
}, () => catalog.close());
|
|
187
|
+
}
|
|
188
|
+
return existsSync(join(directory, JOURNAL_CATALOG_FILE));
|
|
189
|
+
}
|
|
190
|
+
function newestFirst(left, right) {
|
|
191
|
+
const created = Number(right.created_at) - Number(left.created_at);
|
|
192
|
+
if (created !== 0)
|
|
193
|
+
return created;
|
|
194
|
+
return left.run_id < right.run_id ? -1 : left.run_id > right.run_id ? 1 : 0;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Exports runs of a local workflow journal to `<directory>/<runId>.jsonl`, one file per run. Each journal file is read
|
|
198
|
+
* in one read transaction, and each export file is written whole or not at all. The same journal state gives the same
|
|
199
|
+
* bytes, and a file that already holds them is not rewritten.
|
|
200
|
+
*/
|
|
201
|
+
export async function exportWorkflowRuns(storage, directory, options = {}) {
|
|
202
|
+
const t = runJournalTables(storage.kind === "sqlite" ? storage.prefix : undefined);
|
|
203
|
+
const skipped = [];
|
|
204
|
+
const sources = [];
|
|
205
|
+
let owners;
|
|
206
|
+
let catalogued = [];
|
|
207
|
+
const add = (opened) => {
|
|
208
|
+
if ("database" in opened)
|
|
209
|
+
sources.push(opened);
|
|
210
|
+
else
|
|
211
|
+
skipped.push(opened);
|
|
212
|
+
};
|
|
213
|
+
return withCleanup(async () => {
|
|
214
|
+
if (storage.kind === "sqlite") {
|
|
215
|
+
if (existsSync(storage.path))
|
|
216
|
+
add(await openExportSource(storage.path, t, undefined));
|
|
217
|
+
}
|
|
218
|
+
else if (await adoptLegacyJournal(storage.directory)) {
|
|
219
|
+
const catalog = await JournalCatalog.open(storage.directory);
|
|
220
|
+
let shards;
|
|
221
|
+
await withCleanup(async () => {
|
|
222
|
+
shards = await catalog.shards();
|
|
223
|
+
catalogued = await catalog.runs();
|
|
224
|
+
owners = new Map(catalogued.map((run) => [run.runId, run.shard]));
|
|
225
|
+
}, () => catalog.close());
|
|
226
|
+
for (const shard of shards)
|
|
227
|
+
add(await openExportSource(shard.path, t, shard.id));
|
|
228
|
+
}
|
|
229
|
+
const listed = new Map();
|
|
230
|
+
for (const source of sources)
|
|
231
|
+
for (const run of source.runs) {
|
|
232
|
+
const owner = owners?.get(run.run_id);
|
|
233
|
+
if (owner === undefined ? listed.has(run.run_id) : owner !== source.shardId)
|
|
234
|
+
continue;
|
|
235
|
+
listed.set(run.run_id, { source, run });
|
|
236
|
+
}
|
|
237
|
+
// A consolidation that moved a run between reading the catalog and opening the journal files leaves it only in
|
|
238
|
+
// a file the catalog did not name then: that copy is the run. A run whose named file could not be read is not
|
|
239
|
+
// taken from another file, which may hold an older copy an interrupted consolidation left behind.
|
|
240
|
+
const readable = new Set(sources.map((source) => source.shardId));
|
|
241
|
+
for (const source of sources)
|
|
242
|
+
for (const run of source.runs) {
|
|
243
|
+
const owner = owners?.get(run.run_id);
|
|
244
|
+
if (listed.has(run.run_id) || (owner !== undefined && !readable.has(owner)))
|
|
245
|
+
continue;
|
|
246
|
+
listed.set(run.run_id, { source, run });
|
|
247
|
+
}
|
|
248
|
+
// A run whose journal file was read but does not hold it in the current tables is in the pre-0.9.38 format;
|
|
249
|
+
// the runs of a journal file that could not be read are covered by that file's own entry, and a root that is
|
|
250
|
+
// only reserved (no status yet) has nothing to export.
|
|
251
|
+
if (options.runs === undefined)
|
|
252
|
+
for (const entry of catalogued) {
|
|
253
|
+
const source = sources.find((candidate) => candidate.shardId === entry.shard);
|
|
254
|
+
if (!listed.has(entry.runId) && source !== undefined && entry.status !== undefined)
|
|
255
|
+
skipped.push({
|
|
256
|
+
path: source.path,
|
|
257
|
+
runId: entry.runId,
|
|
258
|
+
reason: "it is in the journal format of Atomic before 0.9.38; resume it once to convert it",
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
let selected = [...listed.values()];
|
|
262
|
+
if (options.runs !== undefined) {
|
|
263
|
+
const missing = options.runs.find((runId) => !listed.has(runId));
|
|
264
|
+
if (missing !== undefined)
|
|
265
|
+
throw new WorkflowRunTransferError({
|
|
266
|
+
path: storageLocation(storage),
|
|
267
|
+
runId: missing,
|
|
268
|
+
reason: `run ${missing} is not in this workflow journal`,
|
|
269
|
+
});
|
|
270
|
+
selected = [...new Set(options.runs)].map((runId) => listed.get(runId));
|
|
271
|
+
}
|
|
272
|
+
if (options.unfinished)
|
|
273
|
+
selected = selected.filter(({ run }) => !isFinishedJournalStatus(run.status));
|
|
274
|
+
selected.sort((left, right) => newestFirst(left.run, right.run));
|
|
275
|
+
if (options.limit !== undefined)
|
|
276
|
+
selected = selected.slice(0, options.limit);
|
|
277
|
+
await mkdir(directory, { recursive: true });
|
|
278
|
+
const written = [];
|
|
279
|
+
const unchanged = [];
|
|
280
|
+
for (const { source, run } of selected) {
|
|
281
|
+
const events = await source.database.all(`SELECT * FROM ${t.events} WHERE run_id = ? ORDER BY seq`, run.run_id);
|
|
282
|
+
const file = workflowRunExportFile(directory, run.run_id);
|
|
283
|
+
const outcome = await writeAtomically(file, exportText(run, events, source.path));
|
|
284
|
+
(outcome === "written" ? written : unchanged).push(run.run_id);
|
|
285
|
+
}
|
|
286
|
+
return { written, unchanged, skipped };
|
|
287
|
+
}, async () => {
|
|
288
|
+
await Promise.allSettled(sources.map((source) => source.database.exec("COMMIT")));
|
|
289
|
+
await closeEach(sources.map((source) => source.database));
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
function isObject(value) {
|
|
293
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
294
|
+
}
|
|
295
|
+
function invalidText(value) {
|
|
296
|
+
if (value.includes("\u0000"))
|
|
297
|
+
return "contains a NUL character";
|
|
298
|
+
if (/\p{Surrogate}/u.test(value))
|
|
299
|
+
return "is not well-formed Unicode";
|
|
300
|
+
return undefined;
|
|
301
|
+
}
|
|
302
|
+
function counter(value, minimum) {
|
|
303
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= minimum;
|
|
304
|
+
}
|
|
305
|
+
/** Checks that a line has exactly `fields`; the reason when it does not. */
|
|
306
|
+
function fieldsReason(line, fields) {
|
|
307
|
+
for (const field of fields)
|
|
308
|
+
if (!(field in line))
|
|
309
|
+
return `has no "${field}" field`;
|
|
310
|
+
for (const field of Object.keys(line))
|
|
311
|
+
if (!fields.includes(field))
|
|
312
|
+
return `has an unexpected "${field}" field`;
|
|
313
|
+
return undefined;
|
|
314
|
+
}
|
|
315
|
+
/** Reads and checks one export file, throwing a `WorkflowRunTransferError` that names the file and line. */
|
|
316
|
+
function parseExportFile(file, bytes) {
|
|
317
|
+
const fail = (line, reason, runId) => {
|
|
318
|
+
throw new WorkflowRunTransferError({ path: file, ...(line === undefined ? {} : { line }), runId, reason });
|
|
319
|
+
};
|
|
320
|
+
let text;
|
|
321
|
+
try {
|
|
322
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
323
|
+
}
|
|
324
|
+
catch {
|
|
325
|
+
return fail(undefined, "is not valid UTF-8 text");
|
|
326
|
+
}
|
|
327
|
+
const lines = text.split("\n");
|
|
328
|
+
if (lines.at(-1) === "")
|
|
329
|
+
lines.pop();
|
|
330
|
+
if (lines.length === 0)
|
|
331
|
+
return fail(1, "is empty; expected a workflow run header");
|
|
332
|
+
const parse = (index) => {
|
|
333
|
+
const line = lines[index];
|
|
334
|
+
if (line.trim() === "")
|
|
335
|
+
return fail(index + 1, "is empty");
|
|
336
|
+
let value;
|
|
337
|
+
try {
|
|
338
|
+
value = JSON.parse(line);
|
|
339
|
+
}
|
|
340
|
+
catch (error) {
|
|
341
|
+
return fail(index + 1, `is not valid JSON (${error.message})`);
|
|
342
|
+
}
|
|
343
|
+
if (!isObject(value))
|
|
344
|
+
return fail(index + 1, "is not a JSON object");
|
|
345
|
+
if (typeof value.type !== "string")
|
|
346
|
+
return fail(index + 1, 'has no string "type"');
|
|
347
|
+
return value;
|
|
348
|
+
};
|
|
349
|
+
const first = parse(0);
|
|
350
|
+
if (first.type !== WORKFLOW_RUN_EXPORT_TYPE)
|
|
351
|
+
fail(1, `is not an Atomic workflow run export: its type is "${first.type}", not "${WORKFLOW_RUN_EXPORT_TYPE}"`);
|
|
352
|
+
if (first.version !== WORKFLOW_RUN_EXPORT_VERSION)
|
|
353
|
+
fail(1, `has unsupported export version ${JSON.stringify(first.version ?? null)}; this Atomic reads version ${WORKFLOW_RUN_EXPORT_VERSION}`);
|
|
354
|
+
const headerFields = fieldsReason(first, HEADER_FIELDS);
|
|
355
|
+
if (headerFields !== undefined)
|
|
356
|
+
fail(1, headerFields);
|
|
357
|
+
for (const field of ["runId", "name", "cwd", "status"]) {
|
|
358
|
+
const value = first[field];
|
|
359
|
+
if (typeof value !== "string")
|
|
360
|
+
fail(1, `has a "${field}" that is not a string`);
|
|
361
|
+
const reason = invalidText(value);
|
|
362
|
+
if (reason !== undefined)
|
|
363
|
+
fail(1, `has a "${field}" that ${reason}`);
|
|
364
|
+
}
|
|
365
|
+
const runId = first.runId;
|
|
366
|
+
if (runId === "")
|
|
367
|
+
fail(1, 'has an empty "runId"');
|
|
368
|
+
if (!counter(first.createdAt, Number.MIN_SAFE_INTEGER))
|
|
369
|
+
fail(1, 'has a "createdAt" that is not an integer', runId);
|
|
370
|
+
if (!counter(first.events, 0))
|
|
371
|
+
fail(1, 'has an "events" count that is not a non-negative integer', runId);
|
|
372
|
+
if (!isObject(first.header))
|
|
373
|
+
fail(1, 'has a "header" that is not an object', runId);
|
|
374
|
+
if (first.header.runId !== runId)
|
|
375
|
+
fail(1, `has a "header" whose runId is not the run's ID ${runId}`, runId);
|
|
376
|
+
const events = [];
|
|
377
|
+
const keys = new Map();
|
|
378
|
+
for (let index = 1; index < lines.length; index++) {
|
|
379
|
+
const line = index + 1;
|
|
380
|
+
const event = parse(index);
|
|
381
|
+
const reason = fieldsReason(event, EVENT_FIELDS);
|
|
382
|
+
if (reason !== undefined)
|
|
383
|
+
fail(line, reason, runId);
|
|
384
|
+
if (!EVENT_TYPES.has(event.type))
|
|
385
|
+
fail(line, `has unknown event type "${event.type}"`, runId);
|
|
386
|
+
if (event.seq !== index)
|
|
387
|
+
fail(line, `has seq ${JSON.stringify(event.seq)}; expected ${index}`, runId);
|
|
388
|
+
if (!counter(event.epoch, 0))
|
|
389
|
+
fail(line, 'has an "epoch" that is not a non-negative integer', runId);
|
|
390
|
+
if (!counter(event.at, Number.MIN_SAFE_INTEGER))
|
|
391
|
+
fail(line, 'has an "at" that is not an integer', runId);
|
|
392
|
+
const key = event.key;
|
|
393
|
+
if (key !== null) {
|
|
394
|
+
if (typeof key !== "string")
|
|
395
|
+
fail(line, 'has a "key" that is neither a string nor null', runId);
|
|
396
|
+
const keyReason = invalidText(key);
|
|
397
|
+
if (keyReason !== undefined)
|
|
398
|
+
fail(line, `has a "key" that ${keyReason}`, runId);
|
|
399
|
+
const earlier = keys.get(key);
|
|
400
|
+
if (earlier !== undefined)
|
|
401
|
+
fail(line, `repeats the key of line ${earlier}`, runId);
|
|
402
|
+
keys.set(key, line);
|
|
403
|
+
}
|
|
404
|
+
if (event.type === RUN_EVENT_TYPES.statusChanged) {
|
|
405
|
+
const status = isObject(event.payload) ? event.payload.status : undefined;
|
|
406
|
+
if (typeof status !== "string")
|
|
407
|
+
fail(line, 'is a StatusChanged event whose payload has no string "status"', runId);
|
|
408
|
+
const statusReason = invalidText(status);
|
|
409
|
+
if (statusReason !== undefined)
|
|
410
|
+
fail(line, `has a status that ${statusReason}`, runId);
|
|
411
|
+
}
|
|
412
|
+
events.push({
|
|
413
|
+
type: event.type,
|
|
414
|
+
seq: event.seq,
|
|
415
|
+
epoch: event.epoch,
|
|
416
|
+
key: key,
|
|
417
|
+
at: event.at,
|
|
418
|
+
payload: event.payload,
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
if (lines.length - 1 !== first.events)
|
|
422
|
+
fail(1, `says the run has ${first.events} events, but the file has ${lines.length - 1} event lines`, runId);
|
|
423
|
+
const header = {
|
|
424
|
+
type: WORKFLOW_RUN_EXPORT_TYPE,
|
|
425
|
+
version: WORKFLOW_RUN_EXPORT_VERSION,
|
|
426
|
+
runId,
|
|
427
|
+
name: first.name,
|
|
428
|
+
cwd: first.cwd,
|
|
429
|
+
createdAt: first.createdAt,
|
|
430
|
+
status: first.status,
|
|
431
|
+
events: first.events,
|
|
432
|
+
header: first.header,
|
|
433
|
+
};
|
|
434
|
+
return { file, header, events };
|
|
435
|
+
}
|
|
436
|
+
/** The fields import checks against a stored run: everything but string content, which a tool may redact. */
|
|
437
|
+
function sameEntry(stored, exported) {
|
|
438
|
+
return (Number(stored.seq) === exported.seq &&
|
|
439
|
+
Number(stored.epoch) === exported.epoch &&
|
|
440
|
+
stored.key === exported.key &&
|
|
441
|
+
stored.type === exported.type &&
|
|
442
|
+
Number(stored.at) === exported.at);
|
|
443
|
+
}
|
|
444
|
+
async function readStoredRun(executor, t, runId) {
|
|
445
|
+
if (!(await hasTables(executor, t)))
|
|
446
|
+
return undefined;
|
|
447
|
+
const run = await executor.get(`SELECT * FROM ${t.runs} WHERE run_id = ?`, runId);
|
|
448
|
+
if (run === undefined)
|
|
449
|
+
return undefined;
|
|
450
|
+
const events = await executor.all(`SELECT * FROM ${t.events} WHERE run_id = ? ORDER BY seq`, runId);
|
|
451
|
+
const leases = await executor.get(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`, t.leases);
|
|
452
|
+
const lease = leases === undefined
|
|
453
|
+
? undefined
|
|
454
|
+
: await executor.get(`SELECT *, MAX(0, ${STORE_NOW} - renewed_at) AS age_ms FROM ${t.leases} WHERE run_id = ?`, runId);
|
|
455
|
+
return { run, events, ...(lease === undefined ? {} : { lease }) };
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* What importing `parsed` does to the run as `stored` holds it: add it, add the file's later events, or nothing when
|
|
459
|
+
* the storage already holds every event of the file. A run whose history differs from the file's, or that a process
|
|
460
|
+
* here may still be running, fails with the file and line.
|
|
461
|
+
*/
|
|
462
|
+
function importAction(parsed, stored, location) {
|
|
463
|
+
if (stored === undefined)
|
|
464
|
+
return "add";
|
|
465
|
+
const { header, events, file } = parsed;
|
|
466
|
+
const fail = (line, reason) => {
|
|
467
|
+
throw new WorkflowRunTransferError({ path: file, line, runId: header.runId, reason });
|
|
468
|
+
};
|
|
469
|
+
if (Number(stored.run.created_at) !== header.createdAt)
|
|
470
|
+
fail(1, `run ${header.runId} in ${location} was created at another time; it is a different run with the same ID`);
|
|
471
|
+
const shared = Math.min(stored.events.length, events.length);
|
|
472
|
+
for (let index = 0; index < shared; index++)
|
|
473
|
+
if (!sameEntry(stored.events[index], events[index]))
|
|
474
|
+
fail(index + 2, `event ${index + 1} differs from event ${index + 1} of run ${header.runId} in ${location}: the run continued differently there`);
|
|
475
|
+
if (events.length <= stored.events.length)
|
|
476
|
+
return "unchanged";
|
|
477
|
+
const lease = stored.lease;
|
|
478
|
+
if (lease !== undefined && lease.holder_id !== null && Number(lease.age_ms) < WORKFLOW_RUN_IMPORT_LIVE_LEASE_MS)
|
|
479
|
+
fail(1, `run ${header.runId} is held by ${lease.holder_id} in ${location}, which may still be running it; stop it and import again`);
|
|
480
|
+
return "update";
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Writes the part of `parsed` that `stored` lacks inside the caller's transaction: the run row when it is new, the
|
|
484
|
+
* events after the stored ones, the latest status, and an unheld lease at an epoch above every epoch the run's events
|
|
485
|
+
* and any earlier holder used, so no holder from another machine is imported and a stale one here is fenced.
|
|
486
|
+
*/
|
|
487
|
+
async function applyImport(tx, t, parsed, location) {
|
|
488
|
+
const { header, events } = parsed;
|
|
489
|
+
const action = importAction(parsed, await readStoredRun(tx, t, header.runId), location);
|
|
490
|
+
if (action === "unchanged")
|
|
491
|
+
return action;
|
|
492
|
+
if (action === "add")
|
|
493
|
+
await tx.run(`INSERT INTO ${t.runs}(run_id, name, cwd, created_at, status, header_json) VALUES (?, ?, ?, ?, ?, ?)`, header.runId, header.name, header.cwd, header.createdAt, header.status, JSON.stringify(header.header));
|
|
494
|
+
else
|
|
495
|
+
await tx.run(`UPDATE ${t.runs} SET status = ? WHERE run_id = ?`, header.status, header.runId);
|
|
496
|
+
const stored = action === "add"
|
|
497
|
+
? 0
|
|
498
|
+
: Number((await tx.get(`SELECT COALESCE(MAX(seq), 0) AS seq FROM ${t.events} WHERE run_id = ?`, header.runId)).seq);
|
|
499
|
+
for (const event of events.slice(stored))
|
|
500
|
+
await tx.run(`INSERT INTO ${t.events}(run_id, seq, epoch, key, type, payload, at) VALUES (?, ?, ?, ?, ?, ?, ?)`, header.runId, event.seq, event.epoch, event.key, event.type, JSON.stringify(event.payload), event.at);
|
|
501
|
+
const epoch = events.reduce((highest, event) => Math.max(highest, event.epoch), 0);
|
|
502
|
+
await tx.run(`INSERT INTO ${t.leases}(run_id, holder_id, epoch, renewed_at) VALUES (?, NULL, ?, ${STORE_NOW})
|
|
503
|
+
ON CONFLICT(run_id) DO UPDATE SET holder_id = NULL, renewed_at = excluded.renewed_at,
|
|
504
|
+
epoch = MAX(excluded.epoch, ${t.leases}.epoch + (CASE WHEN ${t.leases}.holder_id IS NULL THEN 0 ELSE 1 END))`, header.runId, epoch);
|
|
505
|
+
return action;
|
|
506
|
+
}
|
|
507
|
+
/** Reads and checks every export file in `directory`; nothing is written. */
|
|
508
|
+
async function readExportDirectory(directory) {
|
|
509
|
+
let names;
|
|
510
|
+
try {
|
|
511
|
+
names = await readdir(directory);
|
|
512
|
+
}
|
|
513
|
+
catch (error) {
|
|
514
|
+
throw new WorkflowRunTransferError({
|
|
515
|
+
path: directory,
|
|
516
|
+
reason: `cannot read the directory: ${error.message}`,
|
|
517
|
+
cause: error,
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
const parsed = [];
|
|
521
|
+
const files = new Map();
|
|
522
|
+
for (const name of names.filter((entry) => entry.endsWith(WORKFLOW_RUN_EXPORT_EXTENSION)).sort()) {
|
|
523
|
+
const file = join(directory, name);
|
|
524
|
+
let bytes;
|
|
525
|
+
try {
|
|
526
|
+
bytes = await readFile(file);
|
|
527
|
+
}
|
|
528
|
+
catch (error) {
|
|
529
|
+
throw new WorkflowRunTransferError({
|
|
530
|
+
path: file,
|
|
531
|
+
reason: `cannot read the file: ${error.message}`,
|
|
532
|
+
cause: error,
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
const run = parseExportFile(file, bytes);
|
|
536
|
+
const earlier = files.get(run.header.runId);
|
|
537
|
+
if (earlier !== undefined)
|
|
538
|
+
throw new WorkflowRunTransferError({
|
|
539
|
+
path: file,
|
|
540
|
+
line: 1,
|
|
541
|
+
runId: run.header.runId,
|
|
542
|
+
reason: `run ${run.header.runId} is also in ${earlier}; keep one file per run`,
|
|
543
|
+
});
|
|
544
|
+
files.set(run.header.runId, file);
|
|
545
|
+
parsed.push(run);
|
|
546
|
+
}
|
|
547
|
+
return parsed;
|
|
548
|
+
}
|
|
549
|
+
/** A journal file an import reads its runs from while it decides what to write: read-only, opened once. */
|
|
550
|
+
class ReadOnlyFiles {
|
|
551
|
+
opened = new Map();
|
|
552
|
+
read(path) {
|
|
553
|
+
let database = this.opened.get(path);
|
|
554
|
+
if (database === undefined) {
|
|
555
|
+
database = openNodeSqliteDatabase(path, { readOnly: true });
|
|
556
|
+
this.opened.set(path, database);
|
|
557
|
+
}
|
|
558
|
+
return database;
|
|
559
|
+
}
|
|
560
|
+
async close() {
|
|
561
|
+
const settled = await Promise.allSettled(this.opened.values());
|
|
562
|
+
await closeEach(settled.flatMap((result) => (result.status === "fulfilled" ? [result.value] : [])));
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
function unreadableShard(parsed, path, error) {
|
|
566
|
+
return new WorkflowRunTransferError({
|
|
567
|
+
path: parsed.file,
|
|
568
|
+
line: 1,
|
|
569
|
+
runId: parsed.header.runId,
|
|
570
|
+
reason: `run ${parsed.header.runId} is in the journal file ${path}, which cannot be read: ${error.message}`,
|
|
571
|
+
cause: error,
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
/** The journal file of a store holding `runId`: the one the catalog names, else an adopted journal that holds it. */
|
|
575
|
+
async function storedShard(catalog, files, t, runId) {
|
|
576
|
+
const found = await catalog.locate(runId);
|
|
577
|
+
if (found !== undefined)
|
|
578
|
+
return found.shard;
|
|
579
|
+
for (const shard of await catalog.shards()) {
|
|
580
|
+
if (shard.kind !== "adopted" || !existsSync(shard.path))
|
|
581
|
+
continue;
|
|
582
|
+
try {
|
|
583
|
+
const database = await files.read(shard.path);
|
|
584
|
+
if ((await hasTables(database, t)) && (await database.get(`SELECT 1 FROM ${t.runs} WHERE run_id = ?`, runId)))
|
|
585
|
+
return shard;
|
|
586
|
+
}
|
|
587
|
+
catch { }
|
|
588
|
+
}
|
|
589
|
+
return undefined;
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* Imports every `<name>.jsonl` export file in `directory` into a local workflow journal. Every file is read and checked,
|
|
593
|
+
* and every run compared with the storage's copy, before anything is written: a malformed file, an unsupported version,
|
|
594
|
+
* a run that continued differently here, or a run a process here may still be running fails the import with the file
|
|
595
|
+
* and line, and nothing changes. A run the storage does not hold is added; one whose earlier events it holds gets the
|
|
596
|
+
* file's later ones; one it holds every event of is left as it is, so importing again changes nothing. String values
|
|
597
|
+
* inside the records are not compared, so a file whose strings a tool redacted imports as the run it was exported from.
|
|
598
|
+
*/
|
|
599
|
+
export async function importWorkflowRuns(storage, directory) {
|
|
600
|
+
const runs = await readExportDirectory(directory);
|
|
601
|
+
const t = runJournalTables(storage.kind === "sqlite" ? storage.prefix : undefined);
|
|
602
|
+
const location = storageLocation(storage);
|
|
603
|
+
const files = new ReadOnlyFiles();
|
|
604
|
+
const actions = [];
|
|
605
|
+
await withCleanup(async () => {
|
|
606
|
+
const catalogExists = storage.kind === "store" && (await adoptLegacyJournal(storage.directory));
|
|
607
|
+
const catalog = catalogExists ? await JournalCatalog.open(storage.directory) : undefined;
|
|
608
|
+
await withCleanup(async () => {
|
|
609
|
+
for (const run of runs) {
|
|
610
|
+
const shard = catalog === undefined ? undefined : await storedShard(catalog, files, t, run.header.runId);
|
|
611
|
+
let path = shard?.path;
|
|
612
|
+
if (storage.kind === "sqlite")
|
|
613
|
+
path = existsSync(storage.path) ? storage.path : undefined;
|
|
614
|
+
let stored;
|
|
615
|
+
if (path !== undefined) {
|
|
616
|
+
try {
|
|
617
|
+
stored = await readStoredRun(await files.read(path), t, run.header.runId);
|
|
618
|
+
}
|
|
619
|
+
catch (error) {
|
|
620
|
+
throw unreadableShard(run, path, error);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
actions.push({
|
|
624
|
+
run,
|
|
625
|
+
action: importAction(run, stored, path ?? location),
|
|
626
|
+
...(shard === undefined ? {} : { shard }),
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
}, async () => catalog?.close());
|
|
630
|
+
}, () => files.close());
|
|
631
|
+
const report = { added: [], updated: [], unchanged: [] };
|
|
632
|
+
const record = (runId, action) => (action === "add" ? report.added : action === "update" ? report.updated : report.unchanged).push(runId);
|
|
633
|
+
const pending = actions.filter(({ action, run }) => {
|
|
634
|
+
if (action === "unchanged")
|
|
635
|
+
record(run.header.runId, action);
|
|
636
|
+
return action !== "unchanged";
|
|
637
|
+
});
|
|
638
|
+
if (pending.length === 0)
|
|
639
|
+
return report;
|
|
640
|
+
if (storage.kind === "sqlite") {
|
|
641
|
+
const database = await openNodeSqliteDatabase(storage.path);
|
|
642
|
+
await withCleanup(async () => {
|
|
643
|
+
for (const { run } of pending)
|
|
644
|
+
record(run.header.runId, await database.transaction(async (tx) => {
|
|
645
|
+
await ensureRunJournalSchema(tx, storage.prefix);
|
|
646
|
+
return applyImport(tx, t, run, location);
|
|
647
|
+
}, TRANSFER_TRANSACTION));
|
|
648
|
+
}, () => database.close());
|
|
649
|
+
return report;
|
|
650
|
+
}
|
|
651
|
+
const catalog = await JournalCatalog.open(storage.directory);
|
|
652
|
+
const shards = new Map();
|
|
653
|
+
await withCleanup(async () => {
|
|
654
|
+
for (const { run, shard: stored } of pending) {
|
|
655
|
+
const { runId, name, cwd, status } = run.header;
|
|
656
|
+
// A new run goes to the shard its ID hashes to, as a consolidated run does: it writes nothing until it is
|
|
657
|
+
// resumed, so it never makes a shard busy for new roots.
|
|
658
|
+
const shard = await catalog.shard(await catalog.index((stored ?? (await catalog.homeShard(runId))).id, { runId, name, cwd, status }));
|
|
659
|
+
if (shard === undefined)
|
|
660
|
+
throw new WorkflowRunTransferError({
|
|
661
|
+
path: run.file,
|
|
662
|
+
line: 1,
|
|
663
|
+
runId,
|
|
664
|
+
reason: `cannot place run ${runId} in ${location}`,
|
|
665
|
+
});
|
|
666
|
+
let database = shards.get(shard.path);
|
|
667
|
+
if (database === undefined) {
|
|
668
|
+
try {
|
|
669
|
+
database = await openNodeSqliteDatabase(shard.path);
|
|
670
|
+
}
|
|
671
|
+
catch (error) {
|
|
672
|
+
throw unreadableShard(run, shard.path, error);
|
|
673
|
+
}
|
|
674
|
+
shards.set(shard.path, database);
|
|
675
|
+
}
|
|
676
|
+
const action = await database.transaction(async (tx) => {
|
|
677
|
+
await ensureRunJournalSchema(tx);
|
|
678
|
+
return applyImport(tx, t, run, shard.path);
|
|
679
|
+
}, TRANSFER_TRANSACTION);
|
|
680
|
+
if (action !== "unchanged")
|
|
681
|
+
await catalog.setStatus(runId, status);
|
|
682
|
+
record(runId, action);
|
|
683
|
+
}
|
|
684
|
+
}, async () => {
|
|
685
|
+
await closeEach(shards.values());
|
|
686
|
+
await catalog.close();
|
|
687
|
+
});
|
|
688
|
+
return report;
|
|
689
|
+
}
|
|
690
|
+
//# sourceMappingURL=journal-transfer.js.map
|