Public: anyone can read this; the crew can change it.
Look pictures (a person's attachments) archive to the BlobStore #16733
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/4546-look-pictures-a-person-s-attachments-arc → main 0 commits fork 2 threads · 2 unresolved
12 files
changed +416
−45
- docs/BLOBS.md
- scripts/unused-exports-allow.json
- src/actions/attach_look.ts
- src/actions/build_shots.ts
- src/http/api/pulls.ts
- src/http/mcp/tools/attach_look.ts
- src/looks/archive.ts
- src/looks/service.ts
- src/web/pages/looks.ts
- test/attach-look-refusals.test.ts
- test/attach-look.test.ts
- test/look-archive.test.ts
docs/BLOBS.md +10
| @@ -46,6 +46,16 @@ secret never appears in a presigned URL; only its signature does. | ||
| 46 | 46 | |
| 47 | 47 | Blobs over a size policy are copied here by object id after a push and served by presigned URL: `docs/features/large-files.md`. |
| 48 | 48 | |
| 49 | ## A person's attached looks | |
| 50 | ||
| 51 | A picture a person attaches to a pull (`src/looks/archive.ts`) is written with `put(key, blob)` under | |
| 52 | `looks/<app>/<env>/<sha256>.<w>x<h>.<ext>` and its row's `path` is `blob:<key>`. The forge's own | |
| 53 | looks stay files under the data dir. The store is the bucket when `S3_*` is set, else | |
| 54 | `<data>/look-blobs`. The forge serves it after `mayFetchLook`; on a bucket it then redirects to a | |
| 55 | 60 s presigned GET, never signing for someone the app does not let in. `deleteLooksAndObjects` | |
| 56 | removes the objects with the rows, keeping one another row still names (same bytes, one object). | |
| 57 | Attachments from before this stay on the disk and are served from there; they are not migrated. | |
| 58 | ||
| 49 | 59 | ## Not here yet |
| 50 | 60 | |
| 51 | 61 | Archiving finished run logs and attachments onto the store and the cold-tier lifecycle are later steps of #4481, each with |
scripts/unused-exports-allow.json +1
src/actions/attach_look.ts +20 −23
| @@ -10,14 +10,11 @@ | ||
| 10 | 10 | * and it is shown only to the writers, never to whoever else can read. |
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | import { mkdirSync, writeFileSync } from "node:fs"; | |
| 14 | import { dirname, join } from "node:path"; | |
| 15 | 13 | import type { App } from "../app.ts"; |
| 16 | 14 | import { previewEnv } from "../apps/data.ts"; |
| 17 | 15 | import { getAppByRepo } from "../core/apps.ts"; |
| 18 | 16 | import { |
| 19 | 17 | attachedPage, |
| 20 | lookSlot, | |
| 21 | 18 | recordLook, |
| 22 | 19 | type Look, |
| 23 | 20 | type LookKind, |
| @@ -27,6 +24,7 @@ import { canRead, canWrite, type Repo } from "../core/repos.ts"; | ||
| 27 | 24 | import type { User } from "../core/users.ts"; |
| 28 | 25 | import { jpegHeader, isJpeg } from "../design/image/jpeg.ts"; |
| 29 | 26 | import { isPng, pngHeader } from "../design/image/png.ts"; |
| 27 | import { archiveBytes, blobPath, contentKey, exclusive, lookStore } from "../looks/archive.ts"; | |
| 30 | 28 | import { id as newId } from "../kernel/id.ts"; |
| 31 | 29 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 32 | 30 | import type { AccessError } from "./access.ts"; |
| @@ -93,14 +91,14 @@ export function cleanNote(raw: string): Result<string, "bad_note"> { | ||
| 93 | 91 | return ok(note); |
| 94 | 92 | } |
| 95 | 93 | |
| 96 | export function attachLook( | |
| 94 | export async function attachLook( | |
| 97 | 95 | app: App, |
| 98 | 96 | actor: User | undefined, |
| 99 | 97 | repo: Repo, |
| 100 | 98 | pull: Pull, |
| 101 | 99 | input: AttachInput, |
| 102 | 100 | dry = false, |
| 103 | ): Result<Look, AttachError> { | |
| 101 | ): Promise<Result<Look, AttachError>> { | |
| 104 | 102 | if (pull.repoId !== repo.id || !canRead(app.db, repo, actor)) |
| 105 | 103 | return err("not_found"); |
| 106 | 104 | if (!actor) return err("unauthorized"); |
| @@ -119,13 +117,9 @@ export function attachLook( | ||
| 119 | 117 | |
| 120 | 118 | const env = previewEnv(pull.number); |
| 121 | 119 | const page = attachedPage(newId()); |
| 122 | const path = join( | |
| 123 | "looks", | |
| 124 | record.id, | |
| 125 | env, | |
| 126 | `${pull.headOid}-${lookSlot(page, kind)}.${image.value.ext}`, | |
| 127 | ); | |
| 128 | const out = join(app.config.dataDir, path); | |
| 120 | // Where it will be held: the store, by the picture's own content (`looks/archive.ts`). | |
| 121 | const key = contentKey(record.id, env, image.value.bytes, image.value.ext, image.value.width, image.value.height); | |
| 122 | const path = blobPath(key); | |
| 129 | 123 | // A dry run has checked everything and writes nothing. |
| 130 | 124 | if (dry) |
| 131 | 125 | return ok({ |
| @@ -143,17 +137,20 @@ export function attachLook( | ||
| 143 | 137 | attachedBy: actor.username, |
| 144 | 138 | note: note.value, |
| 145 | 139 | }); |
| 146 | mkdirSync(dirname(out), { recursive: true }); | |
| 147 | writeFileSync(out, image.value.bytes); | |
| 148 | const look = recordLook(app.db, { | |
| 149 | appId: record.id, | |
| 150 | env, | |
| 151 | commitOid: pull.headOid, | |
| 152 | page, | |
| 153 | kind, | |
| 154 | path, | |
| 155 | attachedBy: actor.username, | |
| 156 | note: note.value, | |
| 140 | // The put and the row are one exclusive step: a delete of the same key (`deleteObjects`) runs | |
| 141 | // before or after both, never between them. | |
| 142 | const look = await exclusive(app.config, async () => { | |
| 143 | await archiveBytes(lookStore(app.config), key, image.value.bytes); | |
| 144 | return recordLook(app.db, { | |
| 145 | appId: record.id, | |
| 146 | env, | |
| 147 | commitOid: pull.headOid, | |
| 148 | page, | |
| 149 | kind, | |
| 150 | path, | |
| 151 | attachedBy: actor.username, | |
| 152 | note: note.value, | |
| 153 | }); | |
| 157 | 154 | }); |
| 158 | 155 | app.bus.append({ |
| 159 | 156 | kind: "look.attached", |
src/actions/build_shots.ts +2 −2
| @@ -11,7 +11,7 @@ | ||
| 11 | 11 | * repository sees it. A writer chooses that, one picture at a time. |
| 12 | 12 | */ |
| 13 | 13 | |
| 14 | import { join } from "node:path"; | |
| 14 | import { lookBytes } from "../looks/archive.ts"; | |
| 15 | 15 | import type { App } from "../app.ts"; |
| 16 | 16 | import { getAppByRepo } from "../core/apps.ts"; |
| 17 | 17 | import { looksForCommits, type Look } from "../core/looks.ts"; |
| @@ -149,7 +149,7 @@ export async function pickShots( | ||
| 149 | 149 | const added: ShotEntry[] = []; |
| 150 | 150 | for (const look of picked) { |
| 151 | 151 | // Read off the event loop: a pick of 12 pictures must not block other requests. |
| 152 | const bytes = await Bun.file(join(app.config.dataDir, look.path)).bytes().catch(() => undefined); | |
| 152 | const bytes = await lookBytes(app.config, look); | |
| 153 | 153 | if (bytes === undefined) return err("no_such_shot"); |
| 154 | 154 | const stored = await storeShot(edit.value.dir, bytes); |
| 155 | 155 | if (!stored.ok) return stored; |
src/http/api/pulls.ts +1 −1
| @@ -644,7 +644,7 @@ export function pullRoutes(router: Router<Handler>): void { | ||
| 644 | 644 | const found = loadPull(ctx); |
| 645 | 645 | if ("error" in found) return found.error; |
| 646 | 646 | const input = await body(ctx.request); |
| 647 | const attached = attachLook( | |
| 647 | const attached = await attachLook( | |
| 648 | 648 | ctx.app, |
| 649 | 649 | ctx.auth.user, |
| 650 | 650 | found.repo, |
src/http/mcp/tools/attach_look.ts +2 −2
| @@ -24,7 +24,7 @@ export const tool: Tool = { | ||
| 24 | 24 | }, |
| 25 | 25 | writes: true, |
| 26 | 26 | dryByDefault: true, |
| 27 | run(ctx, user, args) { | |
| 27 | async run(ctx, user, args) { | |
| 28 | 28 | const repo = planRepo(ctx, user, args); |
| 29 | 29 | if (isAnswer(repo)) return repo; |
| 30 | 30 | const n = args["pull"]; |
| @@ -41,7 +41,7 @@ export const tool: Tool = { | ||
| 41 | 41 | }; |
| 42 | 42 | const name = `${repo.ownerName}/${repo.name}#${pull.number}`; |
| 43 | 43 | const dry = args["dryRun"] !== false; |
| 44 | const attached = attachLook(ctx.app, user, repo, pull, input, dry); | |
| 44 | const attached = await attachLook(ctx.app, user, repo, pull, input, dry); | |
| 45 | 45 | if (!attached.ok) return bad(attached.error, attachWords(attached.error)); |
| 46 | 46 | if (dry) |
| 47 | 47 | return good({ |
src/looks/archive.ts added +139
| @@ -0,0 +1,139 @@ | ||
| 1 | /** | |
| 2 | * A person's attached looks in the BlobStore (#4546, step 2 of #4481 — docs/BLOBS.md). | |
| 3 | * | |
| 4 | * The forge's own looks stay files under the data dir (they are retaken, and aged out by the | |
| 5 | * sweep). A picture a person attaches is theirs to keep, so it is written to the store by a | |
| 6 | * content key and its row's `path` is `blob:<key>`; a row from before this has a plain path and is | |
| 7 | * still read from the disk. The key is | |
| 8 | * `looks/<appId>/<env>/<sha256 of the bytes>.<width>x<height>.<ext>`: the same bytes attached | |
| 9 | * twice to one environment are one object, and the size a page reserves for the picture is in its | |
| 10 | * name, so drawing a pull never reads the store. | |
| 11 | * | |
| 12 | * Served by the forge's own stream after its access check (`mayFetchLook`), bucket or not. | |
| 13 | */ | |
| 14 | ||
| 15 | import { createHash } from "node:crypto"; | |
| 16 | import { join } from "node:path"; | |
| 17 | import type { Database } from "bun:sqlite"; | |
| 18 | import { deleteLooks, type Look } from "../core/looks.ts"; | |
| 19 | import { createLog } from "../kernel/log.ts"; | |
| 20 | import { dirStore, s3FromEnv, s3Store, type BlobStore } from "../blob/store.ts"; | |
| 21 | ||
| 22 | const log = createLog("looks"); | |
| 23 | ||
| 24 | const BLOB = "blob:"; | |
| 25 | const NAME = /^[0-9a-f]{64}\.(\d{1,5})x(\d{1,5})\.(png|jpg)$/; | |
| 26 | ||
| 27 | /** A forge's look store, kept by its config object so two forges in one process never share one. */ | |
| 28 | const stores = new WeakMap<object, BlobStore>(); | |
| 29 | /** What names a forge: its config. */ | |
| 30 | export type LookHome = { readonly dataDir: string }; | |
| 31 | /** | |
| 32 | * The store a forge's attached looks go to: its bucket when `S3_*` is set, else a directory under | |
| 33 | * its data. | |
| 34 | */ | |
| 35 | export function lookStore(home: LookHome): BlobStore { | |
| 36 | let store = stores.get(home); | |
| 37 | if (store === undefined) { | |
| 38 | const target = s3FromEnv(); | |
| 39 | store = target === undefined ? dirStore(join(home.dataDir, "look-blobs")) : s3Store(target, 2); | |
| 40 | stores.set(home, store); | |
| 41 | } | |
| 42 | return store; | |
| 43 | } | |
| 44 | /** Use `store` for a forge: a test's bucket stand-in. */ | |
| 45 | export const useLookStore = (home: LookHome, store: BlobStore): void => void stores.set(home, store); | |
| 46 | ||
| 47 | /** The row's `path` for a picture held in the store. */ | |
| 48 | export const blobPath = (key: string): string => `${BLOB}${key}`; | |
| 49 | /** The store key a row's path names, or undefined for a picture on the disk. */ | |
| 50 | export const blobKey = (path: string): string | undefined => (path.startsWith(BLOB) ? path.slice(BLOB.length) : undefined); | |
| 51 | ||
| 52 | /** The content key of a picture. */ | |
| 53 | export function contentKey(appId: string, env: string, bytes: Uint8Array, ext: "png" | "jpg", width: number, height: number): string { | |
| 54 | const sha = createHash("sha256").update(bytes).digest("hex"); | |
| 55 | return `looks/${appId}/${env}/${sha}.${width}x${height}.${ext}`; | |
| 56 | } | |
| 57 | ||
| 58 | /** The picture's own size and type, read from its key's name. */ | |
| 59 | export function keyFacts(key: string): { width: number; height: number; type: string } | undefined { | |
| 60 | const m = NAME.exec(key.slice(key.lastIndexOf("/") + 1)); | |
| 61 | return m === null ? undefined : { width: Number(m[1]), height: Number(m[2]), type: m[3] === "jpg" ? "image/jpeg" : "image/png" }; | |
| 62 | } | |
| 63 | ||
| 64 | /** Write a picture to the store; the row's path for it. */ | |
| 65 | export async function archiveBytes( | |
| 66 | store: BlobStore, | |
| 67 | key: string, | |
| 68 | bytes: Uint8Array, | |
| 69 | ): Promise<string> { | |
| 70 | await store.put(key, new Blob([bytes]), undefined, { type: keyFacts(key)?.type ?? "image/png" }); | |
| 71 | return blobPath(key); | |
| 72 | } | |
| 73 | ||
| 74 | /** | |
| 75 | * How one picture is served, once the reader has been let in: always the forge's own stream, so | |
| 76 | * the page's `img-src 'self'` holds for a bucket too (a redirect to the bucket's host would be | |
| 77 | * blocked). undefined when the object is not there. | |
| 78 | */ | |
| 79 | export async function serveBlob( | |
| 80 | store: BlobStore, | |
| 81 | key: string, | |
| 82 | ): Promise<{ stream: ReadableStream<Uint8Array>; size: number } | undefined> { | |
| 83 | if (keyFacts(key) === undefined) return undefined; | |
| 84 | const size = await store.size(key); | |
| 85 | const stream = size === undefined ? undefined : await store.getStream(key); | |
| 86 | return stream === undefined || size === undefined ? undefined : { stream, size }; | |
| 87 | } | |
| 88 | ||
| 89 | const chains = new WeakMap<object, Promise<unknown>>(); | |
| 90 | /** | |
| 91 | * Run `fn` after every earlier exclusive step of this forge: a put with its row and a delete with | |
| 92 | * its check never interleave, so a delete cannot remove the object a new row is about to name. | |
| 93 | */ | |
| 94 | export function exclusive<T>(home: LookHome, fn: () => Promise<T> | T): Promise<T> { | |
| 95 | const run = (chains.get(home) ?? Promise.resolve()).then(fn, fn); | |
| 96 | chains.set(home, run.catch(() => undefined)); | |
| 97 | return run; | |
| 98 | } | |
| 99 | ||
| 100 | /** A picture's bytes, from the store or the disk: for a reader inside the forge. */ | |
| 101 | export async function lookBytes(home: LookHome, look: Pick<Look, "path">): Promise<Uint8Array | undefined> { | |
| 102 | const key = blobKey(look.path); | |
| 103 | if (key === undefined) return Bun.file(join(home.dataDir, look.path)).bytes().catch(() => undefined); | |
| 104 | return lookStore(home).get(key).catch(() => undefined); | |
| 105 | } | |
| 106 | ||
| 107 | /** | |
| 108 | * Delete the objects of looks that are gone, except one a remaining row still names (the same | |
| 109 | * bytes attached twice are one object). Never throws: a store that is down leaves an object for | |
| 110 | * the next sweep of the prefix, not a failed pull. | |
| 111 | */ | |
| 112 | export async function deleteObjects(db: Database, home: LookHome, gone: readonly Pick<Look, "path">[]): Promise<void> { | |
| 113 | const keys = new Set<string>(); | |
| 114 | for (const look of gone) { | |
| 115 | const key = blobKey(look.path); | |
| 116 | if (key !== undefined) keys.add(key); | |
| 117 | } | |
| 118 | if (keys.size === 0) return; | |
| 119 | const store = lookStore(home); | |
| 120 | for (const key of keys) { | |
| 121 | await exclusive(home, async () => { | |
| 122 | if (db.query("SELECT 1 FROM look WHERE path = ?1 LIMIT 1").get(blobPath(key)) !== null) return; | |
| 123 | await store.delete(key).catch((error: unknown) => log.warn("look object not deleted", { key, error: String(error) })); | |
| 124 | }); | |
| 125 | } | |
| 126 | } | |
| 127 | ||
| 128 | /** `deleteLooks`, and the objects with the rows. Returns what was forgotten. */ | |
| 129 | export async function deleteLooksAndObjects( | |
| 130 | db: Database, | |
| 131 | home: LookHome, | |
| 132 | appId: string, | |
| 133 | env: string, | |
| 134 | keepCommit?: string, | |
| 135 | ): Promise<Look[]> { | |
| 136 | const gone = deleteLooks(db, appId, env, keepCommit); | |
| 137 | await deleteObjects(db, home, gone); | |
| 138 | return gone; | |
| 139 | } |
src/looks/service.ts +4 −2
| @@ -76,6 +76,7 @@ import { pngHeader } from "../design/image/png.ts"; | ||
| 76 | 76 | import { createLog } from "../kernel/log.ts"; |
| 77 | 77 | import { addCommitLook } from "../checks/looks.ts"; |
| 78 | 78 | import type { LookVitals } from "../checks/summary.ts"; |
| 79 | import { blobKey, deleteLooksAndObjects, deleteObjects } from "./archive.ts"; | |
| 79 | 80 | import { keepAsMain } from "./main_looks.ts"; |
| 80 | 81 | import { closeBrowsers, findChromium, isNoBrowser, lookLanes, takeLook, type Capture } from "./capture.ts"; |
| 81 | 82 | import { browserRefusal } from "./chromium.ts"; |
| @@ -880,7 +881,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle { | ||
| 880 | 881 | aside.delete(envKey({ appId, env })); |
| 881 | 882 | const at = queue.findIndex((q) => q.appId === appId && q.env === env); |
| 882 | 883 | if (at !== -1) queue.splice(at, 1); |
| 883 | deleteLooks(app.db, appId, env); | |
| 884 | void deleteLooksAndObjects(app.db, app.config, appId, env); | |
| 884 | 885 | rmSync(join(looksRoot(dataDir), appId, env), { |
| 885 | 886 | recursive: true, |
| 886 | 887 | force: true, |
| @@ -888,8 +889,9 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle { | ||
| 888 | 889 | } |
| 889 | 890 | |
| 890 | 891 | function remove(looks: readonly { path: string }[]): void { |
| 892 | void deleteObjects(app.db, app.config, looks); | |
| 891 | 893 | for (const look of looks) |
| 892 | if (look.path !== "") rmSync(join(dataDir, look.path), { force: true }); | |
| 894 | if (look.path !== "" && blobKey(look.path) === undefined) rmSync(join(dataDir, look.path), { force: true }); | |
| 893 | 895 | } |
| 894 | 896 | |
| 895 | 897 | /** |
src/web/pages/looks.ts +18 −5
| @@ -30,6 +30,7 @@ import type { Pull } from "../../core/pulls.ts"; | ||
| 30 | 30 | import { canSeeOwnerFacts, type Repo } from "../../core/repos.ts"; |
| 31 | 31 | import type { Ctx } from "../../http/context.ts"; |
| 32 | 32 | import { notFound } from "../../http/respond.ts"; |
| 33 | import { blobKey, keyFacts, lookStore, serveBlob } from "../../looks/archive.ts"; | |
| 33 | 34 | import { pairCounts, pairsLine } from "../../looks/pairs.ts"; |
| 34 | 35 | import { mayFetchLook as mayFetchLookFor } from "../../looks/readable.ts"; |
| 35 | 36 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| @@ -69,7 +70,7 @@ export function thumbLook( | ||
| 69 | 70 | // GET /:owner/:name/looks/:env/:commit/:kind.png — the last segment is |
| 70 | 71 | // really a slot (`lookSlot`): the kind alone for the home page, the page |
| 71 | 72 | // and the kind for any other. |
| 72 | export function lookImage(ctx: Ctx): Response { | |
| 73 | export async function lookImage(ctx: Ctx): Promise<Response> { | |
| 73 | 74 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 74 | 75 | const repo = loadRepo(ctx); |
| 75 | 76 | const env = ctx.params.env ?? ""; |
| @@ -89,10 +90,12 @@ export function lookImage(ctx: Ctx): Response { | ||
| 89 | 90 | }); |
| 90 | 91 | if (found === undefined) return notFound(); |
| 91 | 92 | const look = found; |
| 93 | const key = blobKey(look.path); | |
| 92 | 94 | const path = join(ctx.app.config.dataDir, look.path); |
| 93 | if (!timePhase(ctx.request, "read", () => existsSync(path))) return notFound(); | |
| 95 | if (key === undefined && !timePhase(ctx.request, "read", () => existsSync(path))) return notFound(); | |
| 94 | 96 | const headers = { |
| 95 | "content-type": path.endsWith(".jpg") ? "image/jpeg" : "image/png", | |
| 97 | "content-type": | |
| 98 | (key === undefined ? undefined : keyFacts(key)?.type) ?? (path.endsWith(".jpg") ? "image/jpeg" : "image/png"), | |
| 96 | 99 | // Named by this taking (`lookVersion`), so a retake at the same commit |
| 97 | 100 | // is a new tag as well as a new URL. |
| 98 | 101 | etag: `"${lookVersion(look)}"`, |
| @@ -107,7 +110,12 @@ export function lookImage(ctx: Ctx): Response { | ||
| 107 | 110 | // Only after `mayFetchLook`: a 304 must not say a private picture exists. |
| 108 | 111 | if (requestHolds(ctx.request, headers.etag)) |
| 109 | 112 | return new Response(null, { status: 304, headers }); |
| 110 | return new Response(Bun.file(path), { headers }); | |
| 113 | if (key === undefined) return new Response(Bun.file(path), { headers }); | |
| 114 | // In the store (`looks/archive.ts`): the access check above has passed; streamed by the forge | |
| 115 | // for a bucket too, so the CSP's `img-src 'self'` holds. | |
| 116 | const served = await serveBlob(lookStore(ctx.app.config), key); | |
| 117 | if (served === undefined) return notFound(); | |
| 118 | return new Response(served.stream, { headers: { ...headers, "content-length": String(served.size) } }); | |
| 111 | 119 | } |
| 112 | 120 | |
| 113 | 121 | /** `mayFetchLook` for a request (`looks/readable.ts`). */ |
| @@ -324,11 +332,16 @@ export function lookCard( | ||
| 324 | 332 | ); |
| 325 | 333 | } |
| 326 | 334 | |
| 327 | /** An attached picture's own size, read from its header; none if it cannot be. */ | |
| 335 | /** | |
| 336 | * An attached picture's own size: in its key's name when it is in the store (nothing is read), | |
| 337 | * else read from the header of the file a look from before the store has; none if it cannot be. | |
| 338 | */ | |
| 328 | 339 | function attachedSize( |
| 329 | 340 | ctx: Ctx, |
| 330 | 341 | look: Look, |
| 331 | 342 | ): { width: number; height: number } | undefined { |
| 343 | const key = blobKey(look.path); | |
| 344 | if (key !== undefined) return keyFacts(key); | |
| 332 | 345 | let fd: number | undefined; |
| 333 | 346 | try { |
| 334 | 347 | fd = openSync(join(ctx.app.config.dataDir, look.path), "r"); |
test/attach-look-refusals.test.ts +10 −9
| @@ -44,7 +44,7 @@ describe("attachLook width and place", () => { | ||
| 44 | 44 | }); |
| 45 | 45 | const kept = () => looksForEnv(app.db, record.id, previewEnv(pull.number)); |
| 46 | 46 | const onDisk = () => { |
| 47 | const dir = join(dataDir, "looks"); | |
| 47 | const dir = join(dataDir, "look-blobs"); | |
| 48 | 48 | return existsSync(dir) ? readdirSync(dir, { recursive: true }) : []; |
| 49 | 49 | }; |
| 50 | 50 | const rowCount = () => |
| @@ -98,30 +98,31 @@ describe("attachLook width and place", () => { | ||
| 98 | 98 | await rm(dataDir, { recursive: true, force: true }); |
| 99 | 99 | }); |
| 100 | 100 | |
| 101 | test("a phone look and a desktop look are both kept", () => { | |
| 102 | const phone = attach("phone"); | |
| 103 | const desktop = attach("desktop"); | |
| 101 | test("a phone look and a desktop look are both kept", async () => { | |
| 102 | const phone = await attach("phone"); | |
| 103 | const desktop = await attach("desktop"); | |
| 104 | 104 | expect(phone.ok && phone.value.kind).toBe("phone"); |
| 105 | 105 | expect(desktop.ok && desktop.value.kind).toBe("desktop"); |
| 106 | 106 | expect(kept().map((l) => l.kind).sort()).toEqual(["desktop", "phone"]); |
| 107 | expect(onDisk().filter((f) => /\.png$/.test(String(f))).length).toBe(2); | |
| 107 | // Both widths are the same bytes here: one object in the store, two rows naming it. | |
| 108 | expect(onDisk().filter((f) => /\.png$/.test(String(f))).length).toBe(1); | |
| 108 | 109 | }); |
| 109 | 110 | |
| 110 | test("tablet, an empty string and a number are bad_width, and nothing is stored", () => { | |
| 111 | test("tablet, an empty string and a number are bad_width, and nothing is stored", async () => { | |
| 111 | 112 | const rows = rowCount(); |
| 112 | 113 | const files = onDisk().length; |
| 113 | 114 | for (const width of ["tablet", "", 390]) { |
| 114 | const r = attach(width); | |
| 115 | const r = await attach(width); | |
| 115 | 116 | expect(r).toEqual({ ok: false, error: "bad_width" } as never); |
| 116 | 117 | expect(rowCount()).toBe(rows); |
| 117 | 118 | expect(onDisk().length).toBe(files); |
| 118 | 119 | } |
| 119 | 120 | }); |
| 120 | 121 | |
| 121 | test("a repository that is not an app is no_app, and nothing is stored", () => { | |
| 122 | test("a repository that is not an app is no_app, and nothing is stored", async () => { | |
| 122 | 123 | const rows = rowCount(); |
| 123 | 124 | const files = onDisk().length; |
| 124 | const r = attach("phone", [plainRepo, plainPull]); | |
| 125 | const r = await attach("phone", [plainRepo, plainPull]); | |
| 125 | 126 | expect(r).toEqual({ ok: false, error: "no_app" } as never); |
| 126 | 127 | expect(rowCount()).toBe(rows); |
| 127 | 128 | expect(onDisk().length).toBe(files); |
test/attach-look.test.ts +1 −1
| @@ -62,7 +62,7 @@ describe("attaching a look to a pull", () => { | ||
| 62 | 62 | const good = { width: "phone", says: "the empty garden", image: PHONE }; |
| 63 | 63 | const kept = () => looksForEnv(app.db, record.id, previewEnv(pull.number)); |
| 64 | 64 | const onDisk = () => { |
| 65 | const dir = join(dataDir, "looks"); | |
| 65 | const dir = join(dataDir, "look-blobs"); | |
| 66 | 66 | return existsSync(dir) ? readdirSync(dir, { recursive: true }) : []; |
| 67 | 67 | }; |
| 68 | 68 |
test/look-archive.test.ts added +208
| @@ -0,0 +1,208 @@ | ||
| 1 | /** | |
| 2 | * A person's attached look is written to the BlobStore by its content, served from there after | |
| 3 | * the access check, and deleted with its row (#4546). A bucket's bytes are streamed by the forge, | |
| 4 | * only for someone the app lets in. | |
| 5 | */ | |
| 6 | ||
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { existsSync } from "node:fs"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { openPull } from "../src/actions/pulls.ts"; | |
| 13 | import { attachLook } from "../src/actions/attach_look.ts"; | |
| 14 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 15 | import { createApp, type App } from "../src/app.ts"; | |
| 16 | import { previewEnv } from "../src/apps/data.ts"; | |
| 17 | import { createApp as insertApp, type AppRecord } from "../src/core/apps.ts"; | |
| 18 | import { looksForEnv } from "../src/core/looks.ts"; | |
| 19 | import type { Pull } from "../src/core/pulls.ts"; | |
| 20 | import type { Repo } from "../src/core/repos.ts"; | |
| 21 | import { createUser, type User } from "../src/core/users.ts"; | |
| 22 | import { encodePng } from "../src/design/image/png.ts"; | |
| 23 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 24 | import { dirStore, type BlobStore } from "../src/blob/store.ts"; | |
| 25 | import { blobKey, deleteLooksAndObjects, deleteObjects, keyFacts, lookStore, useLookStore } from "../src/looks/archive.ts"; | |
| 26 | import { err } from "../src/kernel/result.ts"; | |
| 27 | import { startLooks } from "../src/looks/service.ts"; | |
| 28 | import { lookUrl } from "../src/core/looks.ts"; | |
| 29 | import { quietLogs } from "./helpers/globals.ts"; | |
| 30 | ||
| 31 | quietLogs(); | |
| 32 | ||
| 33 | const PASSWORD = "a-good-passphrase"; | |
| 34 | const bytes = encodePng(40, 30, new Uint8Array(40 * 30 * 4).fill(120)); | |
| 35 | const IMAGE = Buffer.from(bytes).toString("base64"); | |
| 36 | const other = Buffer.from(encodePng(20, 10, new Uint8Array(20 * 10 * 4).fill(9))).toString("base64"); | |
| 37 | ||
| 38 | describe("attached looks in the BlobStore", () => { | |
| 39 | let dataDir: string; | |
| 40 | let app: App; | |
| 41 | let servers: Servers; | |
| 42 | let alice: User; | |
| 43 | let repo: Repo; | |
| 44 | let record: AppRecord; | |
| 45 | let pull: Pull; | |
| 46 | const cookies: Record<string, string> = {}; | |
| 47 | let store: BlobStore; | |
| 48 | const env = () => previewEnv(pull.number); | |
| 49 | ||
| 50 | const login = async (username: string): Promise<string> => { | |
| 51 | const r = await fetch(`${servers.url}/signin`, { | |
| 52 | method: "POST", | |
| 53 | headers: { origin: servers.url }, | |
| 54 | body: new URLSearchParams({ username, password: PASSWORD }), | |
| 55 | redirect: "manual", | |
| 56 | }); | |
| 57 | return (r.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 58 | }; | |
| 59 | const fetchLook = (path: string, who: string) => | |
| 60 | fetch(`${servers.url}${path}`, { headers: cookies[who] ? { cookie: cookies[who]! } : {}, redirect: "manual" }); | |
| 61 | const attach = (image = IMAGE) => | |
| 62 | attachLook(app, alice, repo, pull, { width: "phone", note: "the garden", image }); | |
| 63 | ||
| 64 | beforeAll(async () => { | |
| 65 | dataDir = await mkdtemp(join(tmpdir(), "forge-look-archive-")); | |
| 66 | app = createApp({ dataDir, port: 0 }); | |
| 67 | const person = async (username: string): Promise<User> => { | |
| 68 | const made = await createUser(app.db, { | |
| 69 | origin: "seed", | |
| 70 | trusted: true, | |
| 71 | username, | |
| 72 | email: `${username}@forge.local`, | |
| 73 | password: PASSWORD, | |
| 74 | adminIfFirst: username === "alice", | |
| 75 | }); | |
| 76 | if (!made.ok) throw new Error(made.error); | |
| 77 | return made.value; | |
| 78 | }; | |
| 79 | alice = await person("alice"); | |
| 80 | await person("bob"); | |
| 81 | const made = await createRepo(app, alice, { name: "garden", visibility: "private" }); | |
| 82 | if (!made.ok) throw new Error(String(made.error)); | |
| 83 | repo = made.value; | |
| 84 | await commitToBranch(app, alice, repo, { message: "seed", files: [{ path: "README.md", content: "# g\n" }] }); | |
| 85 | await commitToBranch(app, alice, repo, { branch: "one", base: "main", message: "one", files: [{ path: "one.md", content: "x\n" }] }); | |
| 86 | const opened = await openPull(app, alice, repo, { title: "One", body: "", baseBranch: "main", headBranch: "one" }); | |
| 87 | if (!opened.ok) throw new Error(String(opened.error)); | |
| 88 | pull = opened.value; | |
| 89 | const inserted = insertApp(app.db, { repoId: repo.id, slug: "garden", access: "private" }); | |
| 90 | if (!inserted.ok) throw new Error(inserted.error); | |
| 91 | record = inserted.value; | |
| 92 | servers = await serve(app); | |
| 93 | cookies["alice"] = await login("alice"); | |
| 94 | cookies["bob"] = await login("bob"); | |
| 95 | store = lookStore(app.config); // a dirStore: no S3_* here | |
| 96 | }, 30_000); | |
| 97 | ||
| 98 | afterAll(async () => { | |
| 99 | servers.stop(); | |
| 100 | app.close(); | |
| 101 | await rm(dataDir, { recursive: true, force: true }); | |
| 102 | }); | |
| 103 | ||
| 104 | test("a look is written to the store by its content, not the data dir", async () => { | |
| 105 | const made = await attach(); | |
| 106 | if (!made.ok) throw new Error(made.error); | |
| 107 | const key = blobKey(made.value.path)!; | |
| 108 | expect(key).toMatch(new RegExp(`^looks/${record.id}/${env()}/[0-9a-f]{64}\\.40x30\\.png$`)); | |
| 109 | expect(keyFacts(key)).toEqual({ width: 40, height: 30, type: "image/png" }); | |
| 110 | expect(Buffer.from((await store.get(key))!).equals(Buffer.from(bytes))).toBe(true); | |
| 111 | expect(existsSync(join(dataDir, "looks"))).toBe(false); | |
| 112 | expect(store.dir).toBe(join(dataDir, "look-blobs")); | |
| 113 | }); | |
| 114 | ||
| 115 | test("it is served from the store to a writer, and a stranger is not told it exists", async () => { | |
| 116 | const [look] = looksForEnv(app.db, record.id, env()); | |
| 117 | const url = lookUrl(`/alice/garden`, look!); | |
| 118 | const res = await fetchLook(url, "alice"); | |
| 119 | expect(res.status).toBe(200); | |
| 120 | expect(res.headers.get("content-type")).toBe("image/png"); | |
| 121 | expect(Buffer.from(await res.arrayBuffer()).equals(Buffer.from(bytes))).toBe(true); | |
| 122 | expect((await fetchLook(url, "bob")).status).toBe(404); | |
| 123 | expect((await fetchLook(url, "")).status).toBe(404); | |
| 124 | }); | |
| 125 | ||
| 126 | test("on a bucket the bytes are streamed by the forge after the access check, never redirected", async () => { | |
| 127 | const reads: string[] = []; | |
| 128 | const inner = dirStore(join(dataDir, "look-blobs")); | |
| 129 | const bucket: BlobStore = { | |
| 130 | ...inner, | |
| 131 | presign: (key) => `https://bucket.example/${key}?X-Signature=abc`, | |
| 132 | getStream: (key, ...rest) => (reads.push(key), inner.getStream(key, ...rest)), | |
| 133 | }; | |
| 134 | useLookStore(app.config, bucket); | |
| 135 | const [look] = looksForEnv(app.db, record.id, env()); | |
| 136 | const url = lookUrl(`/alice/garden`, look!); | |
| 137 | expect((await fetchLook(url, "bob")).status).toBe(404); | |
| 138 | expect((await fetchLook(url, "")).status).toBe(404); | |
| 139 | expect(reads).toEqual([]); | |
| 140 | const res = await fetchLook(url, "alice"); | |
| 141 | expect(res.status).toBe(200); | |
| 142 | expect(res.headers.get("location")).toBeNull(); | |
| 143 | expect(Buffer.from(await res.arrayBuffer()).equals(Buffer.from(bytes))).toBe(true); | |
| 144 | // The page's CSP allows images from the forge only, so this has to be the forge's own bytes. | |
| 145 | expect(reads).toEqual([blobKey(look!.path)!]); | |
| 146 | useLookStore(app.config, store); | |
| 147 | }); | |
| 148 | ||
| 149 | test("a delete cannot land between an attach's put and its row", async () => { | |
| 150 | const png = Buffer.from(encodePng(8, 8, new Uint8Array(8 * 8 * 4).fill(77))).toString("base64"); | |
| 151 | const first = await attach(png); | |
| 152 | if (!first.ok) throw new Error(first.error); | |
| 153 | const key = blobKey(first.value.path)!; | |
| 154 | // Its row goes; the delete of its object starts while the same bytes are being attached again. | |
| 155 | app.db.query("DELETE FROM look WHERE id = ?1").run(first.value.id); | |
| 156 | const inner = dirStore(join(dataDir, "look-blobs")); | |
| 157 | // The delete has passed its check for rows and is about to remove the object when the attach | |
| 158 | // (put, then row) runs; it only finishes after several turns of the event loop. | |
| 159 | useLookStore(app.config, { | |
| 160 | ...inner, | |
| 161 | delete: async (k) => { | |
| 162 | for (let i = 0; i < 5; i++) await new Promise((r) => setImmediate(r)); | |
| 163 | return inner.delete(k); | |
| 164 | }, | |
| 165 | }); | |
| 166 | const deleting = deleteObjects(app.db, app.config, [first.value]); | |
| 167 | const again = attach(png); | |
| 168 | const [made] = await Promise.all([again, deleting]); | |
| 169 | if (!made.ok) throw new Error(made.error); | |
| 170 | expect(await inner.get(key)).toBeDefined(); // the new row's object survived | |
| 171 | useLookStore(app.config, store); | |
| 172 | app.db.query("DELETE FROM look WHERE id = ?1").run(made.value.id); | |
| 173 | await deleteObjects(app.db, app.config, [made.value]); | |
| 174 | }); | |
| 175 | ||
| 176 | test("deleting an environment's looks deletes the objects, but keeps one another row still names", async () => { | |
| 177 | const twin = await attach(); // the same bytes: one object, two rows | |
| 178 | const different = await attach(other); | |
| 179 | if (!twin.ok || !different.ok) throw new Error("attach"); | |
| 180 | const rows = looksForEnv(app.db, record.id, env()); | |
| 181 | expect(rows.length).toBe(3); | |
| 182 | const shared = blobKey(twin.value.path)!; | |
| 183 | const lone = blobKey(different.value.path)!; | |
| 184 | expect((await store.list(`looks/${record.id}/`)).length).toBe(2); | |
| 185 | // One of the two rows of the shared object goes; its object stays for the other. | |
| 186 | app.db.query("DELETE FROM look WHERE id = ?1").run(twin.value.id); | |
| 187 | await deleteObjects(app.db, app.config, [twin.value]); | |
| 188 | expect(await store.get(shared)).toBeDefined(); | |
| 189 | const gone = await deleteLooksAndObjects(app.db, app.config, record.id, env()); | |
| 190 | expect(gone.length).toBe(2); | |
| 191 | expect(await store.get(shared)).toBeUndefined(); | |
| 192 | expect(await store.get(lone)).toBeUndefined(); | |
| 193 | expect(await store.list(`looks/${record.id}/`)).toEqual([]); | |
| 194 | expect(looksForEnv(app.db, record.id, env())).toEqual([]); | |
| 195 | }); | |
| 196 | ||
| 197 | test("pruning a closed pull's environment removes its objects with its rows", async () => { | |
| 198 | const mine = await attach(other); | |
| 199 | if (!mine.ok) throw new Error(mine.error); | |
| 200 | expect((await store.list(`looks/${record.id}/`)).length).toBe(1); | |
| 201 | const looks = startLooks(app, { localUrl: servers.url, capture: async () => err("no browser") }); | |
| 202 | app.bus.append({ kind: "pull.closed", repoId: repo.id, actorId: alice.id, payload: { number: pull.number } }); | |
| 203 | for (let i = 0; i < 2000 && (await store.list(`looks/${record.id}/`)).length > 0; i++) await new Promise((r) => setImmediate(r)); // real-timer: the delete is a floating promise with no event to await | |
| 204 | await looks.stop(); | |
| 205 | expect(await store.list(`looks/${record.id}/`)).toEqual([]); | |
| 206 | expect(looksForEnv(app.db, record.id, env())).toEqual([]); | |
| 207 | }); | |
| 208 | }); |
new above
offline
Medium: this check and the delete are not atomic with
attachLook, which doesputbeforerecordLook. A delete landing between those two steps removes an object a new row is about to name. Close the window as described in the review body, and add a test.