@foldrun/core 17.3.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/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 +1 -1
- 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/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 +1 -1
- 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
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// The BlobStore contract and the pieces every driver shares (FOL-126).
|
|
2
|
+
// Split out of blob-store.ts so the s3 driver (s3-blob-store.ts) and the fs
|
|
3
|
+
// driver can both use the errors and the source type without importing each
|
|
4
|
+
// other.
|
|
5
|
+
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import crypto from "node:crypto";
|
|
8
|
+
|
|
9
|
+
export class BlobNotFound extends Error {
|
|
10
|
+
readonly key: string;
|
|
11
|
+
constructor(key: string) {
|
|
12
|
+
super(`no object at ${key}`);
|
|
13
|
+
this.name = "BlobNotFound";
|
|
14
|
+
this.key = key;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** A failure the caller may retry: the network, a timeout, a 5xx, a 429, a
|
|
19
|
+
* conditional-write conflict, an expired token. Everything else (403, 400,
|
|
20
|
+
* 404, a bad bucket name) is final. */
|
|
21
|
+
export class BlobTransientError extends Error {
|
|
22
|
+
readonly status?: number;
|
|
23
|
+
/** The store's own error code when it gave one (S3: `SlowDown`, ...). */
|
|
24
|
+
readonly code?: string;
|
|
25
|
+
constructor(message: string, status?: number, code?: string) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = "BlobTransientError";
|
|
28
|
+
this.status = status;
|
|
29
|
+
this.code = code;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The store said no and will say no again: wrong credentials, no such bucket,
|
|
34
|
+
* a malformed request. Carries the HTTP status and the store's error code. */
|
|
35
|
+
export class BlobStoreError extends Error {
|
|
36
|
+
readonly status: number;
|
|
37
|
+
readonly code?: string;
|
|
38
|
+
constructor(message: string, status: number, code?: string) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.name = "BlobStoreError";
|
|
41
|
+
this.status = status;
|
|
42
|
+
this.code = code;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The bytes being uploaded stopped matching what was announced (the file was
|
|
47
|
+
* truncated, rewritten, or does not hash to the name it was given). Not
|
|
48
|
+
* retried: reading it again would give the same answer. */
|
|
49
|
+
export class BlobSourceError extends Error {
|
|
50
|
+
constructor(message: string) {
|
|
51
|
+
super(message);
|
|
52
|
+
this.name = "BlobSourceError";
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface PutOptions {
|
|
57
|
+
contentType?: string;
|
|
58
|
+
signal?: AbortSignal;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface PutSourceOptions extends PutOptions {
|
|
62
|
+
/** Hex sha256 of the whole content, when the caller has it (a blob key is
|
|
63
|
+
* one). It is signed into the request, so the store verifies it; without it
|
|
64
|
+
* the source is read once more to find it. */
|
|
65
|
+
sha256?: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface PutResult {
|
|
69
|
+
created: boolean;
|
|
70
|
+
/** The store's ETag for the object that is there, unquoted, when it said.
|
|
71
|
+
* For a single-request upload that is the md5 of the content on S3, R2 and
|
|
72
|
+
* MinIO; for a multipart upload it is `<hash>-<parts>`. */
|
|
73
|
+
etag?: string;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface HeadResult {
|
|
77
|
+
size: number;
|
|
78
|
+
/** When the object was last written, when the store says (whole seconds on
|
|
79
|
+
* S3). The garbage collector's grace period is measured from here. NOTE: a
|
|
80
|
+
* conditional put that finds the object already there does NOT refresh it,
|
|
81
|
+
* so an old blob that a new publish reuses looks old to a sweeper — the
|
|
82
|
+
* grace period alone does not protect it (see publish.ts, "the GC window"). */
|
|
83
|
+
modifiedAt?: Date;
|
|
84
|
+
etag?: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* A re-readable source of bytes. Streaming upload needs to read the same bytes
|
|
89
|
+
* more than once: to hash them before they are sent, and again for every retry
|
|
90
|
+
* or resumed part. So it is a *range reader*, not a one-shot stream.
|
|
91
|
+
*/
|
|
92
|
+
export interface BlobSource {
|
|
93
|
+
readonly size: number;
|
|
94
|
+
/** The bytes [start, end) as a stream. Throws BlobSourceError if the source
|
|
95
|
+
* turns out shorter than `size`. */
|
|
96
|
+
read(start: number, end: number, signal?: AbortSignal): AsyncIterable<Uint8Array>;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* What every caller gets: create-only, read, ask. There is deliberately no
|
|
101
|
+
* overwrite and no delete here — an object is named by its content, so the only
|
|
102
|
+
* write that makes sense is "put it if it is not there", and removing one is
|
|
103
|
+
* the garbage collector's job alone (BlobSweeper, below). A missed option
|
|
104
|
+
* cannot corrupt a shared object because the option does not exist.
|
|
105
|
+
*/
|
|
106
|
+
export interface BlobStore {
|
|
107
|
+
readonly kind: "fs" | "s3";
|
|
108
|
+
/** Write only if nothing is at the key. `created: false` means it was
|
|
109
|
+
* already there; for a content-addressed key that is success. The existing
|
|
110
|
+
* object is NOT verified against `body` — callers that need that compare the
|
|
111
|
+
* returned `etag` or read it back. After a retry, `created: false` can also
|
|
112
|
+
* mean "my first attempt landed and its answer was lost". */
|
|
113
|
+
putIfAbsent(key: string, body: Uint8Array, opts?: PutOptions): Promise<PutResult>;
|
|
114
|
+
/** The same, for content that should not be held in memory: streamed from the
|
|
115
|
+
* source, and — on s3, past the multipart threshold — uploaded in parts that
|
|
116
|
+
* survive an interruption and are picked up again by the next call. */
|
|
117
|
+
putSourceIfAbsent(key: string, source: BlobSource, opts?: PutSourceOptions): Promise<PutResult>;
|
|
118
|
+
/** The object as a stream, optionally one inclusive byte range. Throws BlobNotFound. */
|
|
119
|
+
get(key: string, opts?: { range?: { start: number; end: number }; signal?: AbortSignal }): Promise<ReadableStream<Uint8Array>>;
|
|
120
|
+
head(key: string, opts?: { signal?: AbortSignal }): Promise<HeadResult | null>;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Removal. Held by the garbage collector and by tests; not passed to publish. */
|
|
124
|
+
export interface BlobSweeper {
|
|
125
|
+
/** Idempotent: a missing key is the end state asked for. */
|
|
126
|
+
delete(key: string, opts?: { signal?: AbortSignal }): Promise<void>;
|
|
127
|
+
/** Throw away uploads that were started and never finished (s3 multipart
|
|
128
|
+
* uploads; fs temp files) and are older than `olderThanMs`. Returns how many.
|
|
129
|
+
* A bucket lifecycle rule (AbortIncompleteMultipartUpload) does the same on
|
|
130
|
+
* AWS and R2; this is for stores that have none, and for tests. */
|
|
131
|
+
abortStaleUploads(opts: { olderThanMs: number; prefix?: string; signal?: AbortSignal }): Promise<number>;
|
|
132
|
+
/** An account is gone: remove everything under its prefix. Only a store that
|
|
133
|
+
* can enumerate has it (the folder one); a bucket's objects are the
|
|
134
|
+
* sweeper's once the account's pins are released. */
|
|
135
|
+
purgeTenant?(tenant: string): Promise<void>;
|
|
136
|
+
/** Every object under a key prefix, with its size and last-modified time —
|
|
137
|
+
* what the sweeper walks. */
|
|
138
|
+
list?(prefix: string, opts?: { signal?: AbortSignal }): AsyncIterable<ListedObject>;
|
|
139
|
+
/** The accounts that have objects (the first key segment under `t/`). */
|
|
140
|
+
tenants?(opts?: { signal?: AbortSignal }): Promise<string[]>;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export interface ListedObject {
|
|
144
|
+
key: string;
|
|
145
|
+
size: number;
|
|
146
|
+
modifiedAt: Date;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Read a whole object. For manifests and small blobs; a large file is
|
|
150
|
+
* streamed with `get`. */
|
|
151
|
+
export async function readAll(store: BlobStore, key: string): Promise<Buffer> {
|
|
152
|
+
const chunks: Buffer[] = [];
|
|
153
|
+
const reader = (await store.get(key)).getReader();
|
|
154
|
+
for (;;) {
|
|
155
|
+
const { done, value } = await reader.read();
|
|
156
|
+
if (done) break;
|
|
157
|
+
chunks.push(Buffer.from(value));
|
|
158
|
+
}
|
|
159
|
+
return Buffer.concat(chunks);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// ---------- keys ----------
|
|
163
|
+
|
|
164
|
+
/** A key is slash-separated safe segments. Checked in every driver, because a
|
|
165
|
+
* key reaches the fs driver as a path. */
|
|
166
|
+
export function assertKey(key: string): string {
|
|
167
|
+
if (!key || key.length > 600 || key.startsWith("/") || key.split("/").some((s) => !/^[A-Za-z0-9._=-]{1,200}$/.test(s) || s === "." || s === "..")) {
|
|
168
|
+
throw new Error(`illegal object key: ${key.slice(0, 80)}`);
|
|
169
|
+
}
|
|
170
|
+
return key;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ---------- sources ----------
|
|
174
|
+
|
|
175
|
+
export function bufferSource(buf: Uint8Array): BlobSource {
|
|
176
|
+
return {
|
|
177
|
+
size: buf.byteLength,
|
|
178
|
+
async *read(start, end) {
|
|
179
|
+
const hi = Math.min(end, buf.byteLength);
|
|
180
|
+
// Slices of at most 1 MiB, so a consumer sees a stream either way.
|
|
181
|
+
for (let at = start; at < hi; at += 1 << 20) yield buf.subarray(at, Math.min(at + (1 << 20), hi));
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** A file on disk. The size is taken now; if the file is shorter (or longer)
|
|
187
|
+
* when it is read, the read throws BlobSourceError rather than send a body
|
|
188
|
+
* that no longer matches what was announced. */
|
|
189
|
+
export function fileSource(filePath: string): BlobSource {
|
|
190
|
+
const size = fs.statSync(filePath).size;
|
|
191
|
+
return {
|
|
192
|
+
size,
|
|
193
|
+
async *read(start, end, signal) {
|
|
194
|
+
const hi = Math.min(end, size);
|
|
195
|
+
if (hi <= start) return;
|
|
196
|
+
const stream = fs.createReadStream(filePath, { start, end: hi - 1, highWaterMark: 1 << 20, signal });
|
|
197
|
+
let got = 0;
|
|
198
|
+
for await (const chunk of stream) {
|
|
199
|
+
got += (chunk as Buffer).length;
|
|
200
|
+
yield chunk as Buffer;
|
|
201
|
+
}
|
|
202
|
+
if (got !== hi - start) throw new BlobSourceError(`${filePath} changed while it was being uploaded: expected ${hi - start} bytes at ${start}, read ${got}`);
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** sha256 (and md5, which is what a single-request ETag is) of a range. */
|
|
208
|
+
export async function hashRange(source: BlobSource, start: number, end: number, signal?: AbortSignal): Promise<{ sha256: string; md5: string }> {
|
|
209
|
+
const sha = crypto.createHash("sha256");
|
|
210
|
+
const md5 = crypto.createHash("md5");
|
|
211
|
+
for await (const chunk of source.read(start, end, signal)) {
|
|
212
|
+
sha.update(chunk);
|
|
213
|
+
md5.update(chunk);
|
|
214
|
+
}
|
|
215
|
+
return { sha256: sha.digest("hex"), md5: md5.digest("hex") };
|
|
216
|
+
}
|
package/src/evals.ts
CHANGED
|
@@ -39,7 +39,7 @@ import fs from "node:fs";
|
|
|
39
39
|
import crypto from "node:crypto";
|
|
40
40
|
import path from "node:path";
|
|
41
41
|
import { deployedCommit } from "./deploy.ts";
|
|
42
|
-
import { latestRevisionId } from "./history.ts";
|
|
42
|
+
import { latestRevisionIdLocal as latestRevisionId } from "./history.ts";
|
|
43
43
|
import matter from "./matter.ts";
|
|
44
44
|
import { spawn } from "node:child_process";
|
|
45
45
|
import { hostSafeEnv } from "./host-env.ts";
|
package/src/history.ts
CHANGED
|
@@ -55,6 +55,64 @@ export function registerTreeReader(fn: TreeReader) {
|
|
|
55
55
|
readTree = (tenant, scope) => fn(tenant, scope) ?? prev(tenant, scope);
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
+
/** The scope's tree as the registered readers see it (text files only), or null. */
|
|
59
|
+
export function currentTree(tenant: string, scope: string): RevisionFile[] | null {
|
|
60
|
+
return readTree(tenant, scope);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Where a committed change set is also handed (workspace-revisions.ts registers
|
|
65
|
+
* here: this module cannot import it, it imports the store which imports this).
|
|
66
|
+
* Called after the legacy record is written; never throws into the writer.
|
|
67
|
+
*/
|
|
68
|
+
type Journal = (tenant: string, scope: string, files: RevisionFile[], meta: { by: string; message: string; at: string }) => void;
|
|
69
|
+
let journal: Journal | null = null;
|
|
70
|
+
export function registerJournal(fn: Journal | null) {
|
|
71
|
+
journal = fn;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A workspace was deleted: whatever a registered journal still holds for it
|
|
75
|
+
* (queued changes, their files) goes too (FOL-126 phase 4). */
|
|
76
|
+
let onGone: ((tenant: string, workspace: string) => void) | null = null;
|
|
77
|
+
export function registerWorkspaceGone(fn: ((tenant: string, workspace: string) => void) | null) {
|
|
78
|
+
onGone = fn;
|
|
79
|
+
}
|
|
80
|
+
export function workspaceGone(tenant: string, workspace: string): void {
|
|
81
|
+
try {
|
|
82
|
+
onGone?.(tenant, workspace);
|
|
83
|
+
} catch {
|
|
84
|
+
// a journal that cannot be cleared now is cleared at the next boot (the replay discards a missing workspace)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* What follows a workspace through a delete or a rename (workspace-revisions.ts
|
|
90
|
+
* registers it): its journal and its history in the revision store. The async
|
|
91
|
+
* forms run the folder's own change INSIDE them (`remove`, `rename`), so that
|
|
92
|
+
* a store which cannot be reached stops the change before anything is removed
|
|
93
|
+
* or moved, and a writer racing the change is held off until it is done. The
|
|
94
|
+
* sync forms are for a caller that cannot wait: they do what can be done now
|
|
95
|
+
* and finish in the background.
|
|
96
|
+
*/
|
|
97
|
+
export interface WorkspaceLifecycle {
|
|
98
|
+
drop(tenant: string, workspace: string, remove: () => void): Promise<void>;
|
|
99
|
+
move(tenant: string, from: string, to: string, rename: () => void): Promise<void>;
|
|
100
|
+
moved(tenant: string, from: string, to: string): void;
|
|
101
|
+
}
|
|
102
|
+
let lifecycleHooks: WorkspaceLifecycle | null = null;
|
|
103
|
+
export function registerWorkspaceLifecycle(l: WorkspaceLifecycle | null) {
|
|
104
|
+
lifecycleHooks = l;
|
|
105
|
+
}
|
|
106
|
+
export const workspaceLifecycle = (): WorkspaceLifecycle | null => lifecycleHooks;
|
|
107
|
+
/** A workspace's folder was renamed (sync path): see WorkspaceLifecycle.moved. */
|
|
108
|
+
export function workspaceMoved(tenant: string, from: string, to: string): void {
|
|
109
|
+
try {
|
|
110
|
+
lifecycleHooks?.moved(tenant, from, to);
|
|
111
|
+
} catch {
|
|
112
|
+
// finished by the next reconcile
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
58
116
|
function assertSafeName(v: string, what: string) {
|
|
59
117
|
if (!/^[A-Za-z0-9][A-Za-z0-9._@-]{0,120}$/.test(v)) throw new Error(`illegal ${what}: ${v}`);
|
|
60
118
|
}
|
|
@@ -166,6 +224,11 @@ export function recordRevision(
|
|
|
166
224
|
// outside this call, such as a bundle's generated index.
|
|
167
225
|
snapshot(tenant, scope, rev.id);
|
|
168
226
|
fs.appendFileSync(path.join(dir, "index.jsonl"), `${JSON.stringify(line)}\n`);
|
|
227
|
+
try {
|
|
228
|
+
journal?.(tenant, scope, changed, { by: rev.by, message: rev.message, at: rev.at });
|
|
229
|
+
} catch {
|
|
230
|
+
// the revision store is not allowed to break a save; workspace-revisions logs and retries
|
|
231
|
+
}
|
|
169
232
|
return rev;
|
|
170
233
|
}
|
|
171
234
|
|
|
@@ -209,13 +272,13 @@ function snapshot(tenant: string, scope: string, id: string): boolean {
|
|
|
209
272
|
}
|
|
210
273
|
|
|
211
274
|
/** Whether a revision can be restored to: it has a snapshot. */
|
|
212
|
-
export function
|
|
275
|
+
export function hasSnapshotLocal(tenant: string, scope: string, id: string): boolean {
|
|
213
276
|
assertSafeName(id, "revision id");
|
|
214
277
|
return fs.existsSync(treePath(tenant, scope, id));
|
|
215
278
|
}
|
|
216
279
|
|
|
217
280
|
/** The whole tree at revision `id`, or null when it has no snapshot. */
|
|
218
|
-
export function
|
|
281
|
+
export function snapshotAtLocal(tenant: string, scope: string, id: string): { path: string; content: string }[] | null {
|
|
219
282
|
assertSafeName(id, "revision id");
|
|
220
283
|
let manifest: { v: number; files: Record<string, string> };
|
|
221
284
|
try {
|
|
@@ -239,7 +302,7 @@ function snapshotIds(tenant: string, scope: string): Set<string> {
|
|
|
239
302
|
}
|
|
240
303
|
|
|
241
304
|
/** The newest revision that can be restored to — what "now" is in history. */
|
|
242
|
-
export function
|
|
305
|
+
export function headRevisionLocal(tenant: string, scope: string): RevisionSummary | null {
|
|
243
306
|
const have = snapshotIds(tenant, scope);
|
|
244
307
|
return journalRevisions(tenant, scope, { limit: Infinity }).find((r) => have.has(r.id)) ?? null;
|
|
245
308
|
}
|
|
@@ -251,8 +314,8 @@ export function headRevision(tenant: string, scope: string): RevisionSummary | n
|
|
|
251
314
|
* by a path that never recorded a change. Returns the head's id, or null
|
|
252
315
|
* when there is nothing to snapshot.
|
|
253
316
|
*/
|
|
254
|
-
export function
|
|
255
|
-
const head =
|
|
317
|
+
export function ensureBaselineLocal(tenant: string, scope: string, by = "foldrun"): string | null {
|
|
318
|
+
const head = headRevisionLocal(tenant, scope);
|
|
256
319
|
if (head) return head.id;
|
|
257
320
|
const tree = readTree(tenant, scope);
|
|
258
321
|
if (!tree || tree.length === 0) return null;
|
|
@@ -265,7 +328,7 @@ export function ensureBaseline(tenant: string, scope: string, by = "foldrun"): s
|
|
|
265
328
|
try {
|
|
266
329
|
fs.writeFileSync(marker, id, { flag: "wx" });
|
|
267
330
|
} catch {
|
|
268
|
-
const held =
|
|
331
|
+
const held = headRevisionLocal(tenant, scope)?.id ?? null;
|
|
269
332
|
// A marker with no baseline behind it, minutes old, is a process that
|
|
270
333
|
// died writing one: clear it, and the next call writes the baseline.
|
|
271
334
|
try {
|
|
@@ -297,16 +360,20 @@ export function ensureBaseline(tenant: string, scope: string, by = "foldrun"): s
|
|
|
297
360
|
* moment. Null when history holds nothing that old. Throws (status 400) on
|
|
298
361
|
* something that is none of those.
|
|
299
362
|
*/
|
|
300
|
-
export function
|
|
363
|
+
export function resolveRevisionLocal(
|
|
301
364
|
tenant: string,
|
|
302
365
|
scope: string,
|
|
303
366
|
to: string,
|
|
304
367
|
now = Date.now(),
|
|
305
368
|
): { id: string; at: string; by: string; message: string } | null {
|
|
369
|
+
const have = snapshotIds(tenant, scope);
|
|
370
|
+
return resolveIn(journalRevisions(tenant, scope, { limit: Infinity }).filter((r) => have.has(r.id)), to, now);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** The pick of resolveRevision over a newest-first list of restorable revisions. */
|
|
374
|
+
function resolveIn(all: RevisionSummary[], to: string, now: number): { id: string; at: string; by: string; message: string } | null {
|
|
306
375
|
const t = to.trim();
|
|
307
376
|
if (!t || t.startsWith("-")) throw Object.assign(new Error(`not a revision or a time: ${to}`), { status: 400 });
|
|
308
|
-
const have = snapshotIds(tenant, scope);
|
|
309
|
-
const all = journalRevisions(tenant, scope, { limit: Infinity }).filter((r) => have.has(r.id));
|
|
310
377
|
const rel = /^(\d+)\s*(m|h|d|w)$/.exec(t);
|
|
311
378
|
const moment = rel
|
|
312
379
|
? now - Number(rel[1]) * { m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 }[rel[2] as "m" | "h" | "d" | "w"]
|
|
@@ -347,7 +414,7 @@ function describe(files: RevisionFile[]): string {
|
|
|
347
414
|
}
|
|
348
415
|
|
|
349
416
|
/** Newest first. `forPath` narrows to revisions that touched one file. */
|
|
350
|
-
export function
|
|
417
|
+
export function listRevisionsLocal(
|
|
351
418
|
tenant: string,
|
|
352
419
|
scope: string,
|
|
353
420
|
opts: { forPath?: string; limit?: number } = {},
|
|
@@ -416,7 +483,7 @@ function rebuildIndex(dir: string): RevisionSummary[] {
|
|
|
416
483
|
return rows.map(({ written: _w, ...r }) => r).reverse();
|
|
417
484
|
}
|
|
418
485
|
|
|
419
|
-
export function
|
|
486
|
+
export function readRevisionLocal(tenant: string, scope: string, id: string, forPath?: string): Revision | null {
|
|
420
487
|
assertSafeName(id, "revision id");
|
|
421
488
|
const file = path.join(historyDir(tenant, scope), `${id}.json`);
|
|
422
489
|
if (!fs.existsSync(file)) return null;
|
|
@@ -427,11 +494,14 @@ export function readRevision(tenant: string, scope: string, id: string, forPath?
|
|
|
427
494
|
/** The files changed after revision `from` up to and including `to`, in a
|
|
428
495
|
* scope — what differs between the versions two runs ran (FOL-72). Null
|
|
429
496
|
* when either is unknown or `to` is not after `from`. */
|
|
430
|
-
export function
|
|
497
|
+
export function changedPathsBetweenLocal(tenant: string, scope: string, from: string | null, to: string | null): string[] | null {
|
|
431
498
|
if (!from || !to) return null;
|
|
432
499
|
if (from === to) return [];
|
|
433
|
-
|
|
434
|
-
|
|
500
|
+
return changedIn(listRevisionsLocal(tenant, scope, { limit: 500 }), from, to);
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function changedIn(revs: RevisionSummary[], from: string, to: string): string[] | null {
|
|
504
|
+
// newest first. An exact id before a commit, as resolveRevision.
|
|
435
505
|
const at = (x: string) => {
|
|
436
506
|
const byId = revs.findIndex((r) => r.id === x);
|
|
437
507
|
return byId >= 0 ? byId : revs.findIndex((r) => r.commit === x);
|
|
@@ -444,8 +514,104 @@ export function changedPathsBetween(tenant: string, scope: string, from: string
|
|
|
444
514
|
|
|
445
515
|
/** The most recent revision id for a scope — what a change is attributed
|
|
446
516
|
* to when nothing more specific (a deployed commit) is on record. */
|
|
447
|
-
export function
|
|
448
|
-
return
|
|
517
|
+
export function latestRevisionIdLocal(tenant: string, scope: string): string | null {
|
|
518
|
+
return listRevisionsLocal(tenant, scope, { limit: 1 })[0]?.id ?? null;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
// ------------------------------------------------- history from revisions
|
|
523
|
+
//
|
|
524
|
+
// FOL-126 phase 3: where the install keeps revisions (workspace-revisions.ts
|
|
525
|
+
// registers a view), the history page, a revision's diff, the restore points
|
|
526
|
+
// and run-to-run compare are answered from them — the same shapes this file
|
|
527
|
+
// has always returned. Everything is async because a revision lives in a
|
|
528
|
+
// store, not on this disk. Where nothing is registered (a laptop, the CLI, an
|
|
529
|
+
// install with the journal off) or a workspace has no revisions yet, the
|
|
530
|
+
// local `.history/` answers, exactly as before; where both exist the list is
|
|
531
|
+
// the revisions followed by the older local entries, so turning revisions on
|
|
532
|
+
// loses no history. The account shelf ("@library") is never in revisions.
|
|
533
|
+
|
|
534
|
+
export interface RevisionView {
|
|
535
|
+
/** Newest first, or null when revisions do not serve this scope. */
|
|
536
|
+
list(tenant: string, scope: string, opts: { forPath?: string; limit?: number }): Promise<RevisionSummary[] | null>;
|
|
537
|
+
read(tenant: string, scope: string, id: string, forPath?: string): Promise<Revision | null>;
|
|
538
|
+
snapshot(tenant: string, scope: string, id: string): Promise<{ path: string; content: string }[] | null>;
|
|
539
|
+
}
|
|
540
|
+
let view: RevisionView | null = null;
|
|
541
|
+
export function registerRevisionView(v: RevisionView | null) {
|
|
542
|
+
view = v;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** Revisions first, then the local entries older than the oldest of them. */
|
|
546
|
+
async function combined(tenant: string, scope: string, opts: { forPath?: string; limit?: number }, restorableOnly = false): Promise<RevisionSummary[]> {
|
|
547
|
+
const limit = opts.limit ?? 200;
|
|
548
|
+
const mine = view && scope !== "@library" ? await view.list(tenant, scope, { ...opts, limit: Number.isFinite(limit) ? limit : 500 }) : null;
|
|
549
|
+
let local = listRevisionsLocal(tenant, scope, { forPath: opts.forPath, limit: Infinity });
|
|
550
|
+
if (restorableOnly) {
|
|
551
|
+
const have = snapshotIds(tenant, scope);
|
|
552
|
+
local = local.filter((r) => have.has(r.id));
|
|
553
|
+
}
|
|
554
|
+
if (!mine || !mine.length) return local.slice(0, limit);
|
|
555
|
+
const oldest = mine[mine.length - 1].at;
|
|
556
|
+
const seen = new Set(mine.map((r) => r.id));
|
|
557
|
+
return [...mine, ...local.filter((r) => !seen.has(r.id) && r.at < oldest)].slice(0, limit);
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
export async function listRevisions(tenant: string, scope: string, opts: { forPath?: string; limit?: number } = {}): Promise<RevisionSummary[]> {
|
|
561
|
+
return combined(tenant, scope, opts);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/** The list the history page shows: each row with whether it can be restored
|
|
565
|
+
* to. One listing answers both — every revision in the store is restorable;
|
|
566
|
+
* a local entry is when it has a snapshot — where asking per row would list
|
|
567
|
+
* the store once per row. */
|
|
568
|
+
export async function listRevisionsRestorable(tenant: string, scope: string, opts: { forPath?: string; limit?: number } = {}): Promise<(RevisionSummary & { restorable: boolean })[]> {
|
|
569
|
+
const rows = await combined(tenant, scope, opts);
|
|
570
|
+
const have = snapshotIds(tenant, scope);
|
|
571
|
+
const stored = view && scope !== "@library" ? new Set(((await view.list(tenant, scope, { limit: 500 })) ?? []).map((r) => r.id)) : new Set<string>();
|
|
572
|
+
return rows.map((r) => ({ ...r, restorable: have.has(r.id) || stored.has(r.id) }));
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
export async function readRevision(tenant: string, scope: string, id: string, forPath?: string): Promise<Revision | null> {
|
|
576
|
+
assertSafeName(id, "revision id");
|
|
577
|
+
const fromStore = view && scope !== "@library" ? await view.read(tenant, scope, id, forPath) : null;
|
|
578
|
+
return fromStore ?? readRevisionLocal(tenant, scope, id, forPath);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
export async function snapshotAt(tenant: string, scope: string, id: string): Promise<{ path: string; content: string }[] | null> {
|
|
582
|
+
assertSafeName(id, "revision id");
|
|
583
|
+
const fromStore = view && scope !== "@library" ? await view.snapshot(tenant, scope, id) : null;
|
|
584
|
+
return fromStore ?? snapshotAtLocal(tenant, scope, id);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
export async function hasSnapshot(tenant: string, scope: string, id: string): Promise<boolean> {
|
|
588
|
+
assertSafeName(id, "revision id");
|
|
589
|
+
if (hasSnapshotLocal(tenant, scope, id)) return true;
|
|
590
|
+
return Boolean(view && scope !== "@library" && (await view.list(tenant, scope, { limit: 500 }))?.some((r) => r.id === id));
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
export async function headRevision(tenant: string, scope: string): Promise<RevisionSummary | null> {
|
|
594
|
+
return (await combined(tenant, scope, { limit: 1 }, true))[0] ?? null;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
export async function resolveRevision(tenant: string, scope: string, to: string, now = Date.now()): Promise<{ id: string; at: string; by: string; message: string } | null> {
|
|
598
|
+
return resolveIn(await combined(tenant, scope, { limit: Infinity }, true), to, now);
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
export async function changedPathsBetween(tenant: string, scope: string, from: string | null, to: string | null): Promise<string[] | null> {
|
|
602
|
+
if (!from || !to) return null;
|
|
603
|
+
if (from === to) return [];
|
|
604
|
+
return changedIn(await combined(tenant, scope, { limit: 500 }), from, to);
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
export async function latestRevisionId(tenant: string, scope: string): Promise<string | null> {
|
|
608
|
+
return (await combined(tenant, scope, { limit: 1 }))[0]?.id ?? null;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** A scope with no revision at all gets a local baseline, as before. */
|
|
612
|
+
export async function ensureBaseline(tenant: string, scope: string, by = "foldrun"): Promise<string | null> {
|
|
613
|
+
const head = await headRevision(tenant, scope);
|
|
614
|
+
return head ? head.id : ensureBaselineLocal(tenant, scope, by);
|
|
449
615
|
}
|
|
450
616
|
|
|
451
617
|
// ------------------------------------------------------------------- diff
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// Where the revision journal's entries are kept (FOL-126 phase 4, item 3).
|
|
2
|
+
//
|
|
3
|
+
// The journal (workspace-revisions.ts) writes every change down BEFORE it is
|
|
4
|
+
// queued for a commit, and removes it once committed. Until now "written down"
|
|
5
|
+
// meant a file under <data>/.revision-journal/ — on the shared volume, which
|
|
6
|
+
// the storage refactor retires. So the place is a seam:
|
|
7
|
+
//
|
|
8
|
+
// fsJournalStore the files, as before: the default, and the only one a
|
|
9
|
+
// laptop or a Compose install without a database ever has.
|
|
10
|
+
// A hosted install keeps it as a LEGACY source, replayed at
|
|
11
|
+
// boot and drained, so switching loses nothing.
|
|
12
|
+
// (platform) pgJournalStore (src/journal-pg.ts): a table, behind the
|
|
13
|
+
// same calls, registered where there is a database.
|
|
14
|
+
//
|
|
15
|
+
// The calls are synchronous (the writers that journal are), and an entry's
|
|
16
|
+
// `handle` is whatever the store needs to find it again.
|
|
17
|
+
|
|
18
|
+
import fs from "node:fs";
|
|
19
|
+
import path from "node:path";
|
|
20
|
+
|
|
21
|
+
/** What is stored: the whole entry (new content only, never the old text). */
|
|
22
|
+
export interface JournalRecord {
|
|
23
|
+
v: 1;
|
|
24
|
+
tenant: string;
|
|
25
|
+
workspace: string;
|
|
26
|
+
id: string;
|
|
27
|
+
files: { path: string; before: null; after: string | null; base?: string | null; handed?: string | null }[];
|
|
28
|
+
by: string;
|
|
29
|
+
message: string;
|
|
30
|
+
at: string;
|
|
31
|
+
restoredFrom?: string;
|
|
32
|
+
/** A run's copy-back: the revisions (workspace head, state head) its stage-in
|
|
33
|
+
* started from. Each file's base is read from these, not from the folder. */
|
|
34
|
+
baseRev?: { workspace: string | null; state: string | null };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface JournalStore {
|
|
38
|
+
/** Which store this is, for logs ("files", "database"). */
|
|
39
|
+
readonly kind: string;
|
|
40
|
+
/** Write the entry down; throws if it cannot. Returns its handle. Putting an
|
|
41
|
+
* id that is already there answers the existing handle. */
|
|
42
|
+
put(rec: JournalRecord): string;
|
|
43
|
+
/** Forget one entry. Safe to repeat. */
|
|
44
|
+
remove(tenant: string, workspace: string, handle: string): void;
|
|
45
|
+
/** Every workspace that has entries. */
|
|
46
|
+
workspaces(): { tenant: string; workspace: string }[];
|
|
47
|
+
/** One workspace's entries, oldest first, with how long each has been there. */
|
|
48
|
+
entries(tenant: string, workspace: string): { handle: string; ageMs: number }[];
|
|
49
|
+
/** Read one entry; throws for one that is torn or foreign. */
|
|
50
|
+
read(tenant: string, workspace: string, handle: string): JournalRecord;
|
|
51
|
+
/** Keep an unreadable entry out of every later replay, without destroying it. */
|
|
52
|
+
setAside(tenant: string, workspace: string, handle: string): void;
|
|
53
|
+
/** Housekeeping before a replay: debris of a write that died half way (files only). */
|
|
54
|
+
sweep(tenant: string, workspace: string, olderThanMs: number): void;
|
|
55
|
+
/** Remove everything of one workspace, or of the whole account. Safe to repeat. */
|
|
56
|
+
drop(tenant: string, workspace?: string): void;
|
|
57
|
+
/** A workspace was renamed: its entries not held by a live queue (a dead
|
|
58
|
+
* process's) now belong to the new name. Handles of entries that were
|
|
59
|
+
* moved are NOT promised to stay valid: a caller holding some forgets them
|
|
60
|
+
* first and puts them again under the new name. */
|
|
61
|
+
move(tenant: string, from: string, to: string): void;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The files: <root>/<tenant>/<workspace>/<time>-<seq>-<id>.json, tmp + rename. */
|
|
65
|
+
export function fsJournalStore(root: () => string): JournalStore {
|
|
66
|
+
let seq = 0;
|
|
67
|
+
const dirOf = (tenant: string, workspace: string) => path.join(root(), tenant, workspace);
|
|
68
|
+
return {
|
|
69
|
+
kind: "files",
|
|
70
|
+
put(rec) {
|
|
71
|
+
const dir = dirOf(rec.tenant, rec.workspace);
|
|
72
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
73
|
+
const name = `${Date.now().toString().padStart(14, "0")}-${String(seq++ % 1_000_000).padStart(6, "0")}-${rec.id}.json`;
|
|
74
|
+
const file = path.join(dir, name);
|
|
75
|
+
fs.writeFileSync(`${file}.tmp`, JSON.stringify(rec));
|
|
76
|
+
fs.renameSync(`${file}.tmp`, file);
|
|
77
|
+
return file;
|
|
78
|
+
},
|
|
79
|
+
remove(tenant, workspace, handle) {
|
|
80
|
+
try {
|
|
81
|
+
fs.rmSync(handle, { force: true });
|
|
82
|
+
fs.rmdirSync(dirOf(tenant, workspace)); // only when empty
|
|
83
|
+
} catch {
|
|
84
|
+
// not empty, or already gone
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
workspaces() {
|
|
88
|
+
const out: { tenant: string; workspace: string }[] = [];
|
|
89
|
+
let tenants: string[] = [];
|
|
90
|
+
try {
|
|
91
|
+
tenants = fs.readdirSync(root());
|
|
92
|
+
} catch {
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
for (const tenant of tenants) {
|
|
96
|
+
try {
|
|
97
|
+
for (const workspace of fs.readdirSync(path.join(root(), tenant))) out.push({ tenant, workspace });
|
|
98
|
+
} catch {
|
|
99
|
+
// not a directory
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return out;
|
|
103
|
+
},
|
|
104
|
+
entries(tenant, workspace) {
|
|
105
|
+
const dir = dirOf(tenant, workspace);
|
|
106
|
+
let names: string[] = [];
|
|
107
|
+
try {
|
|
108
|
+
names = fs.readdirSync(dir).filter((n) => n.endsWith(".json")).sort();
|
|
109
|
+
} catch {
|
|
110
|
+
return [];
|
|
111
|
+
}
|
|
112
|
+
const out: { handle: string; ageMs: number }[] = [];
|
|
113
|
+
for (const n of names) {
|
|
114
|
+
const file = path.join(dir, n);
|
|
115
|
+
try {
|
|
116
|
+
out.push({ handle: file, ageMs: Date.now() - fs.statSync(file).mtimeMs });
|
|
117
|
+
} catch {
|
|
118
|
+
// gone meanwhile
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return out;
|
|
122
|
+
},
|
|
123
|
+
read(_t, _w, handle) {
|
|
124
|
+
return JSON.parse(fs.readFileSync(handle, "utf8")) as JournalRecord;
|
|
125
|
+
},
|
|
126
|
+
setAside(_t, _w, handle) {
|
|
127
|
+
fs.renameSync(handle, `${handle}.unreadable`);
|
|
128
|
+
},
|
|
129
|
+
sweep(tenant, workspace, olderThanMs) {
|
|
130
|
+
const dir = dirOf(tenant, workspace);
|
|
131
|
+
try {
|
|
132
|
+
for (const n of fs.readdirSync(dir)) {
|
|
133
|
+
// a write that died before its rename leaves a .tmp: nothing to replay
|
|
134
|
+
if (n.endsWith(".json.tmp") && olderThanMs > 0 && Date.now() - fs.statSync(path.join(dir, n)).mtimeMs > olderThanMs) fs.rmSync(path.join(dir, n), { force: true });
|
|
135
|
+
}
|
|
136
|
+
} catch {
|
|
137
|
+
// nothing there
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
drop(tenant, workspace) {
|
|
141
|
+
fs.rmSync(workspace === undefined ? path.join(root(), tenant) : dirOf(tenant, workspace), { recursive: true, force: true });
|
|
142
|
+
},
|
|
143
|
+
move(tenant, from, to) {
|
|
144
|
+
const src = dirOf(tenant, from);
|
|
145
|
+
if (!fs.existsSync(src)) return;
|
|
146
|
+
const dest = dirOf(tenant, to);
|
|
147
|
+
fs.mkdirSync(dest, { recursive: true });
|
|
148
|
+
for (const n of fs.readdirSync(src)) fs.renameSync(path.join(src, n), path.join(dest, n));
|
|
149
|
+
fs.rmSync(src, { recursive: true, force: true });
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
}
|