Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

560 lines · 31.9 KBRaw History
1import type { Env } from "../env.js";
2import { uuidPattern } from "../http/gh.js";
3import { dropStaged, finalKey, runComposeStep, stagingPrefix, stepKeys, type BlobBucket, type ComposeStep } from "../lib/blob-store.js";
4import { READ_ALL, roleForPermissions, type JobPermissions } from "../lib/job-permissions.js";
5import { legacyArtifactKeys } from "../lib/storage-keys.js";
6import { HttpError, now } from "../lib/util.js";
7import type { RepoDO } from "./RepoDO.js";
8import type { Role } from "./types.js";
9
10/**
11 * Metadata for the Actions runtime services: GitHub's cache service (keys,
12 * versions and branch scopes) and artifact service (per-run artifacts with
13 * numeric ids and retention). The Worker (http/actions-runtime.ts) handles the
14 * wire protocols and moves the bytes; this module decides what may be read or
15 * written. Every call made with a runtime token names the job, and works only
16 * while that job is running.
17 *
18 * Artifacts that older runners upload through the runner API (a tarball per
19 * name, stored at its legacy key) are recorded here too, as `legacy` rows, so
20 * they get numeric ids, are listed, counted, expired and deleted like the
21 * others. The toolkit's own listing leaves them out, as GitHub's v4 service
22 * leaves out v3 artifacts.
23 */
24
25export type CacheEntry = { id: number; key: string; version: string; scope: string; size: number; createdAt: string; lastUsed: string; etag: string | null };
26export type ArtifactEntry = { id: number; runId: string; runNumber: number; headBranch: string; headSha: string; jobId: string; name: string; size: number; digest: string | null; mimeType: string; createdAt: string; updatedAt: string; expiresAt: string; expired: boolean; etag: string | null; legacy: boolean };
27
28export type JobScope = {
29 runId: string;
30 jobId: string;
31 /** Cache scopes the job may read: its own ref first (also writable), then the PR base and the default branch. */
32 scopes: string[];
33};
34
35type CacheRow = { id: number; key: string; version: string; scope: string; size: number; status: string; job_id: string | null; created_at: string; last_used: string; staged: number; etag: string | null };
36type ArtifactRow = { id: number; run_id: string; job_id: string; name: string; size: number; digest: string | null; mime_type: string; status: string; created_at: string; updated_at: string; expires_at: string; staged: number; etag: string | null; legacy: number };
37
38/** Per-repository cache budget, and how long an unused entry is kept (GitHub's limits). */
39export const CACHE_LIMIT_BYTES = 10 * 1024 ** 3;
40export const CACHE_IDLE_MS = 7 * 24 * 3600_000;
41/** Artifact retention: `retention-days` is clamped to 1..90 days, GitHub's default maximum. */
42export const MAX_RETENTION_DAYS = 90;
43/** How long an expired artifact stays listed (as `expired: true`) after its content is deleted. */
44const EXPIRED_LISTED_DAYS = 90;
45/** Artifact storage per repository unless ARTIFACT_QUOTA_BYTES says otherwise. */
46export const DEFAULT_ARTIFACT_QUOTA = 10 * 1024 ** 3;
47/** Largest block, chunk or single-request upload accepted. */
48export const MAX_UPLOAD_PART = 256 * 1024 * 1024;
49
50const toCache = (r: CacheRow): CacheEntry => ({ id: r.id, key: r.key, version: r.version, scope: r.scope, size: r.size, createdAt: r.created_at, lastUsed: r.last_used, etag: r.etag });
51
52/** Where an artifact's content is: its object, or an older runner's tarball (the current key, then the old layout's). */
53export function artifactObjectKeys(repo: string, a: Pick<ArtifactEntry, "id" | "runId" | "name" | "legacy">): string[] {
54 return a.legacy ? legacyArtifactKeys(repo, a.runId, a.name) : [finalKey({ repo, kind: "artifact", id: a.id })];
55}
56
57/** The file an artifact downloads as: a zip, a single unarchived file, or an older runner's tarball. */
58export function artifactFileName(a: Pick<ArtifactEntry, "name" | "mimeType" | "legacy">): string {
59 return a.legacy ? `${a.name}.tar.gz` : a.mimeType === "application/zip" ? `${a.name}.zip` : a.name;
60}
61
62export class Runtime {
63 constructor(
64 private repo: RepoDO,
65 private env: Env,
66 ) {}
67
68 private get sql() {
69 return this.repo.sql;
70 }
71
72 private get bucket(): BlobBucket {
73 return this.env.BUCKET as unknown as BlobBucket;
74 }
75
76 private get repoId(): string {
77 return this.repo.meta.repoId;
78 }
79
80 /** Artifact storage this repository may use (live artifacts plus uploads in progress). */
81 get artifactQuota(): number {
82 const n = Number(this.env.ARTIFACT_QUOTA_BYTES);
83 return Number.isSafeInteger(n) && n > 0 ? n : DEFAULT_ARTIFACT_QUOTA;
84 }
85
86 // ---------------------------------------------------------------- jobs
87
88 /** The job a runtime token names, if it is still running. */
89 job(jobId: string, runId?: string): JobScope {
90 const j = this.sql
91 .exec<{ status: string; run_id: string; ref: string; event_payload: string }>("SELECT j.status, j.run_id, r.ref, r.event_payload FROM jobs j JOIN runs r ON r.id = j.run_id WHERE j.id = ?", jobId)
92 .toArray()[0];
93 if (!j || j.status !== "in_progress" || (runId && runId !== j.run_id)) throw new HttpError(401, "the job is not running");
94 // Pull requests also read their base branch's caches, and merge groups their target branch's.
95 let base: string | undefined;
96 try {
97 const p = JSON.parse(j.event_payload) as { pull_request?: { base?: { ref?: string } }; merge_group?: { base_ref?: string } };
98 base = p.pull_request?.base?.ref ?? p.merge_group?.base_ref?.replace(/^refs\/heads\//, "");
99 } catch {
100 /* no payload */
101 }
102 const scopes = [j.ref, ...(base ? [`refs/heads/${base}`] : []), `refs/heads/${this.repo.meta.defaultBranch}`];
103 return { runId: j.run_id, jobId, scopes: [...new Set(scopes)] };
104 }
105
106 /** Records what the job token may do (its effective `permissions:`, set when the job starts). */
107 grant(jobId: string, perms: JobPermissions): void {
108 this.sql.exec("INSERT OR REPLACE INTO job_grants (job_id, role, permissions) VALUES (?, ?, ?)", jobId, roleForPermissions(perms), JSON.stringify(perms));
109 }
110
111 /** What a job token may do; read-only for a job that has not started. */
112 grantFor(jobId: string): { role: Role; permissions: JobPermissions } {
113 const r = this.sql.exec<{ role: Role; permissions: string }>("SELECT role, permissions FROM job_grants WHERE job_id = ?", jobId).toArray()[0];
114 return r ? { role: r.role, permissions: { ...READ_ALL, ...(JSON.parse(r.permissions) as Partial<JobPermissions>) } } : { role: "read", permissions: { ...READ_ALL } };
115 }
116
117 // ---------------------------------------------------------------- cache
118
119 /**
120 * GitHub's lookup order: in each scope (own ref, PR base, default branch),
121 * an exact match of the primary key, then the newest entry whose key starts
122 * with it, then the same for each restore key. The version must match.
123 */
124 cacheLookup(jobId: string, keys: string[], version: string): CacheEntry | null {
125 const { scopes } = this.job(jobId);
126 for (const scope of scopes) {
127 for (const key of keys) {
128 const exact = this.sql.exec<CacheRow>("SELECT * FROM rt_caches WHERE key = ? AND version = ? AND scope = ? AND status = 'ready'", key, version, scope).toArray()[0];
129 const hit =
130 exact ??
131 this.sql
132 .exec<CacheRow>("SELECT * FROM rt_caches WHERE substr(key, 1, ?) = ? AND version = ? AND scope = ? AND status = 'ready' ORDER BY created_at DESC, id DESC LIMIT 1", key.length, key, version, scope)
133 .toArray()[0];
134 if (hit) {
135 this.sql.exec("UPDATE rt_caches SET last_used = ? WHERE id = ?", now(), hit.id);
136 return toCache(hit);
137 }
138 }
139 }
140 return null;
141 }
142
143 /** Reserves `key` in the job's own scope. Returns null when an entry already exists there. */
144 async cacheReserve(jobId: string, key: string, version: string): Promise<{ id: number } | null> {
145 const { scopes } = this.job(jobId);
146 if (!key || key.length > 512 || key.includes(",")) throw new HttpError(400, "invalid cache key");
147 if (!/^[0-9a-f]{1,128}$/i.test(version)) throw new HttpError(400, "invalid cache version");
148 const scope = scopes[0]!;
149 const existing = this.sql.exec<CacheRow>("SELECT * FROM rt_caches WHERE key = ? AND version = ? AND scope = ?", key, version, scope).toArray()[0];
150 if (existing) {
151 // A reservation abandoned by a job that has finished can be taken over.
152 const holder = existing.job_id ? this.sql.exec<{ status: string }>("SELECT status FROM jobs WHERE id = ?", existing.job_id).toArray()[0] : undefined;
153 if (existing.status === "ready" || holder?.status === "in_progress") return null;
154 this.sql.exec("DELETE FROM rt_caches WHERE id = ?", existing.id);
155 await this.dropObjects("cache", [existing.id]);
156 }
157 await this.evictCaches();
158 const t = now();
159 this.sql.exec("INSERT INTO rt_caches (key, version, scope, size, status, job_id, created_at, last_used) VALUES (?, ?, ?, 0, 'reserved', ?, ?, ?)", key, version, scope, jobId, t, t);
160 return { id: this.sql.exec<{ id: number }>("SELECT last_insert_rowid() AS id").one().id };
161 }
162
163 /** The job's own reservation, by id or by key and version. */
164 cacheReservation(jobId: string, ref: { id?: number; key?: string; version?: string }): CacheEntry | null {
165 const row =
166 ref.id !== undefined
167 ? this.sql.exec<CacheRow>("SELECT * FROM rt_caches WHERE id = ?", ref.id).toArray()[0]
168 : this.sql.exec<CacheRow>("SELECT * FROM rt_caches WHERE key = ? AND version = ? AND job_id = ? AND status = 'reserved' ORDER BY id DESC LIMIT 1", ref.key ?? "", ref.version ?? "", jobId).toArray()[0];
169 if (!row || row.job_id !== jobId || row.status !== "reserved") return null;
170 this.job(jobId);
171 return toCache(row);
172 }
173
174 /** Whether entry `id`'s content may still be written (it is reserved by a running job). */
175 cacheWritable(id: number): boolean {
176 const r = this.sql.exec<{ status: string; job: string | null }>("SELECT c.status, j.status AS job FROM rt_caches c LEFT JOIN jobs j ON j.id = c.job_id WHERE c.id = ?", id).toArray()[0];
177 return !!r && r.status === "reserved" && r.job === "in_progress";
178 }
179
180 /** Bytes of committed entries plus everything staged by uploads in progress. */
181 private cacheBytes(): number {
182 return this.sql.exec<{ n: number | null }>("SELECT sum(CASE WHEN status = 'ready' THEN size ELSE staged END) AS n FROM rt_caches").one().n ?? 0;
183 }
184
185 /** Bytes of live artifacts (from both upload paths) plus everything staged by uploads in progress. */
186 private artifactBytes(): number {
187 return this.sql.exec<{ n: number | null }>("SELECT sum(CASE WHEN status = 'ready' THEN size ELSE staged END) AS n FROM rt_artifacts WHERE status != 'ready' OR expires_at > ?", now()).one().n ?? 0;
188 }
189
190 /**
191 * Accounts for `bytes` an upload is about to stage (a block, a chunk or a whole
192 * blob), before they are written. The upload must belong to a running job and
193 * stay within the repository's budget: for caches, the least recently used
194 * entries are evicted to make room; artifacts have a quota and are refused beyond it.
195 */
196 async stage(kind: "cache" | "artifact", id: number, bytes: number): Promise<void> {
197 if (!Number.isSafeInteger(bytes) || bytes < 0) throw new HttpError(400, "invalid length");
198 if (bytes > MAX_UPLOAD_PART) throw new HttpError(413, `a single upload request may carry at most ${MAX_UPLOAD_PART} bytes`);
199 if (kind === "cache") {
200 if (!this.cacheWritable(id)) throw new HttpError(409, "this upload is finished or its job is no longer running");
201 const own = this.sql.exec<{ staged: number }>("SELECT staged FROM rt_caches WHERE id = ?", id).one().staged;
202 if (own + bytes > CACHE_LIMIT_BYTES) throw new HttpError(413, `a cache entry may be at most ${CACHE_LIMIT_BYTES} bytes`);
203 if (this.cacheBytes() + bytes > CACHE_LIMIT_BYTES) await this.evictCaches(bytes);
204 if (this.cacheBytes() + bytes > CACHE_LIMIT_BYTES) throw new HttpError(413, "uploads in progress use the repository's whole cache budget");
205 this.sql.exec("UPDATE rt_caches SET staged = staged + ? WHERE id = ?", bytes, id);
206 return;
207 }
208 if (!this.artifactWritable(id)) throw new HttpError(409, "this upload is finished or its job is no longer running");
209 await this.expireArtifacts();
210 if (this.artifactBytes() + bytes > this.artifactQuota) throw new HttpError(413, `the repository's artifact storage quota (${this.artifactQuota} bytes) is used up; delete artifacts or wait for them to expire`);
211 this.sql.exec("UPDATE rt_artifacts SET staged = staged + ? WHERE id = ?", bytes, id);
212 }
213
214 /** Gives back what `stage` counted for a write that then failed, so a failed upload doesn't hold quota. */
215 unstage(kind: "cache" | "artifact", id: number, bytes: number): void {
216 if (!Number.isSafeInteger(bytes) || bytes <= 0) return;
217 this.sql.exec(`UPDATE ${kind === "cache" ? "rt_caches" : "rt_artifacts"} SET staged = max(0, staged - ?) WHERE id = ?`, bytes, id);
218 }
219
220 /** Bytes an older runner's artifact upload may still store under the quota. */
221 async artifactRoom(): Promise<number> {
222 await this.expireArtifacts();
223 return Math.max(0, this.artifactQuota - this.artifactBytes());
224 }
225
226 /** Whether `size` committed bytes for upload `id` fit the budget (evicting caches to make room). */
227 async checkCommitSize(kind: "cache" | "artifact", id: number, size: number): Promise<void> {
228 if (!Number.isSafeInteger(size) || size < 0) throw new HttpError(400, "invalid size");
229 if (kind === "cache") {
230 if (size > CACHE_LIMIT_BYTES) throw new HttpError(413, `a cache entry may be at most ${CACHE_LIMIT_BYTES} bytes`);
231 const own = this.sql.exec<{ staged: number }>("SELECT staged FROM rt_caches WHERE id = ?", id).toArray()[0]?.staged ?? 0;
232 if (this.cacheBytes() - own + size > CACHE_LIMIT_BYTES) await this.evictCaches(size - own);
233 if (this.cacheBytes() - own + size > CACHE_LIMIT_BYTES) throw new HttpError(413, "the repository's cache budget is used up by uploads in progress");
234 return;
235 }
236 const own = this.sql.exec<{ staged: number }>("SELECT staged FROM rt_artifacts WHERE id = ?", id).toArray()[0]?.staged ?? 0;
237 if (this.artifactBytes() - own + size > this.artifactQuota) throw new HttpError(413, `the repository's artifact storage quota (${this.artifactQuota} bytes) is used up`);
238 }
239
240 /** Commits a reservation; `etag` is the object's, so a later overwrite is detected and refused. */
241 async cacheCommit(jobId: string, id: number, size: number, etag: string): Promise<CacheEntry> {
242 const r = this.cacheReservation(jobId, { id });
243 if (!r) throw new HttpError(404, "cache reservation not found");
244 try {
245 await this.checkCommitSize("cache", id, size);
246 } catch (e) {
247 this.sql.exec("DELETE FROM rt_caches WHERE id = ?", id);
248 await this.dropObjects("cache", [id]);
249 throw e;
250 }
251 const t = now();
252 this.sql.exec("UPDATE rt_caches SET status = 'ready', size = ?, staged = 0, etag = ?, created_at = ?, last_used = ? WHERE id = ?", size, etag, t, t, id);
253 return { ...r, size, etag, createdAt: t, lastUsed: t };
254 }
255
256 cacheGet(id: number): CacheEntry | null {
257 const r = this.sql.exec<CacheRow>("SELECT * FROM rt_caches WHERE id = ? AND status = 'ready'", id).toArray()[0];
258 return r ? toCache(r) : null;
259 }
260
261 /** An entry whose object is gone: forget it, so lookups move on to the next match. */
262 async cacheMissing(id: number): Promise<void> {
263 await this.deleteCacheIds([id]);
264 }
265
266 /**
267 * Drops entries unused for a week, then the least recently used ones until
268 * committed entries and uploads in progress fit the budget with `room` to spare.
269 */
270 private async evictCaches(room = 0): Promise<void> {
271 const stale = this.sql.exec<{ id: number }>("SELECT id FROM rt_caches WHERE status = 'ready' AND last_used < ?", new Date(Date.now() - CACHE_IDLE_MS).toISOString()).toArray().map((r) => r.id);
272 let total = this.cacheBytes() + room;
273 const over: number[] = [];
274 for (const r of this.sql.exec<{ id: number; size: number }>("SELECT id, size FROM rt_caches WHERE status = 'ready' ORDER BY last_used, id").toArray()) {
275 if (stale.includes(r.id)) total -= r.size;
276 else if (total > CACHE_LIMIT_BYTES) {
277 over.push(r.id);
278 total -= r.size;
279 }
280 }
281 await this.deleteCacheIds([...stale, ...over]);
282 }
283
284 private async deleteCacheIds(ids: number[]): Promise<void> {
285 if (!ids.length) return;
286 for (const id of ids) this.sql.exec("DELETE FROM rt_caches WHERE id = ?", id);
287 await this.dropObjects("cache", ids, false);
288 }
289
290 /** Deletes the objects of dropped rows: the final object and, for unfinished uploads, what they staged. */
291 private async dropObjects(kind: "cache" | "artifact", ids: number[], staged = true): Promise<void> {
292 const keys = ids.map((id) => finalKey({ repo: this.repoId, kind, id }));
293 for (let i = 0; i < keys.length; i += 1000) await this.bucket.delete(keys.slice(i, i + 1000));
294 // A page of staged objects per upload; the lifecycle rule on actions-staging/ takes any rest.
295 if (staged) for (const id of ids.slice(0, 20)) await dropStaged(this.bucket, { repo: this.repoId, kind, id });
296 }
297
298 /** Deletes older runners' tarballs (both layouts' keys). */
299 private async dropLegacyArtifacts(rows: Array<{ runId: string; name: string }>): Promise<void> {
300 const keys = rows.flatMap((r) => legacyArtifactKeys(this.repoId, r.runId, r.name));
301 for (let i = 0; i < keys.length; i += 1000) await this.bucket.delete(keys.slice(i, i + 1000));
302 }
303
304 /**
305 * When a job ends, its unfinished uploads go: their rows, so they stop counting
306 * against the budgets, and their objects.
307 */
308 async sweepJob(jobId: string, o: { restart?: boolean } = {}): Promise<void> {
309 // A job starting again from the beginning (the platform replaced its runner) drops what it finished uploading too.
310 const caches = this.sql.exec<{ id: number }>(`SELECT id FROM rt_caches WHERE job_id = ?${o.restart ? "" : " AND status = 'reserved'"}`, jobId).toArray().map((r) => r.id);
311 const artifacts = this.sql.exec<{ id: number }>(`SELECT id FROM rt_artifacts WHERE job_id = ?${o.restart ? "" : " AND status = 'uploading'"}`, jobId).toArray().map((r) => r.id);
312 for (const id of caches) this.sql.exec("DELETE FROM rt_caches WHERE id = ?", id);
313 for (const id of artifacts) this.sql.exec("DELETE FROM rt_artifacts WHERE id = ?", id);
314 if (caches.length) await this.dropObjects("cache", caches);
315 if (artifacts.length) await this.dropObjects("artifact", artifacts);
316 await this.expireArtifacts();
317 }
318
319 /**
320 * One step of composing an upload (lib/blob-store.ts), run here so that it gets
321 * an invocation, and subrequests, of its own. It may only touch this upload's
322 * staging area and final object, while the upload is in progress.
323 */
324 async composeStep(ref: { kind: "cache" | "artifact"; id: number }, step: ComposeStep, contentType?: string): Promise<Array<{ partNumber: number; etag: string }>> {
325 const writable = ref.kind === "cache" ? this.cacheWritable(ref.id) : this.artifactWritable(ref.id);
326 if (!writable) throw new HttpError(409, "this upload is finished or its job is no longer running");
327 const b = { repo: this.repoId, kind: ref.kind, id: ref.id };
328 if (!stepKeys(step).every((k) => k === finalKey(b) || k.startsWith(stagingPrefix(b)))) throw new HttpError(400, "the step names objects outside this upload");
329 return runComposeStep(this.bucket, step, contentType);
330 }
331
332 /** REST: GET /actions/caches (newest first). */
333 listCaches(o: { key?: string; ref?: string; sort?: string; direction?: string; page?: number; perPage?: number }): { total: number; caches: CacheEntry[] } {
334 const where = ["status = 'ready'"];
335 const args: unknown[] = [];
336 if (o.key) {
337 where.push("substr(key, 1, ?) = ?");
338 args.push(o.key.length, o.key);
339 }
340 if (o.ref) {
341 where.push("scope = ?");
342 args.push(o.ref);
343 }
344 const col = o.sort === "size_in_bytes" ? "size" : o.sort === "created_at" ? "created_at" : "last_used";
345 const dir = o.direction === "asc" ? "ASC" : "DESC";
346 const w = `WHERE ${where.join(" AND ")}`;
347 const total = this.sql.exec<{ n: number }>(`SELECT count(*) AS n FROM rt_caches ${w}`, ...args).one().n;
348 const per = Math.min(Math.max(o.perPage ?? 30, 1), 100);
349 const rows = this.sql.exec<CacheRow>(`SELECT * FROM rt_caches ${w} ORDER BY ${col} ${dir}, id ${dir} LIMIT ? OFFSET ?`, ...args, per, (Math.max(o.page ?? 1, 1) - 1) * per).toArray();
350 return { total, caches: rows.map(toCache) };
351 }
352
353 /** REST: DELETE /actions/caches?key=&ref= or /actions/caches/:id. */
354 async deleteCaches(o: { id?: number; key?: string; ref?: string }): Promise<CacheEntry[]> {
355 const rows =
356 o.id !== undefined
357 ? this.sql.exec<CacheRow>("SELECT * FROM rt_caches WHERE id = ? AND status = 'ready'", o.id).toArray()
358 : this.sql.exec<CacheRow>("SELECT * FROM rt_caches WHERE key = ? AND status = 'ready'" + (o.ref ? " AND scope = ?" : ""), ...(o.ref ? [o.key ?? "", o.ref] : [o.key ?? ""])).toArray();
359 await this.deleteCacheIds(rows.map((r) => r.id));
360 return rows.map(toCache);
361 }
362
363 cacheUsage(): { count: number; size: number } {
364 const r = this.sql.exec<{ n: number; s: number | null }>("SELECT count(*) AS n, sum(size) AS s FROM rt_caches WHERE status = 'ready'").one();
365 return { count: r.n, size: r.s ?? 0 };
366 }
367
368 // ---------------------------------------------------------------- artifacts
369
370 private toArtifact = (r: ArtifactRow): ArtifactEntry => {
371 const run = this.sql.exec<{ n: number; ref: string; sha: string }>("SELECT run_number AS n, ref, sha FROM runs WHERE id = ?", r.run_id).toArray()[0];
372 return {
373 id: r.id,
374 runId: r.run_id,
375 runNumber: run?.n ?? 0,
376 headBranch: (run?.ref ?? "").replace(/^refs\/(heads|tags)\//, ""),
377 headSha: run?.sha ?? "",
378 jobId: r.job_id,
379 name: r.name,
380 size: r.size,
381 digest: r.digest,
382 mimeType: r.mime_type,
383 createdAt: r.created_at,
384 updatedAt: r.updated_at,
385 expiresAt: r.expires_at,
386 expired: r.status === "expired" || r.expires_at <= now(),
387 etag: r.etag,
388 legacy: r.legacy === 1,
389 };
390 };
391
392 async artifactCreate(jobId: string, name: string, mimeType: string | undefined, expiresAt: string | undefined): Promise<{ id: number }> {
393 const { runId } = this.job(jobId);
394 if (!name || name.length > 256 || /[":<>|*?\\/\r\n]/.test(name)) throw new HttpError(400, `invalid artifact name: ${name}`);
395 await this.expireArtifacts();
396 const existing = this.sql.exec<ArtifactRow>("SELECT * FROM rt_artifacts WHERE run_id = ? AND name = ?", runId, name).toArray();
397 if (existing.some((a) => a.status === "ready")) throw new HttpError(409, `an artifact with this name already exists on the workflow run`);
398 // Unfinished uploads (a crashed earlier attempt) are replaced, objects and all.
399 for (const a of existing) this.sql.exec("DELETE FROM rt_artifacts WHERE id = ?", a.id);
400 if (existing.length) await this.dropObjects("artifact", existing.map((a) => a.id));
401 const maxExpiry = Date.now() + MAX_RETENTION_DAYS * 86400_000;
402 const requested = expiresAt ? Date.parse(expiresAt) : NaN;
403 const expiry = new Date(Number.isFinite(requested) ? Math.min(Math.max(requested, Date.now() + 86400_000), maxExpiry) : maxExpiry).toISOString();
404 const t = now();
405 this.sql.exec(
406 "INSERT INTO rt_artifacts (run_id, job_id, name, size, mime_type, status, created_at, updated_at, expires_at) VALUES (?, ?, ?, 0, ?, 'uploading', ?, ?, ?)",
407 runId,
408 jobId,
409 name,
410 mimeType || "application/zip",
411 t,
412 t,
413 expiry,
414 );
415 return { id: this.sql.exec<{ id: number }>("SELECT last_insert_rowid() AS id").one().id };
416 }
417
418 /** The job's unfinished upload of artifact `name`. */
419 artifactUpload(jobId: string, name: string): ArtifactEntry | null {
420 const { runId } = this.job(jobId);
421 const r = this.sql.exec<ArtifactRow>("SELECT * FROM rt_artifacts WHERE run_id = ? AND name = ? AND job_id = ? AND status = 'uploading' ORDER BY id DESC LIMIT 1", runId, name, jobId).toArray()[0];
422 return r ? this.toArtifact(r) : null;
423 }
424
425 artifactWritable(id: number): boolean {
426 const r = this.sql.exec<{ status: string; job: string | null }>("SELECT a.status, j.status AS job FROM rt_artifacts a LEFT JOIN jobs j ON j.id = a.job_id WHERE a.id = ?", id).toArray()[0];
427 return !!r && r.status === "uploading" && r.job === "in_progress";
428 }
429
430 /** Finishes an upload; `etag` is the object's, so a later overwrite is detected and refused. */
431 async artifactFinalize(jobId: string, name: string, size: number, digest: string | undefined, etag: string): Promise<ArtifactEntry> {
432 const a = this.artifactUpload(jobId, name);
433 if (!a) throw new HttpError(404, `no upload of artifact '${name}' in progress`);
434 try {
435 await this.checkCommitSize("artifact", a.id, size);
436 } catch (e) {
437 this.sql.exec("DELETE FROM rt_artifacts WHERE id = ?", a.id);
438 await this.dropObjects("artifact", [a.id]);
439 throw e;
440 }
441 this.sql.exec("UPDATE rt_artifacts SET status = 'ready', size = ?, staged = 0, digest = ?, etag = ?, updated_at = ? WHERE id = ?", size, digest ?? null, etag, now(), a.id);
442 return this.artifactGet(a.id)!;
443 }
444
445 /**
446 * Refuses an older runner's upload of `name` when the artifact service already
447 * has an artifact of that name in the run (names are unique in a run). The
448 * runner's own earlier upload of the name is replaced instead.
449 */
450 legacyArtifactCheck(runId: string, name: string): void {
451 const taken = this.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rt_artifacts WHERE run_id = ? AND name = ? AND legacy = 0 AND status = 'ready' AND expires_at > ?", runId, name, now()).one().n;
452 if (taken) throw new HttpError(409, "an artifact with this name already exists on the workflow run");
453 }
454
455 /** Records an older runner's upload, already stored at its legacy key; kept for the longest retention. */
456 legacyArtifactSaved(runId: string, jobId: string, name: string, size: number): ArtifactEntry {
457 this.legacyArtifactCheck(runId, name);
458 // The new tarball was written over the earlier one's, so only the earlier row goes.
459 this.sql.exec("DELETE FROM rt_artifacts WHERE run_id = ? AND name = ? AND legacy = 1", runId, name);
460 const t = now();
461 const expires = new Date(Date.now() + MAX_RETENTION_DAYS * 86400_000).toISOString();
462 this.sql.exec("INSERT INTO rt_artifacts (run_id, job_id, name, size, mime_type, status, created_at, updated_at, expires_at, legacy) VALUES (?, ?, ?, ?, 'application/gzip', 'ready', ?, ?, ?, 1)", runId, jobId, name, size, t, t, expires);
463 return this.artifactGet(this.sql.exec<{ id: number }>("SELECT last_insert_rowid() AS id").one().id)!;
464 }
465
466 /** A finished artifact; with `includeExpired` (the REST API), also one past its retention. */
467 artifactGet(id: number, o: { includeExpired?: boolean } = {}): ArtifactEntry | null {
468 const r = o.includeExpired
469 ? this.sql.exec<ArtifactRow>("SELECT * FROM rt_artifacts WHERE id = ? AND status IN ('ready', 'expired')", id).toArray()[0]
470 : this.sql.exec<ArtifactRow>("SELECT * FROM rt_artifacts WHERE id = ? AND status = 'ready' AND expires_at > ?", id, now()).toArray()[0];
471 return r ? this.toArtifact(r) : null;
472 }
473
474 /**
475 * Finished, unexpired artifacts of a run (latest first), optionally by name or id;
476 * with `includeExpired` (the REST API), expired ones too; with `legacy: false`,
477 * not those uploaded by older runners.
478 * A numeric run id (github.run_id, the run number) covers all of the run's attempts; the REST
479 * API's 16-digit run id (http/gh.ts uuidNumber) is one attempt.
480 */
481 runArtifacts(runId: string, filter: { name?: string; id?: number; includeExpired?: boolean; legacy?: false } = {}): ArtifactEntry[] {
482 const pattern = uuidPattern(runId);
483 if (pattern) runId = this.sql.exec<{ id: string }>("SELECT id FROM runs WHERE id GLOB ? ORDER BY created_at DESC LIMIT 1", pattern).toArray()[0]?.id ?? "-";
484 const numeric = /^\d+$/.test(runId);
485 // An attempt also has the artifacts of the jobs a partial re-run kept from an earlier attempt, as on GitHub.
486 const where = [
487 numeric ? "run_id IN (SELECT id FROM runs WHERE run_number = ?)" : "(run_id = ? OR job_id IN (SELECT carried_from FROM jobs WHERE run_id = ? AND carried_from IS NOT NULL))",
488 ...(filter.includeExpired ? ["status IN ('ready', 'expired')"] : ["status = 'ready'", "expires_at > ?"]),
489 ];
490 const args: unknown[] = [...(numeric ? [Number(runId)] : [runId, runId]), ...(filter.includeExpired ? [] : [now()])];
491 if (filter.name !== undefined) {
492 where.push("name = ?");
493 args.push(filter.name);
494 }
495 if (filter.id !== undefined) {
496 where.push("id = ?");
497 args.push(filter.id);
498 }
499 if (filter.legacy === false) where.push("legacy = 0");
500 return this.sql.exec<ArtifactRow>(`SELECT * FROM rt_artifacts WHERE ${where.join(" AND ")} ORDER BY id DESC`, ...args).toArray().map(this.toArtifact);
501 }
502
503 /** The artifacts the artifact service uploaded to a running job's own run (the toolkit's ListArtifacts and GetSignedArtifactURL). */
504 jobArtifacts(jobId: string, filter: { name?: string; id?: number } = {}): ArtifactEntry[] {
505 return this.runArtifacts(this.job(jobId).runId, { ...filter, legacy: false });
506 }
507
508 /** REST: GET /actions/artifacts, expired artifacts included (as GitHub lists them). */
509 repoArtifacts(o: { name?: string; page?: number; perPage?: number }): { total: number; artifacts: ArtifactEntry[] } {
510 const where = ["status IN ('ready', 'expired')"];
511 const args: unknown[] = [];
512 if (o.name) {
513 where.push("name = ?");
514 args.push(o.name);
515 }
516 const w = `WHERE ${where.join(" AND ")}`;
517 const total = this.sql.exec<{ n: number }>(`SELECT count(*) AS n FROM rt_artifacts ${w}`, ...args).one().n;
518 const per = Math.min(Math.max(o.perPage ?? 30, 1), 100);
519 const rows = this.sql.exec<ArtifactRow>(`SELECT * FROM rt_artifacts ${w} ORDER BY id DESC LIMIT ? OFFSET ?`, ...args, per, (Math.max(o.page ?? 1, 1) - 1) * per).toArray();
520 return { total, artifacts: rows.map(this.toArtifact) };
521 }
522
523 /** Deletes an artifact (REST, or the toolkit's DeleteArtifact for `overwrite: true`). */
524 async artifactDelete(id: number): Promise<ArtifactEntry | null> {
525 const a = this.artifactGet(id, { includeExpired: true });
526 this.sql.exec("DELETE FROM rt_artifacts WHERE id = ?", id);
527 if (a?.legacy) await this.dropLegacyArtifacts([a]);
528 else await this.dropObjects("artifact", [id], false);
529 return a;
530 }
531
532 /** The job's own run's artifact `name`, for the toolkit's DeleteArtifact. */
533 async artifactDeleteByName(jobId: string, name: string): Promise<ArtifactEntry | null> {
534 const { runId } = this.job(jobId);
535 const a = this.runArtifacts(runId, { name })[0];
536 return a ? this.artifactDelete(a.id) : null;
537 }
538
539 /**
540 * Artifacts past their retention: the content is deleted and the artifact stays
541 * listed as expired (GitHub's `expired: true`; downloads get 410) for a while;
542 * unfinished uploads past it go entirely. Runs when uploads start and jobs end.
543 */
544 async expireArtifacts(): Promise<void> {
545 const t = now();
546 const due = this.sql
547 .exec<{ id: number; status: string; legacy: number; run_id: string; name: string }>("SELECT id, status, legacy, run_id, name FROM rt_artifacts WHERE expires_at <= ? AND status != 'expired' LIMIT 500", t)
548 .toArray();
549 const ready = due.filter((a) => a.status === "ready" && !a.legacy).map((a) => a.id);
550 const legacy = due.filter((a) => a.status === "ready" && a.legacy).map((a) => ({ id: a.id, runId: a.run_id, name: a.name }));
551 const unfinished = due.filter((a) => a.status !== "ready").map((a) => a.id);
552 for (const id of [...ready, ...legacy.map((a) => a.id)]) this.sql.exec("UPDATE rt_artifacts SET status = 'expired', staged = 0 WHERE id = ?", id);
553 for (const id of unfinished) this.sql.exec("DELETE FROM rt_artifacts WHERE id = ?", id);
554 if (ready.length) await this.dropObjects("artifact", ready, false);
555 if (legacy.length) await this.dropLegacyArtifacts(legacy);
556 if (unfinished.length) await this.dropObjects("artifact", unfinished);
557 const forgotten = new Date(Date.now() - EXPIRED_LISTED_DAYS * 86400_000).toISOString();
558 this.sql.exec("DELETE FROM rt_artifacts WHERE status = 'expired' AND expires_at <= ?", forgotten);
559 }
560}