Files
loki/scripts/test/media-storage.ts
CatoandClaude Opus 5.5 ff2d7cb6b7 Pictures out of Postgres and off the disk, into a private R2 bucket (#1771)
* feat(media): keep pictures in the private R2 bucket, drain them out of Postgres

The owner's rule: pictures live in Cloudflare R2, not in Postgres or on the
box's disk, and the database gets cleaned up.

- src/lib/media/r2.ts: a small S3 client for R2, SigV4 by hand (node:crypto
  + fetch, no SDK), on the fleet's PHOTOS_S3_* names. Everything is private:
  MEDIA_PRIVATE_S3_BUCKET, or private/loki/ in the photos bucket. Unset means
  behaviour exactly as before.
- Chat pictures and report screenshots are written to the bucket when it is
  configured; the row keeps the key (additive migration 0140: nullable
  object_key and screenshot_keys). Reads try the bucket, then the old column.
  A write the bucket refuses stays in Postgres, so nothing is lost.
- A throttled drain started from instrumentation moves what Postgres still
  holds (chat images, report screenshots, executed commands' attachments):
  small batches under a transaction-scoped advisory lock, upload, HEAD to
  verify length/type/MD5, then key-and-null in one statement; error backoff,
  IMAGE_DRAIN=0 kill switch, progress on /api/health under `media`.
- Commands that have not run keep their base64: runners hold no bucket
  credentials. Retry puts moved bytes back before re-sending.
- Bot shots, private tile shots and preview pictures go to the bucket when
  configured, the temp folder otherwise; bucket caches keep their age limits.
- Deleting a chat or an account deletes its objects by prefix.
- Dropping the emptied columns stays a manual step (apply-schema.sh refuses
  DROP COLUMN): docs/infrastructure/media-storage.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T

* fix(media): private pictures only in MEDIA_PRIVATE_S3_BUCKET, never the photos bucket

The photos bucket (fleet-media) gets a public domain, so a private Loki
picture must never fall back into it. The private store now needs
MEDIA_PRIVATE_S3_BUCKET; unset, or equal to PHOTOS_S3_BUCKET, counts as
unconfigured: pictures stay in Postgres as today, the drain does not run,
and the env check warns in one line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-29 07:21:50 +01:00

633 lines
22 KiB
TypeScript

/**
* Pictures in the private R2 bucket (lib/media/*), not in Postgres or on disk.
*
* The owner's rule (2026-11-26): pictures live in the bucket, and the
* database gets cleaned up. What must never happen on the way there is a
* picture dropped from Postgres that the bucket does not hold. So these pin:
* the signing (against AWS's published example), verify-before-null, the
* fallbacks when there is no bucket or it fails, the lock, the backoff and
* the kill switch.
*/
import { createHash } from "node:crypto";
import { mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
halfSetMediaSettings,
mediaSettings,
privateBucketProblem,
signRequest,
type MediaBucket,
type MediaHead,
} from "@/lib/media/r2";
import {
holds,
parseImageDataUrl,
placeNew,
putVerified,
readPicture,
toDataUrl,
} from "@/lib/media/objects";
import {
drainStatus,
resetDrainStatus,
runDrain,
type DrainLock,
type DrainOptions,
type DrainSource,
} from "@/lib/media/drain";
import { drainWanted } from "@/lib/media/start-drain";
import { carriesBytes, parkAttachments, withAttachmentBytes } from "@/lib/media/command-images";
import { placeScreenshots, screenshotAt, screenshotDataUrls } from "@/lib/feedback/screenshots";
import { readCached, sweepCached, writeCached } from "@/lib/media/private-cache";
let passed = 0;
function check(label: string, condition: boolean): void {
if (!condition) throw new Error(`✗ ${label}`);
passed++;
console.log(` ✓ ${label}`);
}
async function rejects(p: Promise<unknown>): Promise<boolean> {
return p.then(
() => false,
() => true,
);
}
// ── A bucket in memory, with ways to make it fail or lie ────────────────────
type Mode = "ok" | "down" | "truncates" | "wrong-etag";
function memoryBucket(mode: { value: Mode } = { value: "ok" }) {
const objects = new Map<string, { bytes: Buffer; contentType: string; at: number }>();
const calls: string[] = [];
const bucket: MediaBucket = {
async put(key, bytes, contentType) {
calls.push(`put ${key}`);
if (mode.value === "down") throw new Error("HTTP 503 from https://acct.r2.example");
const kept = mode.value === "truncates" ? bytes.subarray(0, bytes.length - 1) : bytes;
objects.set(key, { bytes: Buffer.from(kept), contentType, at: Date.now() });
},
async get(key) {
calls.push(`get ${key}`);
if (mode.value === "down") throw new Error("HTTP 503");
const o = objects.get(key);
return o ? { bytes: o.bytes, contentType: o.contentType, modifiedMs: o.at } : null;
},
async head(key): Promise<MediaHead | null> {
calls.push(`head ${key}`);
if (mode.value === "down") throw new Error("HTTP 503");
const o = objects.get(key);
if (!o) return null;
const md5 = createHash("md5").update(o.bytes).digest("hex");
return {
length: o.bytes.length,
contentType: o.contentType,
etag: mode.value === "wrong-etag" ? `"${"0".repeat(32)}"` : `"${md5}"`,
modifiedMs: o.at,
};
},
async delete(key) {
calls.push(`delete ${key}`);
objects.delete(key);
},
async list(prefix) {
return [...objects.entries()]
.filter(([k]) => k.startsWith(prefix))
.map(([key, o]) => ({ key, modifiedMs: o.at }));
},
};
return { bucket, objects, calls, mode };
}
const PNG = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",
"base64",
);
async function main() {
console.log("signing");
// AWS's own example, "GET Object" (Signature Version 4, header-based auth).
// Path-style here, so the "bucket" is the object's path in that example.
const signed = signRequest(
{
endpoint: "https://examplebucket.s3.amazonaws.com",
bucket: "test.txt",
accessKeyId: "AKIAIOSFODNN7EXAMPLE",
secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
region: "us-east-1",
},
"GET",
null,
{ headers: { Range: "bytes=0-9" } },
new Date("2013-05-24T00:00:00Z"),
);
check(
"matches AWS's published signature for GET Object",
signed.headers.authorization.endsWith(
"Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41",
),
);
check("Host is signed, not sent", !("host" in signed.headers));
const listed = signRequest(
{
endpoint: "https://e.example",
bucket: "b",
accessKeyId: "a",
secretAccessKey: "s",
region: "auto",
},
"GET",
null,
{ query: { prefix: "loki/chat/", "list-type": "2" } },
);
check(
"a query is signed in canonical order and encoded",
listed.url === "https://e.example/b?list-type=2&prefix=loki%2Fchat%2F",
);
console.log("settings");
const four = {
PHOTOS_S3_ENDPOINT: "https://acct.r2.example/",
PHOTOS_S3_BUCKET: "photos",
PHOTOS_S3_ACCESS_KEY_ID: "id",
PHOTOS_S3_SECRET_ACCESS_KEY: "secret",
};
check("unset means no bucket", mediaSettings({}) === null);
check("three of four means no bucket", mediaSettings({ ...four, PHOTOS_S3_BUCKET: "" }) === null);
check(
"three of four is reported",
halfSetMediaSettings({ ...four, PHOTOS_S3_BUCKET: "" }).join() === "PHOTOS_S3_BUCKET",
);
check("none set is not a half-set", halfSetMediaSettings({}).length === 0);
check(
"the account alone is no private store: the photos bucket is public",
mediaSettings(four) === null,
);
check(
"…and the env check says why, in one line",
/MEDIA_PRIVATE_S3_BUCKET is unset/.test(privateBucketProblem(four) ?? ""),
);
const same = { ...four, MEDIA_PRIVATE_S3_BUCKET: "photos" };
check(
"the photos bucket named as the private one is no private store",
mediaSettings(same) === null,
);
check(
"…and the env check says so",
/is the public photos bucket/.test(privateBucketProblem(same) ?? ""),
);
const full = { ...four, MEDIA_PRIVATE_S3_BUCKET: "loki-private" };
const own = mediaSettings(full)!;
check(
"with a bucket of their own, Loki's pictures go there and only there",
own.bucket === "loki-private" && own.prefix === "loki/",
);
check("…and the env check is quiet", privateBucketProblem(full) === null);
check("no account at all: nothing to warn about", privateBucketProblem({}) === null);
check("the endpoint loses its trailing slash", own.endpoint === "https://acct.r2.example");
check("the drain wants a private bucket and a database", !drainWanted({ ...full }));
check(
"…and never runs without the private bucket",
!drainWanted({ ...four, DATABASE_URL: "postgres://x" }),
);
check("…and runs with both", drainWanted({ ...full, DATABASE_URL: "postgres://x" }));
check(
"IMAGE_DRAIN=0 is the kill switch",
!drainWanted({ ...full, DATABASE_URL: "postgres://x", IMAGE_DRAIN: "0" }),
);
console.log("verify before anything is dropped");
{
const m = memoryBucket();
await putVerified(m.bucket, "k", PNG, "image/png");
check("a good bucket holds the bytes", holds(await m.bucket.head("k"), PNG, "image/png"));
const before = m.calls.length;
await putVerified(m.bucket, "k", PNG, "image/png");
check(
"a picture already held is not written again",
m.calls.slice(before).every((c) => !c.startsWith("put")),
);
m.mode.value = "truncates";
check(
"a bucket that keeps one byte less is caught",
await rejects(putVerified(m.bucket, "short", PNG, "image/png")),
);
m.mode.value = "wrong-etag";
check(
"an MD5 ETag that is not these bytes is caught",
await rejects(putVerified(m.bucket, "etag", PNG, "image/png")),
);
check(
"a different content type is not the same object",
!holds(
{ length: PNG.length, contentType: "image/jpeg", etag: null, modifiedMs: null },
PNG,
"image/png",
),
);
check(
"a multipart ETag (not an MD5) leaves length and type to decide",
holds(
{ length: PNG.length, contentType: "image/png", etag: '"abc-2"', modifiedMs: null },
PNG,
"image/png",
),
);
}
console.log("data URLs");
const url = toDataUrl(PNG, "image/png");
check(
"a clean data URL comes back as its bytes",
parseImageDataUrl(url)?.bytes.equals(PNG) ?? false,
);
check("a gif is not a screenshot", parseImageDataUrl(toDataUrl(PNG, "image/gif")) === null);
check(
"a data URL Node would read leniently is not moved",
parseImageDataUrl(`${url.slice(0, -2)}A`) === null,
);
console.log("new pictures, and the fallbacks");
{
check(
"no bucket: the caller keeps the bytes",
(await placeNew(null, "k", PNG, "image/png")) === null,
);
const down = memoryBucket({ value: "down" });
check(
"a bucket that is down: the caller keeps the bytes",
(await placeNew(down.bucket, "k", PNG, "image/png")) === null,
);
const up = memoryBucket();
check(
"a bucket that takes it: the key",
(await placeNew(up.bucket, "k", PNG, "image/png")) === "k",
);
check(
"read: the bucket first",
(await readPicture(up.bucket, "k", null))?.equals(PNG) ?? false,
);
const old = Buffer.from("old");
check("read: no key, the row's bytes", (await readPicture(up.bucket, null, old)) === old);
check("read: no bucket, the row's bytes", (await readPicture(null, "k", old)) === old);
check(
"read: the bucket is down, the row's bytes",
(await readPicture(down.bucket, "k", old)) === old,
);
check(
"read: the bucket is down and there is no copy — an error, not 'not found'",
await rejects(readPicture(down.bucket, "k", null)),
);
check("read: neither has it", (await readPicture(up.bucket, "missing", null)) === null);
}
console.log("a report's screenshots");
{
const values = { userId: "u1", screenshots: [url, url] };
check("no bucket: exactly as given", (await placeScreenshots(values, null)) === values);
const m = memoryBucket();
const placed = await placeScreenshots(values, m.bucket);
check(
"with a bucket: keys in order, no data URLs in the row",
placed.screenshots === null && placed.screenshotKeys?.length === 2,
);
check(
"the keys are the owner's and unguessable",
placed.screenshotKeys!.every((k) => /^feedback\/u1\/[0-9a-f-]{36}\.png$/.test(k)),
);
check(
"read back as the same data URLs",
(await screenshotDataUrls(placed, m.bucket)).join() === [url, url].join(),
);
check(
"one read back as bytes",
(await screenshotAt(placed, 1, m.bucket))?.bytes.equals(PNG) ?? false,
);
check("an unknown index is null", (await screenshotAt(placed, 4, m.bucket)) === null);
check(
"an old row is read from its own column",
(await screenshotAt(values, 0, null))?.mimeType === "image/png",
);
const odd = { userId: "u1", screenshots: [url, "data:image/png;base64,@@"] };
check(
"one odd screenshot keeps the row as it is",
(await placeScreenshots(odd, m.bucket)) === odd,
);
// The bucket takes the first and fails on the second: nothing half-moved.
let n = 0;
const flaky: MediaBucket = {
...m.bucket,
async put(key, bytes, type) {
if (n++ === 1) throw new Error("HTTP 500");
return m.bucket.put(key, bytes, type);
},
};
const before = m.objects.size;
const kept = await placeScreenshots(values, flaky);
await new Promise((r) => setTimeout(r, 10));
check("a half-taken row stays in the database whole", kept === values);
check("…and the half in the bucket is deleted", m.objects.size === before);
check(
"keys in the row but no bucket here is an error, not an empty list",
await rejects(screenshotDataUrls(placed, null)),
);
}
console.log("a command's screenshots");
{
const m = memoryBucket();
const payload = {
prompt: "look",
attachments: [
{ id: "a1", name: "s.png", mimeType: "image/png", dataBase64: PNG.toString("base64") },
],
};
check("a payload with bytes is seen", carriesBytes(payload));
const parked = await parkAttachments(m.bucket, "u1", "c1", payload);
const att = (parked.payload.attachments as { dataBase64?: string; objectKey?: string }[])[0];
check(
"parked: the key, not the bytes",
!att.dataBase64 && att.objectKey === "commands/u1/c1/a1.png",
);
check("parked payload carries no bytes", !carriesBytes(parked.payload));
const back = await withAttachmentBytes(parked.payload, m.bucket);
check(
"Retry gets the bytes back, as a runner reads them",
JSON.stringify(back) === JSON.stringify(payload),
);
const gone = await withAttachmentBytes(parked.payload, memoryBucket().bucket);
check(
"a picture the bucket lost is left out, not a broken attachment",
!("attachments" in (gone as object)),
);
m.mode.value = "truncates";
check(
"a command is not parked unless the bucket provably holds it",
await rejects(parkAttachments(m.bucket, "u1", "c2", payload)),
);
}
console.log("caches: the bucket, else the folder");
{
const dir = mkdtempSync(join(tmpdir(), "media-cache-"));
try {
const name = { key: "cache/x/a.jpg", file: join(dir, "a.jpg") };
const m = memoryBucket();
check(
"with a bucket, written there",
(await writeCached(name, PNG, "image/jpeg", m.bucket)) === "bucket",
);
check("…and not to the disk", !readFileSafe(name.file));
check(
"read from the bucket",
(await readCached(name, 60_000, m.bucket))?.equals(PNG) ?? false,
);
check(
"older than its age is not read",
(await readCached(name, 60_000, m.bucket, Date.now() + 120_000)) === null,
);
const down = memoryBucket({ value: "down" });
check(
"a bucket that is down: the folder",
(await writeCached(name, PNG, "image/jpeg", down.bucket)) === "disk",
);
check(
"…and read back from it",
(await readCached(name, 60_000, down.bucket))?.equals(PNG) ?? false,
);
const legacy = { key: "cache/x/b.jpg", file: join(dir, "b.jpg") };
writeFileSync(legacy.file, PNG);
check(
"a picture kept on disk before the bucket is still found",
(await readCached(legacy, 60_000, m.bucket))?.equals(PNG) ?? false,
);
const t = (Date.now() - 120_000) / 1000;
utimesSync(legacy.file, t, t);
check("a stale file is not read", (await readCached(legacy, 60_000, null)) === null);
check(
"no bucket: the folder",
(await writeCached(legacy, PNG, "image/jpeg", null)) === "disk",
);
const sweep = memoryBucket();
await sweep.bucket.put("cache/s/old.jpg", PNG, "image/jpeg");
await sweep.bucket.put("cache/s/new.jpg", PNG, "image/jpeg");
const dropped = await sweepCached("cache/s/", 60_000, sweep.bucket, Date.now() + 120_000, 0);
check(
"the bucket's sweep drops what is past its age",
dropped === 2 && sweep.objects.size === 0,
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
}
console.log("the drain");
await drainTests();
console.log(`\n${passed} checks passed`);
}
function readFileSafe(file: string): Buffer | null {
try {
return readFileSync(file);
} catch {
return null;
}
}
/** A table in memory, moved the way drain-sources.ts moves the real ones. */
function memoryTable(n: number) {
const rows = new Map<string, { data: Buffer | null; objectKey: string | null }>();
for (let i = 0; i < n; i++)
rows.set(`id-${String(i).padStart(3, "0")}`, { data: PNG, objectKey: null });
let batches = 0;
const source: DrainSource = {
name: "chat-images",
async remaining() {
return [...rows.values()].filter((r) => r.data).length;
},
async batch(after, limit) {
batches++;
return [...rows.entries()]
.filter(([id, r]) => r.data && (after === null || id > after))
.sort(([a], [b]) => (a < b ? -1 : 1))
.slice(0, limit)
.map(([id, r]) => ({ id, bytes: r.data!.length }));
},
async move(row, bucket) {
const r = rows.get(row.id)!;
const key = `chat/u/c/${row.id}.png`;
await putVerified(bucket, key, r.data!, "image/png");
// One statement: the key and the null together.
rows.set(row.id, { data: null, objectKey: key });
return "moved";
},
};
return { rows, source, batches: () => batches };
}
function options(over: Partial<DrainOptions> = {}) {
const sleeps: number[] = [];
const o: DrainOptions = {
batchRows: 2,
bytesPerSecond: 1e9,
pauseMs: 1,
firstBackoffMs: 100,
maxBackoffMs: 400,
idleMs: 5_000,
maxPasses: 1,
enabled: () => true,
sleep: async (ms) => void sleeps.push(ms),
log: () => undefined,
...over,
};
return { o, sleeps };
}
const freeLock: DrainLock = async (fn) => ({ acquired: true, value: await fn() });
async function drainTests() {
{
resetDrainStatus();
const m = memoryBucket();
const t = memoryTable(5);
const { o } = options();
await runDrain(m.bucket, [t.source], freeLock, o);
check(
"every row moved: key set, bytes gone",
[...t.rows.values()].every((r) => r.data === null && r.objectKey),
);
check("…and the bucket holds every one", m.objects.size === 5);
check("the status counts them", drainStatus().sources["chat-images"].moved === 5);
}
{
resetDrainStatus();
const m = memoryBucket({ value: "truncates" });
const t = memoryTable(3);
const { o, sleeps } = options({ maxPasses: 3 });
await runDrain(m.bucket, [t.source], freeLock, o);
check(
"a bucket that does not hold the bytes: no row loses them",
[...t.rows.values()].every((r) => r.data !== null && r.objectKey === null),
);
const backoffs = sleeps.filter((ms) => ms >= 100);
check(
"failures back off, doubling, to the cap",
backoffs.slice(0, 4).join() === "100,200,400,400" && backoffs.every((ms) => ms <= 400),
);
check("the failure is on the status", drainStatus().sources["chat-images"].failed > 0);
}
{
resetDrainStatus();
const m = memoryBucket({ value: "down" });
const t = memoryTable(2);
const { o } = options();
await runDrain(m.bucket, [t.source], freeLock, o);
check(
"the error on /api/health carries no address",
!(drainStatus().lastError ?? "").includes("https://"),
);
// Back up: the next run moves them.
m.mode.value = "ok";
await runDrain(m.bucket, [t.source], freeLock, options().o);
check(
"a recovered bucket gets them all",
[...t.rows.values()].every((r) => r.data === null),
);
}
{
resetDrainStatus();
const m = memoryBucket();
const t = memoryTable(3);
const { o, sleeps } = options();
const taken: DrainLock = async () => ({ acquired: false });
await runDrain(m.bucket, [t.source], taken, o);
check("another instance holds the lock: this one reads no batch", t.batches() === 0);
check("…moves nothing", m.objects.size === 0);
const { o: o2, sleeps: s2 } = options({ maxPasses: 2 });
await runDrain(m.bucket, [t.source], taken, o2);
check("…and looks again after the idle wait", s2.includes(5_000));
}
{
resetDrainStatus();
let active = 0;
let overlapped = false;
const exclusive: DrainLock = async (fn) => {
if (active > 0) {
overlapped = true;
return { acquired: false };
}
active++;
try {
return { acquired: true, value: await fn() };
} finally {
active--;
}
};
const m = memoryBucket();
const t = memoryTable(8);
await Promise.all([
runDrain(m.bucket, [t.source], exclusive, options({ maxPasses: 3 }).o),
runDrain(m.bucket, [t.source], exclusive, options({ maxPasses: 3 }).o),
]);
check("the second instance was refused while the first held it", overlapped);
check(
"…so no picture was written twice",
m.calls.filter((c) => c.startsWith("put")).length === 8,
);
check(
"…and between them every row moved once",
[...t.rows.values()].every((r) => r.data === null),
);
}
{
resetDrainStatus();
const m = memoryBucket();
const t = memoryTable(3);
let on = true;
const { o } = options({ enabled: () => on, maxPasses: undefined });
on = false;
const ended = await runDrain(m.bucket, [t.source], freeLock, o);
check("IMAGE_DRAIN=0 stops it before a batch", ended === "off" && m.objects.size === 0);
check("…and the status says off", drainStatus().state === "off");
}
{
resetDrainStatus();
const m = memoryBucket();
let moves = 0;
const skipping: DrainSource = {
name: "feedback-screenshots",
remaining: async () => 1,
batch: async (after) => (after === null ? [{ id: "odd", bytes: 1 }] : []),
move: async () => {
moves++;
return "skip";
},
};
await runDrain(m.bucket, [skipping], freeLock, options({ maxPasses: 3 }).o);
check("a row that cannot be moved is tried once, then left alone", moves === 1);
check("…and counted as skipped", drainStatus().sources["feedback-screenshots"].skipped === 1);
}
{
resetDrainStatus();
const m = memoryBucket();
const broken: DrainSource = {
name: "command-attachments",
remaining: async () => 1,
batch: async () => {
throw new Error("connection reset");
},
move: async () => "moved",
};
const { o, sleeps } = options({ maxPasses: 2 });
const ended = await runDrain(m.bucket, [broken], freeLock, o);
check("a failing database backs off instead of crashing the drain", ended === "stopped");
check("…with the backoff", sleeps.includes(100));
}
}
main().catch((e) => {
console.error(e);
process.exit(1);
});