// Where the engine's state lives. One interface, three implementations: // memoryStore() for tests // fileStore() for the local server: one JSON file // blobStore() for Vercel: one private blob, written with a conditional write // A store is { load() -> {data, etag}, save(data, etag) -> true | false }. save() answers false when the state // changed since that load: the caller then reads again and redoes its work on the fresh state. That retry is what // keeps two serverless invocations from both spending the same credits or both starting a fourth instance. import { createHash } from "node:crypto"; import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; import { dirname } from "node:path"; import { emptyState } from "./engine.mjs"; const tag = (text) => createHash("sha1").update(text).digest("hex"); /** In memory. `initial` may be a state object; without one it starts empty. */ export function memoryStore(initial) { let text = JSON.stringify(initial ?? emptyState()); const s = { loads: 0, saves: 0, conflicts: 0, async load() { s.loads++; return { data: JSON.parse(text), etag: tag(text) }; }, async save(data, etag) { if (etag !== tag(text)) { s.conflicts++; return false; } text = JSON.stringify(data); s.saves++; return true; }, peek: () => JSON.parse(text), }; return s; } /** One JSON file, for a single local process. A missing file is an empty state: this store is never used online. */ export function fileStore(path) { const read = () => (existsSync(path) ? readFileSync(path, "utf8") : JSON.stringify(emptyState())); return { async load() { const text = read(); return { data: JSON.parse(text), etag: tag(text) }; }, async save(data, etag) { if (etag !== tag(read())) return false; mkdirSync(dirname(path), { recursive: true }); writeFileSync(path + ".tmp", JSON.stringify(data)); renameSync(path + ".tmp", path); return true; }, }; } export class StateMissing extends Error { constructor() { super("the state blob does not exist yet"); this.code = "state-missing"; } } /** * One private Vercel Blob. Three things learned the hard way on the Dark engine, kept here: * - a read may carry a weak ETag (W/"..."); the conditional write wants the strong form; * - the blob must exist before first use (scripts/init-state.mjs creates it once). A missing blob is an error, * never an empty state: otherwise a slow read right after creation would start again from nothing and * wipe every balance; * - reads are never cached. * @param {{path?:string, sdk?:object}} o `sdk` is @vercel/blob ({get, put, BlobPreconditionFailedError}); tests pass a stand-in */ export function blobStore(o = {}) { const path = o.path ?? "idle-gpu/state.json"; let sdk = o.sdk ?? null; const lib = async () => (sdk ??= await import("@vercel/blob")); return { async load() { const { get } = await lib(); const r = await get(path, { access: "private", useCache: false }); if (!r || r.statusCode !== 200) throw new StateMissing(); return { data: JSON.parse(await new Response(r.stream).text()), etag: r.blob.etag.replace(/^W\//, "") }; }, async save(data, etag) { const { put, BlobPreconditionFailedError } = await lib(); try { await put(path, JSON.stringify(data), { access: "private", addRandomSuffix: false, contentType: "application/json", ifMatch: etag, allowOverwrite: true }); return true; } catch (e) { if (e instanceof BlobPreconditionFailedError) return false; throw e; } }, }; } export class Busy extends Error { constructor() { super("the state kept changing; try again"); this.code = "busy"; } } /** * Read, act, write if something changed, start over if someone else wrote first. * `fn(state)` is synchronous, changes the state in place and returns what the caller wants back. * @param {{sleep?:(ms:number)=>Promise, tries?:number}} o */ export async function transact(store, fn, o = {}) { const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))); const tries = o.tries ?? 8; for (let i = 0; i < tries; i++) { const got = await store.load(); const state = got.data; const before = JSON.stringify(state); const out = fn(state); if (JSON.stringify(state) === before || (await store.save(state, got.etag))) return out; await sleep(15 + Math.random() * 50 * (i + 1)); } throw new Busy(); }