@foldrun/core 17.2.0 → 17.4.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/dist/src/approvals.js +3 -3
- package/dist/src/blob-cache.d.ts +58 -0
- package/dist/src/blob-cache.js +309 -0
- package/dist/src/blob-pins.d.ts +44 -0
- package/dist/src/blob-pins.js +61 -0
- package/dist/src/blob-store.d.ts +47 -0
- package/dist/src/blob-store.js +357 -0
- package/dist/src/blob-sweeper.d.ts +70 -0
- package/dist/src/blob-sweeper.js +254 -0
- package/dist/src/blob-types.d.ts +145 -0
- package/dist/src/blob-types.js +115 -0
- package/dist/src/browse-egress.d.ts +31 -0
- package/dist/src/browse-egress.js +43 -0
- package/dist/src/egress.d.ts +9 -0
- package/dist/src/evals.js +1 -1
- package/dist/src/history.d.ts +86 -9
- package/dist/src/history.js +132 -16
- package/dist/src/journal-store.d.ts +58 -0
- package/dist/src/journal-store.js +117 -0
- package/dist/src/manifest.d.ts +92 -0
- package/dist/src/manifest.js +239 -0
- package/dist/src/ops-log.js +26 -3
- package/dist/src/platform.d.ts +7 -0
- package/dist/src/platform.js +1 -0
- package/dist/src/publish.d.ts +134 -0
- package/dist/src/publish.js +434 -0
- package/dist/src/records.d.ts +72 -0
- package/dist/src/records.js +24 -0
- package/dist/src/revision-store.d.ts +161 -0
- package/dist/src/revision-store.js +378 -0
- package/dist/src/run-container.d.ts +20 -0
- package/dist/src/run-container.js +61 -0
- package/dist/src/runner.js +22 -4
- package/dist/src/s3-blob-store.d.ts +29 -0
- package/dist/src/s3-blob-store.js +458 -0
- package/dist/src/state-retention.d.ts +15 -0
- package/dist/src/state-retention.js +65 -0
- package/dist/src/storage.d.ts +29 -1
- package/dist/src/storage.js +331 -81
- package/dist/src/store.d.ts +41 -0
- package/dist/src/store.js +188 -5
- package/dist/src/trigger-log.js +17 -0
- package/dist/src/workspace-revisions.d.ts +259 -0
- package/dist/src/workspace-revisions.js +1274 -0
- package/package.json +1 -1
- package/src/approvals.ts +3 -3
- package/src/blob-cache.ts +354 -0
- package/src/blob-pins.ts +99 -0
- package/src/blob-store.ts +385 -0
- package/src/blob-sweeper.ts +308 -0
- package/src/blob-types.ts +216 -0
- package/src/browse-egress.ts +49 -1
- package/src/egress.ts +6 -0
- package/src/evals.ts +1 -1
- package/src/history.ts +182 -16
- package/src/journal-store.ts +152 -0
- package/src/manifest.ts +274 -0
- package/src/ops-log.ts +25 -3
- package/src/platform.ts +8 -0
- package/src/publish.ts +520 -0
- package/src/records.ts +105 -0
- package/src/revision-store.ts +513 -0
- package/src/run-container.ts +62 -0
- package/src/runner.ts +21 -4
- package/src/s3-blob-store.ts +489 -0
- package/src/state-retention.ts +83 -0
- package/src/storage.ts +335 -81
- package/src/store.ts +178 -5
- package/src/trigger-log.ts +15 -0
- package/src/workspace-revisions.ts +1324 -0
package/src/publish.ts
ADDED
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
// The publish protocol (FOL-126, phase 1). No caller uses it yet.
|
|
2
|
+
//
|
|
3
|
+
// Every write to a workspace — a run's copy-back, a dashboard save, /deploy,
|
|
4
|
+
// the assistant, /import, /restore — ends the same way:
|
|
5
|
+
//
|
|
6
|
+
// 1. The writer starts from a pinned base: it staged a revision, and every
|
|
7
|
+
// change it makes records the sha it STARTED from (`PathChange.base`).
|
|
8
|
+
// 2. publish() uploads the new blobs (conditional put: identical content is
|
|
9
|
+
// a no-op) — outside any transaction, so slow uploads never hold one.
|
|
10
|
+
// 3. It folds the changes onto the CURRENT head:
|
|
11
|
+
// - the head still holds the sha the writer started from → apply;
|
|
12
|
+
// - the head already holds what the writer wants → nothing to do;
|
|
13
|
+
// - the head holds something else → a CONFLICT on that path: the head's
|
|
14
|
+
// version stays, the writer's version is kept beside it as
|
|
15
|
+
// `<stem>.conflict-<op>.<ext>`. Different paths never conflict, so
|
|
16
|
+
// two runs editing different memory files both land. There is no
|
|
17
|
+
// merge of text, JSON or binaries (applyContainerChanges' append
|
|
18
|
+
// merge stays where it is, before the changes reach here).
|
|
19
|
+
// 4. It uploads the new manifests, confirms every blob the result names is
|
|
20
|
+
// still in the store (a sweeper may have removed one that nothing
|
|
21
|
+
// referenced yet — we hold the bytes, so we put it back), and then makes
|
|
22
|
+
// ONE commit: compare-and-set the head, insert the revision, record the
|
|
23
|
+
// op id. Nothing before that step changes what anyone reads.
|
|
24
|
+
// 5. The head moved meanwhile → stale → fold again on the new head.
|
|
25
|
+
// 6. The op id committed already (a retry after a lost answer) → `duplicate`
|
|
26
|
+
// with the original revision. A retry never publishes twice.
|
|
27
|
+
//
|
|
28
|
+
// A crash anywhere before step 4's commit leaves orphan blobs and manifests —
|
|
29
|
+
// unreferenced, invisible, collected later — and the old head. A crash after
|
|
30
|
+
// the commit leaves the new head. Never a mix: the head moves in one step.
|
|
31
|
+
//
|
|
32
|
+
// THE GC WINDOW (closed in phase 2). A sweeper that deleted between "the blobs
|
|
33
|
+
// are there" and "the commit landed" would strand the new revision. Now the
|
|
34
|
+
// publisher pins its blobs (BlobPins, blob-pins.ts) BEFORE it checks they
|
|
35
|
+
// exist and releases them after the commit; a revision pins its manifests in
|
|
36
|
+
// the same transaction as the commit; the sweeper deletes only through
|
|
37
|
+
// `guardDelete`. See blob-pins.ts for the argument.
|
|
38
|
+
//
|
|
39
|
+
// TWO HEADS (decided 6 Nov 2026). Authored files move on the workspace head and
|
|
40
|
+
// `state/` on its own state head, so a per-step state checkpoint never makes a
|
|
41
|
+
// source save replay (or the reverse). One publish() call whose changes touch
|
|
42
|
+
// both sides is therefore two commits — workspace first, then state, with a
|
|
43
|
+
// derived op id — and each is idempotent on its own: a crash between them is
|
|
44
|
+
// finished by retrying the same call. A revision names the manifest of its own
|
|
45
|
+
// side and EMPTY_MANIFEST_ID for the other.
|
|
46
|
+
//
|
|
47
|
+
// Restore is a publish too: a new revision whose manifest is an old one.
|
|
48
|
+
// History is never rewritten; `state/` is rewound only when asked, by naming a
|
|
49
|
+
// state revision (`stateTo`).
|
|
50
|
+
|
|
51
|
+
import type { BlobStore } from "./blob-store.ts";
|
|
52
|
+
import { BlobNotFound, readAll } from "./blob-store.ts";
|
|
53
|
+
import { PUBLISH_PIN_TTL_MS, type BlobPins } from "./blob-pins.ts";
|
|
54
|
+
import {
|
|
55
|
+
applyChanges,
|
|
56
|
+
assertManifest,
|
|
57
|
+
assertManifestPath,
|
|
58
|
+
blobObjectKey,
|
|
59
|
+
canonicalManifest,
|
|
60
|
+
conflictPath,
|
|
61
|
+
EMPTY_MANIFEST_ID,
|
|
62
|
+
emptyManifest,
|
|
63
|
+
entryId,
|
|
64
|
+
manifestId,
|
|
65
|
+
manifestObjectKey,
|
|
66
|
+
parseManifest,
|
|
67
|
+
sha256Hex,
|
|
68
|
+
sideOf,
|
|
69
|
+
MODE_EXEC,
|
|
70
|
+
MODE_FILE,
|
|
71
|
+
type Changes,
|
|
72
|
+
type Manifest,
|
|
73
|
+
type ManifestId,
|
|
74
|
+
type PathChange,
|
|
75
|
+
type Side,
|
|
76
|
+
} from "./manifest.ts";
|
|
77
|
+
import { assertOpId, OpIdReused, type RevisionStore, type Revision, type Scope, type WorkspaceRef } from "./revision-store.ts";
|
|
78
|
+
|
|
79
|
+
export interface Deps {
|
|
80
|
+
blobs: BlobStore;
|
|
81
|
+
revisions: RevisionStore;
|
|
82
|
+
/** Durable pins for GC. Unset = none (an install with no database has no sweeper). */
|
|
83
|
+
pins?: BlobPins;
|
|
84
|
+
/** Does this workspace exist right now? Handed to every commit as its guard
|
|
85
|
+
* (revision-store.ts CommitInput.guard). Unset: commits are not guarded. */
|
|
86
|
+
workspaceExists?: (ws: WorkspaceRef) => boolean | Promise<boolean>;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** A revision (or a publish) names a blob the store does not have. Explicit,
|
|
90
|
+
* never an empty file: the caller decides whether this is a repair or a
|
|
91
|
+
* refusal. */
|
|
92
|
+
export class BlobMissing extends Error {
|
|
93
|
+
readonly path: string;
|
|
94
|
+
readonly sha: string;
|
|
95
|
+
constructor(path: string, sha: string) {
|
|
96
|
+
super(`${path}: its content (${sha.slice(0, 12)}…) is missing from the store`);
|
|
97
|
+
this.name = "BlobMissing";
|
|
98
|
+
this.path = path;
|
|
99
|
+
this.sha = sha;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export class PublishError extends Error {
|
|
104
|
+
readonly code: "too_many_replays" | "bad_change" | "gone";
|
|
105
|
+
constructor(message: string, code: "too_many_replays" | "bad_change" | "gone") {
|
|
106
|
+
super(message);
|
|
107
|
+
this.name = "PublishError";
|
|
108
|
+
this.code = code;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface PublishInput {
|
|
113
|
+
ws: WorkspaceRef;
|
|
114
|
+
/** Idempotency key for THIS logical publish; the same on every retry. */
|
|
115
|
+
opId: string;
|
|
116
|
+
by: string;
|
|
117
|
+
message: string;
|
|
118
|
+
/** Per path, as the writer saw it. */
|
|
119
|
+
changes: Changes;
|
|
120
|
+
/** The bytes behind every `put` (by sha). Called only for blobs that must be
|
|
121
|
+
* uploaded or re-uploaded; may read a staged file lazily. */
|
|
122
|
+
bytesOf: (sha: string) => Promise<Uint8Array>;
|
|
123
|
+
/** Replay attempts before giving up under sustained contention. Default 8. */
|
|
124
|
+
maxReplays?: number;
|
|
125
|
+
/** This publish carries a restore: the revision whose content the changes
|
|
126
|
+
* bring back (the workspace head only; the history shows the link). */
|
|
127
|
+
restoredFrom?: string;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export interface Conflict {
|
|
131
|
+
path: string;
|
|
132
|
+
/** Where the writer's version was kept; null when the writer deleted the
|
|
133
|
+
* path and the head's newer version simply stayed. */
|
|
134
|
+
keptAs: string | null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export type PublishResult =
|
|
138
|
+
| { status: "committed"; revision: Revision; conflicts: Conflict[]; stateRevision?: Revision | null }
|
|
139
|
+
| { status: "duplicate"; revision: Revision; conflicts: Conflict[]; stateRevision?: Revision | null }
|
|
140
|
+
/** The head already holds all of it; no revision was made. */
|
|
141
|
+
| { status: "unchanged"; revision: Revision | null; conflicts: Conflict[]; stateRevision?: Revision | null };
|
|
142
|
+
|
|
143
|
+
/** Both heads of a workspace, read together. */
|
|
144
|
+
export interface Heads {
|
|
145
|
+
workspace: Revision | null;
|
|
146
|
+
state: Revision | null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export async function headsOf(deps: Deps, ws: WorkspaceRef): Promise<Heads> {
|
|
150
|
+
const [workspace, state] = await Promise.all([deps.revisions.head({ ...ws, scope: "workspace" }), deps.revisions.head({ ...ws, scope: "state" })]);
|
|
151
|
+
return { workspace, state };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The revision that owns a path: the state head for `state/…`, the workspace
|
|
155
|
+
* head for everything else. null when the path is on neither side. */
|
|
156
|
+
export function revisionFor(heads: Heads, rel: string): Revision | null {
|
|
157
|
+
const side = sideOf(rel);
|
|
158
|
+
return side === "state" ? heads.state : side === "authored" ? heads.workspace : null;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The two manifests as the pair of heads defines them. */
|
|
162
|
+
export async function manifestsAt(deps: Deps, tenant: string, heads: Heads): Promise<{ authored: Manifest; state: Manifest }> {
|
|
163
|
+
const [authored, state] = await Promise.all([
|
|
164
|
+
heads.workspace ? loadManifest(deps, tenant, heads.workspace.authored) : emptyManifest(),
|
|
165
|
+
heads.state ? loadManifest(deps, tenant, heads.state.state) : emptyManifest(),
|
|
166
|
+
]);
|
|
167
|
+
return { authored, state };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ---------- reading ----------
|
|
171
|
+
|
|
172
|
+
export async function loadManifest(deps: Deps, tenant: string, id: ManifestId): Promise<Manifest> {
|
|
173
|
+
if (id === EMPTY_MANIFEST_ID) return emptyManifest();
|
|
174
|
+
let bytes: Buffer;
|
|
175
|
+
try {
|
|
176
|
+
bytes = await readAll(deps.blobs, manifestObjectKey(tenant, id));
|
|
177
|
+
} catch (err) {
|
|
178
|
+
if (err instanceof BlobNotFound) throw new BlobMissing(`manifest ${id.slice(0, 12)}…`, id);
|
|
179
|
+
throw err;
|
|
180
|
+
}
|
|
181
|
+
// An object is named by its content; one that is not that content is
|
|
182
|
+
// corruption (or an overwrite), and every revision pointing at it is wrong.
|
|
183
|
+
if (sha256Hex(bytes) !== id) throw new Error(`manifest ${id.slice(0, 12)}… does not hash to its name — the stored object is corrupt`);
|
|
184
|
+
return parseManifest(bytes.toString("utf8"));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The two manifests a revision names (one of them is empty: a revision lives
|
|
188
|
+
* on one head; see manifestsAt for the workspace as a whole). */
|
|
189
|
+
export async function manifestsOf(deps: Deps, tenant: string, rev: Revision | null): Promise<{ authored: Manifest; state: Manifest }> {
|
|
190
|
+
if (!rev) return { authored: emptyManifest(), state: emptyManifest() };
|
|
191
|
+
const [authored, state] = await Promise.all([loadManifest(deps, tenant, rev.authored), loadManifest(deps, tenant, rev.state)]);
|
|
192
|
+
return { authored, state };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** One file of a revision, as a stream. Pass the revision of the head that
|
|
196
|
+
* owns the path (revisionFor); a path on the other side is simply absent. */
|
|
197
|
+
export async function openPath(deps: Deps, tenant: string, rev: Revision, rel: string): Promise<{ size: number; body: ReadableStream<Uint8Array> } | null> {
|
|
198
|
+
const side = sideOf(rel);
|
|
199
|
+
if (!side) return null;
|
|
200
|
+
const m = await loadManifest(deps, tenant, rev[side]);
|
|
201
|
+
const e = m.files[rel];
|
|
202
|
+
if (!e) return null;
|
|
203
|
+
try {
|
|
204
|
+
return { size: e.size, body: await deps.blobs.get(blobObjectKey(tenant, e.sha)) };
|
|
205
|
+
} catch (err) {
|
|
206
|
+
if (err instanceof BlobNotFound) throw new BlobMissing(rel, e.sha);
|
|
207
|
+
throw err;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Every blob a revision names, checked present. Returns the missing ones. */
|
|
212
|
+
export async function missingBlobs(
|
|
213
|
+
deps: Deps,
|
|
214
|
+
tenant: string,
|
|
215
|
+
rev: Revision,
|
|
216
|
+
opts: { state?: boolean; authored?: boolean; parallel?: number } = {},
|
|
217
|
+
): Promise<{ path: string; sha: string }[]> {
|
|
218
|
+
const parallel = opts.parallel ?? 8;
|
|
219
|
+
const authored = opts.authored === false ? emptyManifest() : await loadManifest(deps, tenant, rev.authored);
|
|
220
|
+
const state = opts.state === false ? emptyManifest() : await loadManifest(deps, tenant, rev.state);
|
|
221
|
+
const entries = [...Object.entries(authored.files), ...Object.entries(state.files)];
|
|
222
|
+
const missing: { path: string; sha: string }[] = [];
|
|
223
|
+
let next = 0;
|
|
224
|
+
await Promise.all(
|
|
225
|
+
Array.from({ length: Math.min(parallel, entries.length) }, async () => {
|
|
226
|
+
while (next < entries.length) {
|
|
227
|
+
const [p, e] = entries[next++];
|
|
228
|
+
if (!(await deps.blobs.head(blobObjectKey(tenant, e.sha)))) missing.push({ path: p, sha: e.sha });
|
|
229
|
+
}
|
|
230
|
+
}),
|
|
231
|
+
);
|
|
232
|
+
return missing.sort((a, b) => a.path.localeCompare(b.path));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// ---------- publishing ----------
|
|
236
|
+
|
|
237
|
+
const ENTRY_ID = /^[0-9a-f]{64}:\d+$/;
|
|
238
|
+
|
|
239
|
+
function validate(changes: Changes) {
|
|
240
|
+
for (const [p, c] of Object.entries(changes)) {
|
|
241
|
+
assertManifestPath(p);
|
|
242
|
+
if (c.base !== null && !(typeof c.base === "string" && ENTRY_ID.test(c.base))) throw new PublishError(`change for ${p} has a malformed base`, "bad_change");
|
|
243
|
+
if (c.op === "put") {
|
|
244
|
+
if (!/^[0-9a-f]{64}$/.test(c.sha) || !Number.isSafeInteger(c.size) || c.size < 0 || (c.mode !== MODE_FILE && c.mode !== MODE_EXEC)) {
|
|
245
|
+
throw new PublishError(`change for ${p} is malformed`, "bad_change");
|
|
246
|
+
}
|
|
247
|
+
} else if (c.op === "delete") {
|
|
248
|
+
if (c.base === null) throw new PublishError(`delete of ${p} names no base`, "bad_change");
|
|
249
|
+
} else {
|
|
250
|
+
throw new PublishError(`change for ${p} has no operation`, "bad_change");
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** The request's identity, for the operation record. Same changes, author and
|
|
256
|
+
* message → same digest; the op id alone does not say "this is a retry". */
|
|
257
|
+
export function requestDigest(kind: string, parts: unknown): string {
|
|
258
|
+
const canon = (v: unknown): unknown =>
|
|
259
|
+
Array.isArray(v) ? v.map(canon) : v && typeof v === "object" ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canon((v as Record<string, unknown>)[k])])) : v;
|
|
260
|
+
return sha256Hex(JSON.stringify([kind, canon(parts)]));
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Fold `changes` onto `head`'s manifests. Pure. */
|
|
264
|
+
export function fold(head: { authored: Manifest; state: Manifest }, changes: Changes, opId: string): { authored: Manifest; state: Manifest; conflicts: Conflict[]; applied: Changes } {
|
|
265
|
+
const apply: Record<"authored" | "state", Changes> = { authored: {}, state: {} };
|
|
266
|
+
const conflicts: Conflict[] = [];
|
|
267
|
+
for (const [p, c] of Object.entries(changes)) {
|
|
268
|
+
const side = sideOf(p)!;
|
|
269
|
+
const here = head[side].files[p];
|
|
270
|
+
const cur = here ? entryId(here) : null;
|
|
271
|
+
const want = c.op === "put" ? entryId(c) : null;
|
|
272
|
+
if (cur === want) continue; // the head already holds exactly that (bytes and mode)
|
|
273
|
+
if (cur === c.base) {
|
|
274
|
+
apply[side][p] = c as PathChange;
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
// The head holds something the writer did not start from, and not what it
|
|
278
|
+
// wants: keep the head's, and keep the writer's put beside it — under a
|
|
279
|
+
// name that is free (never over something else), and the same name on a
|
|
280
|
+
// retry.
|
|
281
|
+
if (c.op === "put") {
|
|
282
|
+
let keptAs = "";
|
|
283
|
+
for (let attempt = 0; ; attempt++) {
|
|
284
|
+
keptAs = conflictPath(p, opId, attempt);
|
|
285
|
+
const taken = apply[side][keptAs] ?? null;
|
|
286
|
+
const occupant = head[side].files[keptAs];
|
|
287
|
+
if (!occupant && !taken) break;
|
|
288
|
+
if (occupant && entryId(occupant) === entryId(c)) break; // this very copy is already there
|
|
289
|
+
if (attempt > 20) throw new PublishError(`no free name for the conflict copy of ${p}`, "bad_change");
|
|
290
|
+
}
|
|
291
|
+
const occupant = head[side].files[keptAs];
|
|
292
|
+
apply[side][keptAs] = { op: "put", base: occupant ? entryId(occupant) : null, sha: c.sha, size: c.size, mode: c.mode };
|
|
293
|
+
conflicts.push({ path: p, keptAs });
|
|
294
|
+
} else {
|
|
295
|
+
conflicts.push({ path: p, keptAs: null });
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
return {
|
|
299
|
+
authored: applyChanges(head.authored, apply.authored),
|
|
300
|
+
state: applyChanges(head.state, apply.state),
|
|
301
|
+
conflicts,
|
|
302
|
+
applied: { ...apply.authored, ...apply.state },
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
async function putManifest(deps: Deps, tenant: string, m: Manifest): Promise<ManifestId> {
|
|
307
|
+
const id = manifestId(m);
|
|
308
|
+
await deps.blobs.putIfAbsent(manifestObjectKey(tenant, id), Buffer.from(canonicalManifest(m)), { contentType: "application/json" });
|
|
309
|
+
return id;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Make sure every sha in `applied` is in the store, uploading from `bytesOf`
|
|
313
|
+
* any that are not. Cheap when they are (one head each). */
|
|
314
|
+
async function ensureBlobs(deps: Deps, tenant: string, applied: Changes, bytesOf: PublishInput["bytesOf"], parallel = 8): Promise<void> {
|
|
315
|
+
const want = new Map<string, number>(); // sha → the size the changes declare
|
|
316
|
+
for (const c of Object.values(applied)) {
|
|
317
|
+
if (c.op !== "put") continue;
|
|
318
|
+
if (want.has(c.sha) && want.get(c.sha) !== c.size) throw new PublishError(`two changes declare different sizes for ${c.sha.slice(0, 12)}…`, "bad_change");
|
|
319
|
+
want.set(c.sha, c.size);
|
|
320
|
+
}
|
|
321
|
+
const list = [...want];
|
|
322
|
+
let next = 0;
|
|
323
|
+
await Promise.all(
|
|
324
|
+
Array.from({ length: Math.min(parallel, list.length) }, async () => {
|
|
325
|
+
while (next < list.length) {
|
|
326
|
+
const [sha, size] = list[next++];
|
|
327
|
+
const key = blobObjectKey(tenant, sha);
|
|
328
|
+
const there = await deps.blobs.head(key);
|
|
329
|
+
if (there) {
|
|
330
|
+
if (there.size !== size) throw new PublishError(`${sha.slice(0, 12)}… is stored with ${there.size} bytes but the change says ${size}`, "bad_change");
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
const bytes = await bytesOf(sha);
|
|
334
|
+
if (sha256Hex(bytes) !== sha) throw new PublishError(`the bytes for ${sha.slice(0, 12)}… do not hash to it`, "bad_change");
|
|
335
|
+
if (bytes.length !== size) throw new PublishError(`the bytes for ${sha.slice(0, 12)}… are ${bytes.length} long but the change says ${size}`, "bad_change");
|
|
336
|
+
await deps.blobs.putIfAbsent(key, bytes);
|
|
337
|
+
}
|
|
338
|
+
}),
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function replay(op: { outcome: "committed" | "unchanged"; revision: Revision | null }): PublishResult {
|
|
343
|
+
// The conflict list is not stored beyond the paths (revision.conflicts);
|
|
344
|
+
// the duplicate answer says which revision was made, not how it got there.
|
|
345
|
+
return op.outcome === "committed" && op.revision
|
|
346
|
+
? { status: "duplicate", revision: op.revision, conflicts: [] }
|
|
347
|
+
: { status: "unchanged", revision: op.revision, conflicts: [] };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** The op id of the state half of a publish/restore: derived, so a retry
|
|
351
|
+
* makes the same one, and kept within the op-id length limit. */
|
|
352
|
+
export function stateOpId(opId: string): string {
|
|
353
|
+
return `${opId.slice(0, 120)}+state+${sha256Hex(opId).slice(0, 16)}`;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const RANK = { committed: 2, duplicate: 1, unchanged: 0 } as const;
|
|
357
|
+
|
|
358
|
+
const guardOf = (deps: Deps, ws: WorkspaceRef) => (deps.workspaceExists ? { guard: () => deps.workspaceExists!({ tenant: ws.tenant, workspace: ws.workspace }) } : {});
|
|
359
|
+
|
|
360
|
+
/** One head's half of a publish. */
|
|
361
|
+
async function publishScope(deps: Deps, input: PublishInput, scope: Scope, changes: Changes, opId: string): Promise<PublishResult> {
|
|
362
|
+
const ws: WorkspaceRef = { ...input.ws, scope };
|
|
363
|
+
const side: Side = scope === "workspace" ? "authored" : "state";
|
|
364
|
+
const digest = requestDigest("publish", { by: input.by, message: input.message, changes });
|
|
365
|
+
const earlier = await deps.revisions.operation(ws, opId);
|
|
366
|
+
if (earlier) {
|
|
367
|
+
if (earlier.digest !== digest) throw new OpIdReused(opId);
|
|
368
|
+
return replay(earlier);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// Upload first, outside any transaction. ensureBlobs inside the loop repeats
|
|
372
|
+
// the existence check right before each commit; the pins (taken by publish())
|
|
373
|
+
// are what make a sweep between here and there harmless.
|
|
374
|
+
await ensureBlobs(deps, ws.tenant, changes, input.bytesOf);
|
|
375
|
+
|
|
376
|
+
const max = input.maxReplays ?? 8;
|
|
377
|
+
for (let attempt = 0; attempt <= max; attempt++) {
|
|
378
|
+
const head = await deps.revisions.head(ws);
|
|
379
|
+
const current = head ? await loadManifest(deps, ws.tenant, head[side]) : emptyManifest();
|
|
380
|
+
const next = fold(side === "authored" ? { authored: current, state: emptyManifest() } : { authored: emptyManifest(), state: current }, changes, opId);
|
|
381
|
+
const nextManifest = next[side];
|
|
382
|
+
// Never write a manifest we could not read back.
|
|
383
|
+
assertManifest(nextManifest);
|
|
384
|
+
const id = manifestId(nextManifest);
|
|
385
|
+
if (head && id === head[side]) {
|
|
386
|
+
await deps.revisions.recordNoop(ws, opId, digest);
|
|
387
|
+
return { status: "unchanged", revision: head, conflicts: next.conflicts };
|
|
388
|
+
}
|
|
389
|
+
await ensureBlobs(deps, ws.tenant, next.applied, input.bytesOf);
|
|
390
|
+
if (id !== head?.[side]) await putManifest(deps, ws.tenant, nextManifest);
|
|
391
|
+
|
|
392
|
+
const res = await deps.revisions.commit(ws, {
|
|
393
|
+
base: head?.id ?? null,
|
|
394
|
+
authored: side === "authored" ? id : EMPTY_MANIFEST_ID,
|
|
395
|
+
state: side === "state" ? id : EMPTY_MANIFEST_ID,
|
|
396
|
+
opId,
|
|
397
|
+
digest,
|
|
398
|
+
by: input.by,
|
|
399
|
+
message: input.message,
|
|
400
|
+
conflicts: next.conflicts.map((c) => c.path),
|
|
401
|
+
...(input.restoredFrom && side === "authored" ? { restoredFrom: input.restoredFrom } : {}),
|
|
402
|
+
...guardOf(deps, input.ws),
|
|
403
|
+
});
|
|
404
|
+
if (res.status === "gone") throw new PublishError(`${input.ws.workspace} does not exist (any more)`, "gone");
|
|
405
|
+
if (res.status === "committed") return { status: "committed", revision: res.revision, conflicts: next.conflicts };
|
|
406
|
+
if (res.status === "duplicate") return { status: "duplicate", revision: res.revision, conflicts: [] };
|
|
407
|
+
// stale: the head moved. Fold again onto it.
|
|
408
|
+
}
|
|
409
|
+
throw new PublishError("the workspace changed too often while publishing; try again", "too_many_replays");
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Combine the two heads' answers: the workspace revision is `revision`, the
|
|
413
|
+
* state one `stateRevision`; the status is the strongest of the two. */
|
|
414
|
+
function combine(ws: PublishResult | null, st: PublishResult | null): PublishResult {
|
|
415
|
+
const parts = [ws, st].filter((x): x is PublishResult => x !== null);
|
|
416
|
+
const strongest = parts.reduce((a, b) => (RANK[b.status] > RANK[a.status] ? b : a));
|
|
417
|
+
return {
|
|
418
|
+
status: strongest.status,
|
|
419
|
+
revision: (ws ?? st)!.revision,
|
|
420
|
+
conflicts: parts.flatMap((x) => x.conflicts),
|
|
421
|
+
...(st ? { stateRevision: st.revision } : {}),
|
|
422
|
+
} as PublishResult;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
export async function publish(deps: Deps, input: PublishInput): Promise<PublishResult> {
|
|
426
|
+
assertOpId(input.opId);
|
|
427
|
+
validate(input.changes);
|
|
428
|
+
const split: Record<Side, Changes> = { authored: {}, state: {} };
|
|
429
|
+
for (const [p, c] of Object.entries(input.changes)) split[sideOf(p)!][p] = c;
|
|
430
|
+
const hasAuthored = Object.keys(split.authored).length > 0;
|
|
431
|
+
const hasState = Object.keys(split.state).length > 0;
|
|
432
|
+
|
|
433
|
+
// Pin every blob this publish may name BEFORE anything checks that it exists.
|
|
434
|
+
const shas = [...new Set(Object.values(input.changes).flatMap((c) => (c.op === "put" ? [c.sha] : [])))];
|
|
435
|
+
const holder = { kind: "publish" as const, id: input.opId };
|
|
436
|
+
if (shas.length) await deps.pins?.pinBlobs(input.ws.tenant, shas, holder, { ttlMs: PUBLISH_PIN_TTL_MS });
|
|
437
|
+
try {
|
|
438
|
+
// A call with no changes at all is the (empty) first publish of a workspace.
|
|
439
|
+
const ws = hasAuthored || !hasState ? await publishScope(deps, input, "workspace", split.authored, input.opId) : null;
|
|
440
|
+
const st = hasState ? await publishScope(deps, input, "state", split.state, stateOpId(input.opId)) : null;
|
|
441
|
+
return combine(ws, st);
|
|
442
|
+
} finally {
|
|
443
|
+
// Committed: the revision's own manifest pin protects the blobs now.
|
|
444
|
+
// Failed: nothing references them, and the lease would have expired anyway.
|
|
445
|
+
if (shas.length) await deps.pins?.release(input.ws.tenant, holder).catch(() => {});
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// ---------- restore ----------
|
|
450
|
+
|
|
451
|
+
export interface RestoreInput {
|
|
452
|
+
ws: WorkspaceRef;
|
|
453
|
+
/** The workspace-head revision whose content to bring back. */
|
|
454
|
+
to: string;
|
|
455
|
+
opId: string;
|
|
456
|
+
by: string;
|
|
457
|
+
message?: string;
|
|
458
|
+
/** Rewind state/ too, to this state-head revision. Unset: state stays —
|
|
459
|
+
* restoring source must not erase what agents have accumulated. */
|
|
460
|
+
stateTo?: string;
|
|
461
|
+
maxReplays?: number;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
async function restoreScope(deps: Deps, input: RestoreInput, scope: Scope, toId: string, opId: string): Promise<PublishResult> {
|
|
465
|
+
const ws: WorkspaceRef = { ...input.ws, scope };
|
|
466
|
+
const side: Side = scope === "workspace" ? "authored" : "state";
|
|
467
|
+
const digest = requestDigest("restore", { to: toId, scope, by: input.by, message: input.message ?? null });
|
|
468
|
+
const earlier = await deps.revisions.operation(ws, opId);
|
|
469
|
+
if (earlier) {
|
|
470
|
+
if (earlier.digest !== digest) throw new OpIdReused(opId);
|
|
471
|
+
return replay(earlier);
|
|
472
|
+
}
|
|
473
|
+
const target = await deps.revisions.revision(ws, toId);
|
|
474
|
+
if (!target) throw new PublishError(`no ${scope} revision ${toId}`, "bad_change");
|
|
475
|
+
// Check exactly what the new revision will point at, and nothing else:
|
|
476
|
+
// missing history it never references must not block it.
|
|
477
|
+
const missing = await missingBlobs(deps, ws.tenant, target, side === "authored" ? { state: false } : { authored: false });
|
|
478
|
+
if (missing.length) throw new BlobMissing(missing[0].path, missing[0].sha);
|
|
479
|
+
|
|
480
|
+
const max = input.maxReplays ?? 8;
|
|
481
|
+
for (let attempt = 0; attempt <= max; attempt++) {
|
|
482
|
+
const head = await deps.revisions.head(ws);
|
|
483
|
+
if (head && head[side] === target[side]) {
|
|
484
|
+
await deps.revisions.recordNoop(ws, opId, digest);
|
|
485
|
+
return { status: "unchanged", revision: head, conflicts: [] };
|
|
486
|
+
}
|
|
487
|
+
const res = await deps.revisions.commit(ws, {
|
|
488
|
+
base: head?.id ?? null,
|
|
489
|
+
authored: side === "authored" ? target.authored : EMPTY_MANIFEST_ID,
|
|
490
|
+
state: side === "state" ? target.state : EMPTY_MANIFEST_ID,
|
|
491
|
+
opId,
|
|
492
|
+
digest,
|
|
493
|
+
by: input.by,
|
|
494
|
+
message: input.message ?? `restore ${target.id}`,
|
|
495
|
+
restoredFrom: target.id,
|
|
496
|
+
...guardOf(deps, input.ws),
|
|
497
|
+
});
|
|
498
|
+
if (res.status === "gone") throw new PublishError(`${input.ws.workspace} does not exist (any more)`, "gone");
|
|
499
|
+
if (res.status === "committed") return { status: "committed", revision: res.revision, conflicts: [] };
|
|
500
|
+
if (res.status === "duplicate") return { status: "duplicate", revision: res.revision, conflicts: [] };
|
|
501
|
+
}
|
|
502
|
+
throw new PublishError("the workspace changed too often while restoring; try again", "too_many_replays");
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/** A new revision with an old one's content. History is untouched. Refuses,
|
|
506
|
+
* before committing anything, when a blob the old revision names is gone. */
|
|
507
|
+
export async function restore(deps: Deps, input: RestoreInput): Promise<PublishResult> {
|
|
508
|
+
assertOpId(input.opId);
|
|
509
|
+
// Both targets are checked before either head moves: a bad state target must
|
|
510
|
+
// not leave the source half restored.
|
|
511
|
+
if (input.stateTo) {
|
|
512
|
+
const st = await deps.revisions.revision({ ...input.ws, scope: "state" }, input.stateTo);
|
|
513
|
+
if (!st) throw new PublishError(`no state revision ${input.stateTo}`, "bad_change");
|
|
514
|
+
const missing = await missingBlobs(deps, input.ws.tenant, st, { authored: false });
|
|
515
|
+
if (missing.length) throw new BlobMissing(missing[0].path, missing[0].sha);
|
|
516
|
+
}
|
|
517
|
+
const ws = await restoreScope(deps, input, "workspace", input.to, input.opId);
|
|
518
|
+
const st = input.stateTo ? await restoreScope(deps, input, "state", input.stateTo, stateOpId(input.opId)) : null;
|
|
519
|
+
return combine(ws, st);
|
|
520
|
+
}
|
package/src/records.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// The records a workspace accumulates, behind a seam (FOL-126, phase 2).
|
|
2
|
+
//
|
|
3
|
+
// Runs, the run index, the trigger log and the storage file index used to be
|
|
4
|
+
// files on the data volume. On a hosted install they are rows in Postgres —
|
|
5
|
+
// but core has no database, and its callers are synchronous (readRun is called
|
|
6
|
+
// from dozens of places). So this is a small SYNCHRONOUS port: the platform
|
|
7
|
+
// registers an implementation (foldrun-platform src/records-pg.ts, which asks
|
|
8
|
+
// Postgres through a thread so the caller can keep its shape) and every
|
|
9
|
+
// function here falls back to the files when none is registered. A laptop, the
|
|
10
|
+
// CLI and a self-hosted install with no database never register one, so none
|
|
11
|
+
// of them changes by a byte.
|
|
12
|
+
//
|
|
13
|
+
// What is NOT here: run outputs and captured calls (bytes, phase 5), the
|
|
14
|
+
// ledger (platform, its own table), secrets (phase 6), workspace files
|
|
15
|
+
// (phase 3, revisions).
|
|
16
|
+
|
|
17
|
+
import { platform } from "./platform.ts";
|
|
18
|
+
import type { RunRecord, RunSummary } from "./store.ts";
|
|
19
|
+
import type { TriggerEvent } from "./trigger-log.ts";
|
|
20
|
+
import type { FileRecord } from "./storage.ts";
|
|
21
|
+
|
|
22
|
+
/** The read half of the port without blocking the event loop (FOL-126 phase
|
|
23
|
+
* 3b): the hot reads — one run, a workspace's run list, its live runs — asked
|
|
24
|
+
* of the database directly. Optional: a port without it is read through its
|
|
25
|
+
* synchronous twin, so a caller can always ask the async form. The rest of
|
|
26
|
+
* the port (writes, the trigger log, the storage index, counts, moves) is
|
|
27
|
+
* still synchronous: see the phase 3b report for the list. */
|
|
28
|
+
export interface RecordsPortAsync {
|
|
29
|
+
runGet(tenant: string, workspace: string, id: string): Promise<RunRecord | null>;
|
|
30
|
+
runSummaries(tenant: string, workspace: string): Promise<RunSummary[]>;
|
|
31
|
+
runLive(tenant: string, workspace: string): Promise<RunRecord[]>;
|
|
32
|
+
/** The write half, for a caller that is async anyway (FOL-126 phase 4):
|
|
33
|
+
* the same upsert as the synchronous runPut, honouring the fence of the
|
|
34
|
+
* lock its async context holds, with the event loop free while it waits.
|
|
35
|
+
* Optional like the reads: a port without it is written through runPut. */
|
|
36
|
+
runPut?(tenant: string, workspace: string, run: RunRecord, summary: RunSummary, live: boolean): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface RecordsPort {
|
|
40
|
+
/** Async reads (see RecordsPortAsync). */
|
|
41
|
+
async?: RecordsPortAsync;
|
|
42
|
+
// ---- runs: the whole record, and the row a list reads
|
|
43
|
+
/** Insert or replace one run. `live`: queued, running or parked at a gate. Last write wins. */
|
|
44
|
+
runPut(tenant: string, workspace: string, run: RunRecord, summary: RunSummary, live: boolean): void;
|
|
45
|
+
runGet(tenant: string, workspace: string, id: string): RunRecord | null;
|
|
46
|
+
/** True when a row was there. */
|
|
47
|
+
runDelete(tenant: string, workspace: string, id: string): boolean;
|
|
48
|
+
/** Every run's row, newest first. */
|
|
49
|
+
runSummaries(tenant: string, workspace: string): RunSummary[];
|
|
50
|
+
/** The live runs, whole, newest first. */
|
|
51
|
+
runLive(tenant: string, workspace: string): RunRecord[];
|
|
52
|
+
runCount(tenant: string, workspace: string): number;
|
|
53
|
+
/** Every workspace's run count in one question (the workspace list asks it once, not once per workspace). */
|
|
54
|
+
runCounts(tenant: string): Record<string, number>;
|
|
55
|
+
/** Every run, whole, newest first. */
|
|
56
|
+
runAll(tenant: string, workspace: string): RunRecord[];
|
|
57
|
+
/** Up to `limit` of one flow's runs, whole, newest first. */
|
|
58
|
+
runRecent(tenant: string, workspace: string, flow: string, limit: number): RunRecord[];
|
|
59
|
+
/** Runs that started at or after `sinceMs`, whole, newest first. */
|
|
60
|
+
runsSince(tenant: string, workspace: string, sinceMs: number): RunRecord[];
|
|
61
|
+
/** When the row last changed, in epoch MICROseconds, or null when there is
|
|
62
|
+
* none — what a poller compares instead of a file's mtime (two writes in one
|
|
63
|
+
* millisecond still differ), and what runUpdatedMs divides by 1000 for the
|
|
64
|
+
* age checks that want milliseconds. */
|
|
65
|
+
runStamp(tenant: string, workspace: string, id: string): number | null;
|
|
66
|
+
|
|
67
|
+
// ---- the trigger log: newest 500 per workspace kept
|
|
68
|
+
triggerAppend(tenant: string, workspace: string, event: TriggerEvent): void;
|
|
69
|
+
/** Newest first. */
|
|
70
|
+
triggerRead(tenant: string, workspace: string, limit: number): TriggerEvent[];
|
|
71
|
+
|
|
72
|
+
// ---- the storage/ file index
|
|
73
|
+
fileList(tenant: string, workspace: string): FileRecord[];
|
|
74
|
+
filePut(tenant: string, workspace: string, record: FileRecord): void;
|
|
75
|
+
fileDelete(tenant: string, workspace: string, path: string): boolean;
|
|
76
|
+
|
|
77
|
+
// ---- a workspace as a whole
|
|
78
|
+
/** Every record of the workspace is gone (it was deleted). Safe to repeat. */
|
|
79
|
+
workspaceDrop(tenant: string, workspace: string): void;
|
|
80
|
+
/** The workspace was renamed: its runs and trigger log follow. The file
|
|
81
|
+
* index does NOT — it moves with the bytes it names (fileMove), after they
|
|
82
|
+
* are copied, so a failed copy leaves index and bytes together. */
|
|
83
|
+
workspaceMove(tenant: string, from: string, to: string): void;
|
|
84
|
+
/** The storage file index follows the workspace's new name. */
|
|
85
|
+
fileMove(tenant: string, from: string, to: string): void;
|
|
86
|
+
|
|
87
|
+
/** True while this workspace's records are still FILES on this process: its
|
|
88
|
+
* boot import could not move them (records-import.ts), so every function
|
|
89
|
+
* answers from the files for it, and the next boot tries again. Optional:
|
|
90
|
+
* a port without it has no such workspaces. */
|
|
91
|
+
onFiles?(tenant: string, workspace: string): boolean;
|
|
92
|
+
|
|
93
|
+
/** A short named lock across processes, with stale-holder fencing: while
|
|
94
|
+
* `fn` runs, every write of this port made in its async context is refused
|
|
95
|
+
* if a newer holder took the lock over. */
|
|
96
|
+
lock<T>(name: string, fn: () => Promise<T>): Promise<T>;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The registered port, or null: files, as before. With a workspace, null also
|
|
100
|
+
* when that workspace is still on files (its import is pending). */
|
|
101
|
+
export function records(tenant?: string, workspace?: string): RecordsPort | null {
|
|
102
|
+
const port = platform.records ?? null;
|
|
103
|
+
if (port && tenant !== undefined && workspace !== undefined && port.onFiles?.(tenant, workspace)) return null;
|
|
104
|
+
return port;
|
|
105
|
+
}
|