{"draft":null,"from":8,"to":318,"files":[{"path":"server/src/push.ts","added":305,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/push.ts\n@@ -0,0 +1,305 @@\n+// Out to Artifacts (#8): shared's files as one git commit on main of the\n+// project's repo, with the publish message and the agent as author. The repo\n+// is created on first use. isomorphic-git works in an in-memory filesystem:\n+// a depth-1 clone of main with nothing checked out, then a new tree from\n+// shared's files that compresses and writes only what changed (abso issue 293).\n+import { createHash } from \"node:crypto\";\n+import git from \"isomorphic-git\";\n+import http from \"isomorphic-git/http/web\";\n+import type { FileModes } from \"../../worker/project/project-api.ts\";\n+import type { SqliteStorage } from \"./engine-project.ts\";\n+import { GitDiskIntake } from \"./git-disk-intake.ts\";\n+import { GitFileContents } from \"./git-file-contents.ts\";\n+import { gitHttp } from \"./git-http.ts\";\n+import { MemoryFS } from \"./memory-fs.ts\";\n+\n+export interface PushResult {\n+\trepo: string;\n+\tremote: string;\n+\tcommit: string;\n+\tversion: number;\n+\tms: number;\n+}\n+\n+/** New blob bytes per push before the push out splits into parts: Artifacts refuses a push much over 20 MB. */\n+const PUSH_BATCH = 16 * 1024 * 1024;\n+\n+/** A file as a tree entry holds it: its blob and its mode (\"100644\", \"100755\", \"120000\"). */\n+export interface TreeFile {\n+\toid: string;\n+\tmode: string;\n+}\n+\n+/** Every file in a tree, and every folder's tree oid (\"\" is the root), read from tree objects only. */\n+export async function readTreeFiles(\n+\tfs: MemoryFS,\n+\tdir: string,\n+\toid: string,\n+\tprefix = \"\",\n+\tfiles = new Map<string, TreeFile>(),\n+\ttrees = new Map<string, string>(),\n+\tcache?: object,\n+): Promise<{ files: Map<string, TreeFile>; trees: Map<string, string> }> {\n+\ttrees.set(prefix, oid);\n+\tconst { tree } = await git.readTree({ fs, dir, oid, cache });\n+\tfor (const e of tree) {\n+\t\tconst path = prefix === \"\" ? e.path : `${prefix}/${e.path}`;\n+\t\tif (e.type === \"tree\") await readTreeFiles(fs, dir, e.oid, path, files, trees, cache);\n+\t\telse if (e.type === \"blob\") files.set(path, { oid: e.oid, mode: e.mode });\n+\t}\n+\treturn { files, trees };\n+}\n+\n+/**\n+ * Hash the Git header and content separately so export does not allocate a second whole-file buffer.\n+ */\n+export async function blobOid(bytes: Uint8Array): Promise<string> {\n+\treturn createHash(\"sha1\").update(`blob ${bytes.byteLength}\\0`).update(bytes).digest(\"hex\");\n+}\n+\n+const parentOf = (path: string) => {\n+\tconst cut = path.lastIndexOf(\"/\");\n+\treturn cut < 0 ? \"\" : path.slice(0, cut);\n+};\n+\n+/**\n+ * The tree for `files`, written bottom up. A folder with nothing changed under it keeps its old tree oid (`before`),\n+ * so only the folders on a changed path are written again.\n+ */\n+export async function writeTrees(\n+\tfs: MemoryFS,\n+\tdir: string,\n+\tfiles: Map<string, TreeFile>,\n+\tbefore: Map<string, string>,\n+\tchanged: Set<string>,\n+): Promise<string> {\n+\tconst dirty = new Set<string>([\"\"]);\n+\tfor (const path of changed) for (let d = parentOf(path); d !== \"\"; d = parentOf(d)) dirty.add(d);\n+\ttype Entry = { mode: string; oid: string; type: \"blob\" | \"tree\" };\n+\tconst kids = new Map<string, Map<string, Entry>>([[\"\", new Map()]]);\n+\tconst folder = (d: string) => {\n+\t\tlet k = kids.get(d);\n+\t\tif (!k) {\n+\t\t\tkids.set(d, (k = new Map()));\n+\t\t\tif (d !== \"\") folder(parentOf(d));\n+\t\t}\n+\t\treturn k;\n+\t};\n+\tfor (const [path, f] of files)\n+\t\tfolder(parentOf(path)).set(path.slice(path.lastIndexOf(\"/\") + 1), { ...f, type: \"blob\" });\n+\t// Deepest first, so a folder's subfolders have their oids before it is written.\n+\tconst depth = (d: string) => (d === \"\" ? 0 : d.split(\"/\").length);\n+\tconst order = [...kids.keys()].sort((a, b) => depth(b) - depth(a));\n+\tlet root = \"\";\n+\tfor (const d of order) {\n+\t\tconst old = before.get(d);\n+\t\tconst oid =\n+\t\t\told !== undefined && !dirty.has(d)\n+\t\t\t\t? old\n+\t\t\t\t: await git.writeTree({ fs, dir, tree: [...kids.get(d)!].map(([path, e]) => ({ path, ...e })) });\n+\t\tif (d === \"\") root = oid;\n+\t\telse folder(parentOf(d)).set(d.slice(d.lastIndexOf(\"/\") + 1), { mode: \"040000\", oid, type: \"tree\" });\n+\t}\n+\treturn root;\n+}\n+\n+/**\n+ * A project's Artifacts repo: abso-<project>. Project names are letters, digits, \".\", \"_\" and \"-\" (validName), which\n+ * repo names take as they are.\n+ */\n+export function repoName(project: string): string {\n+\treturn `abso-${project}`;\n+}\n+\n+/** The project one of our repos holds, or null for a repo that isn't ours. */\n+export function projectOfRepo(repo: string): string | null {\n+\treturn repo.startsWith(\"abso-\") && repo.length > \"abso-\".length ? repo.slice(\"abso-\".length) : null;\n+}\n+\n+/** The repo's remote and a write token good for `seconds`, creating the repo if it's new. */\n+export async function writeAccess(\n+\tartifacts: Artifacts,\n+\tname: string,\n+\tseconds = 600,\n+): Promise<{ remote: string; secret: string }> {\n+\ttry {\n+\t\tusing repo = await artifacts.get(name);\n+\t\tconst [info, token] = await Promise.all([repo.info(), repo.createToken(\"write\", seconds)]);\n+\t\treturn { remote: info!.remote, secret: token.plaintext.split(\"?expires=\")[0]! };\n+\t} catch {\n+\t\tconst created = await artifacts.create(name, { description: `abso project ${name}`, setDefaultBranch: \"main\" });\n+\t\treturn { remote: created.remote, secret: created.token.split(\"?expires=\")[0]! };\n+\t}\n+}\n+\n+export interface SharedFiles {\n+\tversion: number;\n+\tfiles: Record<string, string>;\n+\tmodes?: FileModes;\n+\tblobs?: Record<string, string>;\n+\tlast?: { agent: string; message: string };\n+}\n+\n+/**\n+ * Shared's files as commits on top of `head` (null: a repo with no main yet), in the repo at `dir`. `part` is called\n+ * with each earlier part's commit when the new blobs are too big for one push. Answers the last commit and how many\n+ * paths changed.\n+ */\n+export async function commitShared(\n+\tfs: MemoryFS,\n+\tdir: string,\n+\thead: string | null,\n+\tshared: SharedFiles,\n+\treadBlob: (sha256: string) => Uint8Array | null,\n+\tpart: (commit: string) => Promise<void> = async () => {},\n+\tcache?: object,\n+): Promise<{ commit: string; changed: number }> {\n+\tconst old = head\n+\t\t? await readTreeFiles(\n+\t\t\t\tfs,\n+\t\t\t\tdir,\n+\t\t\t\t(await git.readCommit({ fs, dir, oid: head, cache })).commit.tree,\n+\t\t\t\t\"\",\n+\t\t\t\tnew Map(),\n+\t\t\t\tnew Map(),\n+\t\t\t\tcache,\n+\t\t\t)\n+\t\t: { files: new Map<string, TreeFile>(), trees: new Map<string, string>() };\n+\tconst blobs = shared.blobs ?? {};\n+\tconst now = new Map<string, TreeFile>();\n+\tconst changed = new Set<string>();\n+\tfor (const path of old.files.keys()) if (!(path in shared.files) && !(path in blobs)) changed.add(path);\n+\t// A file whose blob and mode match the last push keeps its entry; only a new blob is compressed and written.\n+\tconst put = async (path: string, bytes: Uint8Array, mode: string, oid: string) => {\n+\t\tconst was = old.files.get(path);\n+\t\tif (was?.oid !== oid) await git.writeBlob({ fs, dir, blob: bytes });\n+\t\tif (was?.oid !== oid || was.mode !== mode) changed.add(path);\n+\t\tnow.set(path, { oid, mode });\n+\t};\n+\t// Each file goes into the tree as a blob with its mode (#27): 100755 for exec, 120000 for a link, whose blob is\n+\t// its target.\n+\tconst enc = new TextEncoder();\n+\tconst agent = shared.last?.agent ?? \"abso\";\n+\tconst author = { name: agent, email: `${agent}@abso.invalid` };\n+\tconst committer = { name: \"abso\", email: \"abso@abso.invalid\" };\n+\tconst say = (p: string) => `${shared.last?.message ?? \"Start the project\"}${p}\\n\\nabso-version: ${shared.version}\\n`;\n+\tlet parent = head;\n+\t// A part holds what's written so far and preserves old entries for files not reached yet.\n+\tconst commitNow = async (message: string) => {\n+\t\tconst files = new Map(now);\n+\t\tfor (const [path, f] of old.files)\n+\t\t\tif (!files.has(path) && (path in blobs || path in shared.files)) files.set(path, f);\n+\t\tconst tree = await writeTrees(fs, dir, files, old.trees, changed);\n+\t\tparent = await git.commit({\n+\t\t\tcache,\n+\t\t\tfs,\n+\t\t\tdir,\n+\t\t\tmessage,\n+\t\t\tauthor,\n+\t\t\tcommitter,\n+\t\t\ttree,\n+\t\t\tparent: parent ? [parent] : [],\n+\t\t\tref: \"main\",\n+\t\t});\n+\t\treturn parent;\n+\t};\n+\t// Artifacts refuses a push much over 20 MB, so when new text or binary blobs add up\n+\t// to more than PUSH_BATCH, the earlier ones go in commits of their own\n+\t// first. Every part carries abso-version, so intake never takes them in.\n+\tlet pending = 0;\n+\tlet parts = 0;\n+\tfor (const path of Object.keys(shared.files)) {\n+\t\tconst mode = shared.modes?.[path];\n+\t\tconst link = typeof mode?.link === \"string\" ? mode.link : null;\n+\t\tconst bytes = enc.encode(link ?? shared.files[path]!);\n+\t\tconst oid = await blobOid(bytes);\n+\t\tconst fresh = old.files.get(path)?.oid !== oid;\n+\t\tif (fresh && pending > 0 && pending + bytes.byteLength > PUSH_BATCH) {\n+\t\t\tawait part(await commitNow(say(` (part ${++parts})`)));\n+\t\t\tpending = 0;\n+\t\t}\n+\t\tif (fresh) pending += bytes.byteLength;\n+\t\tawait put(path, bytes, link !== null ? \"120000\" : mode?.exec ? \"100755\" : \"100644\", oid);\n+\t}\n+\tfor (const [path, sha] of Object.entries(blobs)) {\n+\t\tconst bytes = readBlob(sha);\n+\t\tif (!bytes) throw new Error(`${path}: blob ${sha} is missing from the project's store`);\n+\t\tconst oid = await blobOid(bytes);\n+\t\tconst fresh = old.files.get(path)?.oid !== oid;\n+\t\tif (fresh && pending > 0 && pending + bytes.byteLength > PUSH_BATCH) {\n+\t\t\tawait part(await commitNow(say(` (part ${++parts})`)));\n+\t\t\tpending = 0;\n+\t\t}\n+\t\tif (fresh) pending += bytes.byteLength;\n+\t\tawait put(path, bytes, shared.modes?.[path]?.exec ? \"100755\" : \"100644\", oid);\n+\t}\n+\tconst commit = await commitNow(say(parts > 0 ? ` (part ${parts + 1}, last)` : \"\"));\n+\treturn { commit, changed: changed.size };\n+}\n+\n+export async function pushShared(\n+\tartifacts: Artifacts,\n+\tproject: string,\n+\tshared: SharedFiles,\n+\t/** A binary file's bytes by SHA-256 (#27), from the project's blob store. */\n+\treadBlob: (sha256: string) => Uint8Array | null = () => null,\n+\tdisk?: { storage: SqliteStorage; maxPackBytes: number; maxObjectBytes: number; maxDecodedBytes: number },\n+): Promise<PushResult> {\n+\tconst t0 = Date.now();\n+\tconst name = repoName(project);\n+\tconst { remote, secret } = await writeAccess(artifacts, name);\n+\tconst onAuth = () => ({ username: \"x\", password: secret });\n+\tusing contents = disk ? new GitFileContents(disk.storage, disk.maxObjectBytes, disk.maxDecodedBytes) : undefined;\n+\tusing intake = disk\n+\t\t? new GitDiskIntake(disk.storage, disk.maxPackBytes, disk.maxObjectBytes, disk.maxDecodedBytes)\n+\t\t: undefined;\n+\tconst cache = disk ? {} : undefined;\n+\tif (intake && cache) intake.attach(cache);\n+\tconst transport = disk ? gitHttp() : http;\n+\tlet fs = new MemoryFS(contents);\n+\tconst dir = \"/repo\";\n+\t// A new repo has no main yet. isomorphic-git \"clones\" an empty repo without\n+\t// an error but leaves HEAD on master, so check for main and start clean.\n+\t// Nothing is checked out: the new tree is built from tree objects (293).\n+\t// Only an explicitly absent main is an empty repository. Transport, decode,\n+\t// and size failures must never become permission to replace remote history.\n+\tconst refs = await git.listServerRefs({ http: transport, url: remote, onAuth, prefix: \"refs/heads/main\" });\n+\tlet head: string | null = null;\n+\tif (refs.some((ref) => ref.ref === \"refs/heads/main\")) {\n+\t\tawait git.clone({\n+\t\t\tfs,\n+\t\t\thttp: transport,\n+\t\t\tcache,\n+\t\t\tdir,\n+\t\t\turl: remote,\n+\t\t\tref: \"main\",\n+\t\t\tsingleBranch: true,\n+\t\t\tdepth: 1,\n+\t\t\tnoCheckout: true,\n+\t\t\tonAuth,\n+\t\t});\n+\t\tintake?.assertReady();\n+\t\thead = await git.resolveRef({ fs, dir, ref: \"main\" });\n+\t}\n+\tif (head === null) {\n+\t\tfs = new MemoryFS(contents);\n+\t\tawait git.init({ fs, dir, defaultBranch: \"main\" });\n+\t}\n+\tconst t1 = Date.now();\n+\tconst push = () => git.push({ fs, http: transport, cache, dir, url: remote, ref: \"main\", remoteRef: \"main\", onAuth });\n+\tconst { commit, changed } = await commitShared(\n+\t\tfs,\n+\t\tdir,\n+\t\thead,\n+\t\tshared,\n+\t\treadBlob,\n+\t\tasync () => void (await push()),\n+\t\tcache,\n+\t);\n+\tconst t2 = Date.now();\n+\tawait push();\n+\tconsole.log(\n+\t\t`push ${project} v${shared.version}: clone ${t1 - t0} ms, files ${t2 - t1} ms (${changed} changed), push ${Date.now() - t2} ms`,\n+\t);\n+\treturn { repo: name, remote, commit, version: shared.version, ms: Date.now() - t0 };\n+}"}],"unmatched":[]}