- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/server/src/push.ts?version=166&format=json
256 linesspeed 99% · codex-capacity-chair 1%Last change codex-capacity-chair in version 166, 2 versions changed it
You're reading version 166. The newest is 318, and 2 versions since then changed this file.
1// Out to Artifacts (#8): shared's files as one git commit on main of the
2// project's repo, with the publish message and the agent as author. The repo
3// is created on first use. isomorphic-git works in an in-memory filesystem:
4// a depth-1 clone of main with nothing checked out, then a new tree from
5// shared's files that compresses and writes only what changed (abso issue 293).
6import git from "isomorphic-git";
7import http from "isomorphic-git/http/web";
8import type { FileModes } from "../../worker/project/project-api.ts";
9import { MemoryFS } from "./memory-fs.ts";
11export interface PushResult {
12 repo: string;
13 remote: string;
14 commit: string;
15 version: number;
16 ms: number;
17}
19/** New blob bytes per push before the push out splits into parts: Artifacts refuses a push much over 20 MB. */
20const PUSH_BATCH = 16 * 1024 * 1024;
22/** A file as a tree entry holds it: its blob and its mode ("100644", "100755", "120000"). */
23export interface TreeFile {
24 oid: string;
25 mode: string;
26}
28/** Every file in a tree, and every folder's tree oid ("" is the root), read from tree objects only. */
29export async function readTreeFiles(
30 fs: MemoryFS,
31 dir: string,
32 oid: string,
33 prefix = "",
34 files = new Map<string, TreeFile>(),
35 trees = new Map<string, string>(),
36): Promise<{ files: Map<string, TreeFile>; trees: Map<string, string> }> {
37 trees.set(prefix, oid);
38 const { tree } = await git.readTree({ fs, dir, oid });
39 for (const e of tree) {
40 const path = prefix === "" ? e.path : `${prefix}/${e.path}`;
41 if (e.type === "tree") await readTreeFiles(fs, dir, e.oid, path, files, trees);
42 else if (e.type === "blob") files.set(path, { oid: e.oid, mode: e.mode });
43 }
44 return { files, trees };
45}
47/**
48 * A blob's git oid, with the platform's SHA-1 (abso issue 293): native and awaited, so hashing every file of a big
49 * project neither burns the object's CPU in JavaScript nor holds its other requests back for long.
50 */
51export async function blobOid(bytes: Uint8Array): Promise<string> {
52 const head = new TextEncoder().encode(`blob ${bytes.byteLength}\0`);
53 const all = new Uint8Array(head.byteLength + bytes.byteLength);
54 all.set(head);
55 all.set(bytes, head.byteLength);
56 const d = new Uint8Array(await crypto.subtle.digest("SHA-1", all));
57 return [...d].map((b) => b.toString(16).padStart(2, "0")).join("");
58}
60const parentOf = (path: string) => {
61 const cut = path.lastIndexOf("/");
62 return cut < 0 ? "" : path.slice(0, cut);
63};
65/**
66 * The tree for `files`, written bottom up. A folder with nothing changed under it keeps its old tree oid (`before`),
67 * so only the folders on a changed path are written again.
68 */
69export async function writeTrees(
70 fs: MemoryFS,
71 dir: string,
72 files: Map<string, TreeFile>,
73 before: Map<string, string>,
74 changed: Set<string>,
75): Promise<string> {
76 const dirty = new Set<string>([""]);
77 for (const path of changed) for (let d = parentOf(path); d !== ""; d = parentOf(d)) dirty.add(d);
78 type Entry = { mode: string; oid: string; type: "blob" | "tree" };
79 const kids = new Map<string, Map<string, Entry>>([["", new Map()]]);
80 const folder = (d: string) => {
81 let k = kids.get(d);
82 if (!k) {
83 kids.set(d, (k = new Map()));
84 if (d !== "") folder(parentOf(d));
85 }
86 return k;
87 };
88 for (const [path, f] of files)
89 folder(parentOf(path)).set(path.slice(path.lastIndexOf("/") + 1), { ...f, type: "blob" });
90 // Deepest first, so a folder's subfolders have their oids before it is written.
91 const depth = (d: string) => (d === "" ? 0 : d.split("/").length);
92 const order = [...kids.keys()].sort((a, b) => depth(b) - depth(a));
93 let root = "";
94 for (const d of order) {
95 const old = before.get(d);
96 const oid =
97 old !== undefined && !dirty.has(d)
98 ? old
99 : await git.writeTree({ fs, dir, tree: [...kids.get(d)!].map(([path, e]) => ({ path, ...e })) });
100 if (d === "") root = oid;
101 else folder(parentOf(d)).set(d.slice(d.lastIndexOf("/") + 1), { mode: "040000", oid, type: "tree" });
102 }
103 return root;
104}
106/**
107 * A project's Artifacts repo: abso-<project>. Project names are letters, digits, ".", "_" and "-" (validName), which
108 * repo names take as they are.
109 */
110export function repoName(project: string): string {
111 return `abso-${project}`;
112}
114/** The project one of our repos holds, or null for a repo that isn't ours. */
115export function projectOfRepo(repo: string): string | null {
116 return repo.startsWith("abso-") && repo.length > "abso-".length ? repo.slice("abso-".length) : null;
117}
119/** The repo's remote and a write token good for `seconds`, creating the repo if it's new. */
120export async function writeAccess(
121 artifacts: Artifacts,
122 name: string,
123 seconds = 600,
124): Promise<{ remote: string; secret: string }> {
125 try {
126 using repo = await artifacts.get(name);
127 const [info, token] = await Promise.all([repo.info(), repo.createToken("write", seconds)]);
128 return { remote: info!.remote, secret: token.plaintext.split("?expires=")[0]! };
129 } catch {
130 const created = await artifacts.create(name, { description: `abso project ${name}`, setDefaultBranch: "main" });
131 return { remote: created.remote, secret: created.token.split("?expires=")[0]! };
132 }
133}
135export interface SharedFiles {
136 version: number;
137 files: Record<string, string>;
138 modes?: FileModes;
139 blobs?: Record<string, string>;
140 last?: { agent: string; message: string };
141}
143/**
144 * Shared's files as commits on top of `head` (null: a repo with no main yet), in the repo at `dir`. `part` is called
145 * with each earlier part's commit when the new blobs are too big for one push. Answers the last commit and how many
146 * paths changed.
147 */
148export async function commitShared(
149 fs: MemoryFS,
150 dir: string,
151 head: string | null,
152 shared: SharedFiles,
153 readBlob: (sha256: string) => Uint8Array | null,
154 part: (commit: string) => Promise<void> = async () => {},
155): Promise<{ commit: string; changed: number }> {
156 const old = head
157 ? await readTreeFiles(fs, dir, (await git.readCommit({ fs, dir, oid: head })).commit.tree)
158 : { files: new Map<string, TreeFile>(), trees: new Map<string, string>() };
159 const blobs = shared.blobs ?? {};
160 const now = new Map<string, TreeFile>();
161 const changed = new Set<string>();
162 for (const path of old.files.keys()) if (!(path in shared.files) && !(path in blobs)) changed.add(path);
163 // A file whose blob and mode match the last push keeps its entry; only a new blob is compressed and written.
164 const put = async (path: string, bytes: Uint8Array, mode: string, oid: string) => {
165 const was = old.files.get(path);
166 if (was?.oid !== oid) await git.writeBlob({ fs, dir, blob: bytes });
167 if (was?.oid !== oid || was.mode !== mode) changed.add(path);
168 now.set(path, { oid, mode });
169 };
170 // Each file goes into the tree as a blob with its mode (#27): 100755 for exec, 120000 for a link, whose blob is
171 // its target.
172 const enc = new TextEncoder();
173 for (const path of Object.keys(shared.files)) {
174 const mode = shared.modes?.[path];
175 const link = typeof mode?.link === "string" ? mode.link : null;
176 const bytes = enc.encode(link ?? shared.files[path]!);
177 await put(path, bytes, link !== null ? "120000" : mode?.exec ? "100755" : "100644", await blobOid(bytes));
178 }
179 const agent = shared.last?.agent ?? "abso";
180 const author = { name: agent, email: `${agent}@abso.invalid` };
181 const committer = { name: "abso", email: "abso@abso.invalid" };
182 const say = (p: string) => `${shared.last?.message ?? "Start the project"}${p}\n\nabso-version: ${shared.version}\n`;
183 let parent = head;
184 // A part holds what's written so far, and the last push's entries for the binary files not reached yet.
185 const commitNow = async (message: string) => {
186 const files = new Map(now);
187 for (const [path, f] of old.files) if (!files.has(path) && path in blobs) files.set(path, f);
188 const tree = await writeTrees(fs, dir, files, old.trees, changed);
189 parent = await git.commit({
190 fs,
191 dir,
192 message,
193 author,
194 committer,
195 tree,
196 parent: parent ? [parent] : [],
197 ref: "main",
198 });
199 return parent;
200 };
201 // Binary files (#27) aren't in files: their bytes come from the blob store.
202 // Artifacts refuses a push much over 20 MB, so when the new blobs add up
203 // to more than PUSH_BATCH, the earlier ones go in commits of their own
204 // first. Every part carries abso-version, so intake never takes them in.
205 let pending = 0;
206 let parts = 0;
207 for (const [path, sha] of Object.entries(blobs)) {
208 const bytes = readBlob(sha);
209 if (!bytes) throw new Error(`${path}: blob ${sha} is missing from the project's store`);
210 const oid = await blobOid(bytes);
211 const fresh = old.files.get(path)?.oid !== oid;
212 if (fresh && pending > 0 && pending + bytes.byteLength > PUSH_BATCH) {
213 await part(await commitNow(say(` (part ${++parts})`)));
214 pending = 0;
215 }
216 if (fresh) pending += bytes.byteLength;
217 await put(path, bytes, shared.modes?.[path]?.exec ? "100755" : "100644", oid);
218 }
219 const commit = await commitNow(say(parts > 0 ? ` (part ${parts + 1}, last)` : ""));
220 return { commit, changed: changed.size };
221}
223export async function pushShared(
224 artifacts: Artifacts,
225 project: string,
226 shared: SharedFiles,
227 /** A binary file's bytes by SHA-256 (#27), from the project's blob store. */
228 readBlob: (sha256: string) => Uint8Array | null = () => null,
229): Promise<PushResult> {
230 const t0 = Date.now();
231 const name = repoName(project);
232 const { remote, secret } = await writeAccess(artifacts, name);
233 const onAuth = () => ({ username: "x", password: secret });
234 let fs = new MemoryFS();
235 const dir = "/repo";
236 // A new repo has no main yet. isomorphic-git "clones" an empty repo without
237 // an error but leaves HEAD on master, so check for main and start clean.
238 // Nothing is checked out: the new tree is built from tree objects (293).
239 const head = await git
240 .clone({ fs, http, dir, url: remote, ref: "main", singleBranch: true, depth: 1, noCheckout: true, onAuth })
241 .then(() => git.resolveRef({ fs, dir, ref: "main" }))
242 .catch(() => null);
243 if (head === null) {
244 fs = new MemoryFS();
245 await git.init({ fs, dir, defaultBranch: "main" });
246 }
247 const t1 = Date.now();
248 const push = () => git.push({ fs, http, dir, url: remote, ref: "main", remoteRef: "main", onAuth });
249 const { commit, changed } = await commitShared(fs, dir, head, shared, readBlob, async () => void (await push()));
250 const t2 = Date.now();
251 await push();
252 console.log(
253 `push ${project} v${shared.version}: clone ${t1 - t0} ms, files ${t2 - t1} ms (${changed} changed), push ${Date.now() - t2} ms`,
254 );
255 return { repo: name, remote, commit, version: shared.version, ms: Date.now() - t0 };
256}