- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/local-store.ts?version=293&format=json
362 linespinch 100%Last change pinch in version 289, 2 versions changed it
You're reading version 293. The newest is 318, and 3 versions since then changed this file.
1// Local projects (abso init --local): the open server's own router and project object (server/src) run in this
2// process, over Node's SQLite, so a project needs no server, account or network. Each project is one SQLite file in a
3// store folder. Every call runs in one SQLite write transaction, which is the store's lock: another process's call
4// waits for it, and a process that dies mid-call leaves nothing half-written.
6import { existsSync, mkdirSync } from "node:fs";
7import { homedir } from "node:os";
8import { join, resolve } from "node:path";
9import { deserialize, serialize } from "node:v8";
10import { UsageError } from "./args.ts";
11import { fromEnv } from "./env-names.ts";
13/** The server a local folder's config names. */
14export const LOCAL = "local";
15/** The address the client's calls use for a local project; they never leave this process. */
16export const LOCAL_BASE = "http://local.abso.invalid";
17/** The shared token the in-process server is given, and that its calls carry. Not a secret: nothing listens. */
18const LOCAL_TOKEN = "local-store";
20export const isLocal = (server: string | undefined): boolean => server === LOCAL;
22type EnvMap = Readonly<Record<string, string | undefined>>;
24/**
25 * Where local projects live: the folder's own store (--store, kept in its config), else ABSO_STORE, else the OS's
26 * per-user data folder. Undefined when there is none to use (no data folder and nothing named), so nothing assumes a
27 * writable home folder.
28 */
29export function storeDir(env: EnvMap, configured?: string, cwd = process.cwd()): string | undefined {
30 if (configured) return resolve(cwd, configured);
31 const named = fromEnv(env, "STORE");
32 if (named) return resolve(cwd, named);
33 const data =
34 process.platform === "win32"
35 ? env.LOCALAPPDATA
36 : process.platform === "darwin"
37 ? env.HOME && join(env.HOME, "Library", "Application Support")
38 : env.XDG_DATA_HOME || (env.HOME ? join(env.HOME, ".local", "share") : undefined);
39 if (data) return join(data, "abso", "store");
40 try {
41 const home = homedir();
42 return home ? join(home, ".local", "share", "abso", "store") : undefined;
43 } catch {
44 return undefined;
45 }
46}
48export const NO_STORE =
49 "there's no folder for local projects here: set ABSO_STORE to one, or give abso init --local a --store <folder>";
51// --- The Workers runtime's parts the server uses, over node:sqlite -----------------------------------------------
53interface Db {
54 exec(sql: string): void;
55 prepare(sql: string): {
56 all(...args: unknown[]): unknown[];
57 run(...args: unknown[]): unknown;
58 get(...args: unknown[]): unknown;
59 columns(): unknown[];
60 };
61 close(): void;
62}
64/** A Durable Object's storage: SQL, synchronous transactions, the key-value calls and the alarm, on one database. */
65function storageOver(db: Db) {
66 db.exec(
67 "CREATE TABLE IF NOT EXISTS _local_kv (key TEXT PRIMARY KEY, value BLOB NOT NULL); CREATE TABLE IF NOT EXISTS _local_alarm (id INTEGER PRIMARY KEY CHECK (id = 0), at INTEGER)",
68 );
69 const statements = new Map<string, ReturnType<Db["prepare"]>>();
70 const prepared = (query: string) => {
71 let s = statements.get(query);
72 if (!s) {
73 s = db.prepare(query);
74 statements.set(query, s);
75 }
76 return s;
77 };
78 // Workers takes and gives BLOB columns as ArrayBuffers; node:sqlite as Uint8Arrays.
79 const bind = (v: unknown) => (v instanceof ArrayBuffer ? new Uint8Array(v) : v);
80 const out = (v: unknown) => (v instanceof Uint8Array ? v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength) : v);
81 let depth = 0;
82 const kvGet = (key: string) => {
83 const row = prepared("SELECT value FROM _local_kv WHERE key = ?").get(key) as { value: Uint8Array } | undefined;
84 return row ? deserialize(row.value) : undefined;
85 };
86 const kvPut = (key: string, value: unknown) =>
87 prepared(
88 "INSERT INTO _local_kv (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value",
89 ).run(key, serialize(value));
90 const kvDelete = (key: string) =>
91 (prepared("DELETE FROM _local_kv WHERE key = ?").run(key) as { changes: number | bigint }).changes > 0;
92 const storage = {
93 sql: {
94 exec(query: string, ...bindings: unknown[]) {
95 const statement = prepared(query);
96 const args = bindings.map(bind);
97 const rows = statement.columns().length > 0 ? statement.all(...args) : (statement.run(...args), []);
98 return {
99 toArray: () =>
100 (rows as Record<string, unknown>[]).map((r) =>
101 Object.fromEntries(Object.entries(r).map(([k, v]) => [k, out(v)])),
102 ),
103 };
104 },
105 },
106 transactionSync<T>(fn: () => T): T {
107 const name = `local_t${depth++}`;
108 db.exec(`SAVEPOINT ${name}`);
109 try {
110 const value = fn();
111 db.exec(`RELEASE ${name}`);
112 return value;
113 } catch (e) {
114 db.exec(`ROLLBACK TO ${name}; RELEASE ${name}`);
115 throw e;
116 } finally {
117 depth--;
118 }
119 },
120 async transaction<T>(fn: (txn: unknown) => Promise<T>): Promise<T> {
121 return fn(storage);
122 },
123 async get(key: string | string[]) {
124 if (typeof key === "string") return kvGet(key);
125 return new Map(key.flatMap((k) => (kvGet(k) === undefined ? [] : [[k, kvGet(k)] as const])));
126 },
127 async put(key: string | Record<string, unknown>, value?: unknown) {
128 if (typeof key === "string") kvPut(key, value);
129 else for (const [k, v] of Object.entries(key)) kvPut(k, v);
130 },
131 async delete(key: string | string[]) {
132 if (typeof key === "string") return kvDelete(key);
133 return key.filter(kvDelete).length;
134 },
135 async list(options: { prefix?: string } = {}) {
136 const rows = prepared("SELECT key, value FROM _local_kv WHERE key >= ? ORDER BY key").all(
137 options.prefix ?? "",
138 ) as { key: string; value: Uint8Array }[];
139 return new Map(
140 rows.filter((r) => r.key.startsWith(options.prefix ?? "")).map((r) => [r.key, deserialize(r.value)]),
141 );
142 },
143 // The alarm is kept, but nothing in a local project needs it: it pushes out to Artifacts, which is off here.
144 async getAlarm() {
145 const row = prepared("SELECT at FROM _local_alarm WHERE id = 0").get() as { at: number | null } | undefined;
146 return row?.at ?? null;
147 },
148 async setAlarm(at: number | Date) {
149 prepared("INSERT INTO _local_alarm (id, at) VALUES (0, ?) ON CONFLICT (id) DO UPDATE SET at = excluded.at").run(
150 Number(at),
151 );
152 },
153 async deleteAlarm() {
154 prepared("DELETE FROM _local_alarm WHERE id = 0").run();
155 },
156 };
157 return storage;
158}
160/** Workers' crypto.DigestStream, which the blob store hashes uploads with. */
161async function installDigestStream(): Promise<void> {
162 const c = globalThis.crypto as unknown as { DigestStream?: unknown };
163 if (c.DigestStream) return;
164 const { createHash } = await import("node:crypto");
165 class DigestStream extends WritableStream<Uint8Array> {
166 readonly digest: Promise<ArrayBuffer>;
167 constructor(algorithm: string) {
168 const hash = createHash(algorithm.replace("-", "").toLowerCase());
169 let done!: (b: ArrayBuffer) => void;
170 const digest = new Promise<ArrayBuffer>((ok) => {
171 done = ok;
172 });
173 super({
174 write: (chunk) => void hash.update(chunk),
175 close: () => {
176 const b = hash.digest();
177 done(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer);
178 },
179 });
180 this.digest = digest;
181 }
182 }
183 c.DigestStream = DigestStream;
184}
186// --- Loading the server's code ------------------------------------------------------------------------------------
188type Server = {
189 DatabaseSync: new (path: string) => Db;
190 handle: (request: Request, env: unknown, ctx: unknown, issues: unknown) => Promise<Response>;
191 ProjectObject: new (ctx: unknown, env: unknown) => object;
192};
193let server: Promise<Server> | undefined;
195/** Node's SQLite says it's experimental on every start; that line would land in every local command's output. */
196function quietSqliteWarning(): void {
197 const emit = process.emitWarning;
198 if ((emit as { quiet?: boolean }).quiet) return;
199 const quiet = ((warning: string | Error, ...rest: unknown[]) => {
200 const text = typeof warning === "string" ? warning : warning.message;
201 if (text.startsWith("SQLite is an experimental feature")) return;
202 return (emit as (...a: unknown[]) => void).call(process, warning, ...rest);
203 }) as typeof process.emitWarning;
204 (quiet as unknown as { quiet: boolean }).quiet = true;
205 process.emitWarning = quiet;
206}
208export const NODE_TOO_OLD = `local projects need Node 22.13 or later, for its built-in SQLite; this is Node ${process.versions.node}`;
210function loadServer(): Promise<Server> {
211 server ??= (async () => {
212 quietSqliteWarning();
213 let sqlite: { DatabaseSync: Server["DatabaseSync"] };
214 try {
215 sqlite = (await import("node:sqlite")) as unknown as typeof sqlite;
216 } catch {
217 throw new LocalError(NODE_TOO_OLD);
218 }
219 await installDigestStream();
220 // Run as .ts files, the server's `import { DurableObject } from "cloudflare:workers"` needs a stand-in. A built
221 // copy has it already: the build points the import at the same file (scripts/build-client.mjs).
222 const standIn = new URL("./durable-object-stand-in.ts", import.meta.url).href;
223 const mod = (await import("node:module")) as unknown as {
224 registerHooks?: (hooks: unknown) => unknown;
225 };
226 // The hook stays for the rest of the process: deregistering it crashes Node 24 at exit when the compile cache
227 // is on (client/avcs.ts turns it on). It answers only cloudflare:workers.
228 mod.registerHooks?.({
229 resolve(specifier: string, context: unknown, next: (s: string, c: unknown) => unknown) {
230 if (specifier === "cloudflare:workers") return { url: standIn, shortCircuit: true };
231 return next(specifier, context);
232 },
233 });
234 let loaded: typeof import("./local-server.mjs");
235 try {
236 loaded = await import("./local-server.mjs");
237 } catch (e) {
238 // Nothing is reached for here: a part of the client is missing (its packages not installed, say).
239 throw new LocalError(
240 `local projects couldn't load the server's code: ${e instanceof Error ? e.message : String(e)}`,
241 );
242 }
243 return { DatabaseSync: sqlite.DatabaseSync, handle: loaded.handle, ProjectObject: loaded.ProjectObject };
244 })();
245 return server;
246}
248/** What stops a local project from opening at all: said plainly, like a usage error. */
249export class LocalError extends UsageError {}
251// --- One store, as a fetch -----------------------------------------------------------------------------------------
253interface Open {
254 db: Db;
255 storage: ReturnType<typeof storageOver>;
256 object: object | undefined;
257 /** PRAGMA data_version when this process last used the project: it changes when another process writes. */
258 seen: number | undefined;
259}
261/** Every store file this process has open: closed when its command ends (closeLocalStores). */
262const opened = new Set<Db>();
264/** Closes every local project this process opened. Its next call opens them again. */
265export function closeLocalStores(): void {
266 for (const db of opened) {
267 try {
268 db.close();
269 } catch {}
270 }
271 opened.clear();
272}
274const PROJECT_PATH = /^\/p\/([^/]+)\//;
275const NAME = /^[A-Za-z0-9._-]{1,100}$/;
276const json = (status: number, body: unknown) => Response.json(body, { status });
278/**
279 * The fetch a local folder's calls go through: each call is answered by the open server's router, in this process,
280 * against the project's SQLite file in `dir`. Only init makes a project's file.
281 */
282export function localFetch(dir: string): (input: string, init?: RequestInit) => Promise<Response> {
283 const open = new Map<string, Open>();
284 let opening: Server | undefined;
285 const openProject = (name: string, create: boolean): Open | undefined => {
286 const existing = open.get(name);
287 if (existing && opened.has(existing.db)) return existing;
288 const folder = join(dir, name);
289 const file = join(folder, "project.sqlite");
290 if (create) mkdirSync(folder, { recursive: true });
291 else if (!existsSync(file)) return undefined;
292 const db = new opening!.DatabaseSync(file);
293 opened.add(db);
294 db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 120000; PRAGMA synchronous = NORMAL");
295 const project = { db, storage: storageOver(db), object: undefined, seen: undefined };
296 open.set(name, project);
297 return project;
298 };
299 const env = (name: string) => ({
300 ABSO_TOKEN: LOCAL_TOKEN,
301 ABSO_ARTIFACTS: "off",
302 ABSO_DISK_FIRST: "off",
303 PROJECT: {
304 idFromName: (n: string) => n,
305 get: (n: string) => {
306 const p = open.get(n);
307 if (!p || n !== name) throw new LocalError(`no local project ${n}`);
308 p.object ??= new opening!.ProjectObject(
309 { id: { toString: () => n, name: n }, storage: p.storage, waitUntil: () => {} },
310 env(name),
311 );
312 return p.object;
313 },
314 },
315 // Issues, asks and news aren't in local projects yet: a start note's issue hooks find nothing to call.
316 ISSUES_DO: { idFromName: (n: string) => n, get: () => ({}) },
317 });
318 return async (input, init = {}) => {
319 const s = await loadServer();
320 opening = s;
321 const url = new URL(input);
322 const match = PROJECT_PATH.exec(url.pathname);
323 if (!match) return json(404, { error: "a local store answers only project calls" });
324 const name = decodeURIComponent(match[1]!);
325 if (!NAME.test(name)) return json(400, { error: "project names use letters, digits, '.', '_' and '-'" });
326 const p = openProject(name, url.pathname === `/p/${match[1]}/init`);
327 if (!p) return json(404, { error: `no local project ${name} in ${dir}` });
328 const headers = new Headers(init.headers);
329 headers.set("authorization", `Bearer ${LOCAL_TOKEN}`);
330 const request = new Request(url, { ...init, headers });
331 const waits: Promise<unknown>[] = [];
332 p.db.exec("BEGIN IMMEDIATE");
333 try {
334 const version = (p.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version;
335 if (p.seen !== undefined && version !== p.seen) p.object = undefined;
336 const response = await s.handle(
337 request,
338 env(name),
339 { waitUntil: (w: Promise<unknown>) => waits.push(w) },
340 issuesNone,
341 );
342 await Promise.allSettled(waits);
343 // The answer is read whole before the write is kept, so a body that fails to arrive keeps nothing either.
344 const body = await response.arrayBuffer();
345 p.db.exec("COMMIT");
346 p.seen = (p.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version;
347 return new Response(body, { status: response.status, headers: response.headers });
348 } catch (e) {
349 try {
350 p.db.exec("ROLLBACK");
351 } catch {}
352 // What the object held in memory may be from the rolled-back call.
353 p.object = undefined;
354 p.seen = undefined;
355 if (e instanceof LocalError) throw e;
356 // Where the Workers runtime answers a throw with a 500, so does this.
357 return json(500, { error: e instanceof Error ? e.message : String(e) });
358 }
359 };
360}
362const issuesNone = async () => json(404, { error: "issues, asks and news aren't in local projects yet" });