Dough Git

commit

Update CDN with speed and QOL improvements

commit
afc97b3296bdf6038df48a8fafa367cdd1b898bd
author
Clove Twilight <[email protected]>
date
2026-11-11 15:27

diff --git a/src/files.ts b/src/files.ts
index e21df86..431ae8f 100644
--- a/src/files.ts
+++ b/src/files.ts
@@ -122,8 +122,38 @@ function fileHeaders(obj: R2Object): Headers {
   return headers;
 }
 
-/** GET /api/list — flat list of every object, for the browser. */
-export async function listFiles(c: AppContext): Promise<Response> {
+// Seconds the listing stays in the edge cache. Writes purge it in their own
+// data centre; the others catch up when this runs out.
+const LIST_TTL = 60;
+
+function listCacheKey(c: AppContext): Request {
+  return new Request(new URL("/api/list", c.req.url).href);
+}
+
+/** Drops the cached listing. Called after every upload, new folder and delete. */
+async function purgeList(c: AppContext): Promise<void> {
+  await caches.default.delete(listCacheKey(c));
+}
+
+async function etagOf(body: string): Promise<string> {
+  const digest = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(body));
+  const hex = [...new Uint8Array(digest)]
+    .map((byte) => byte.toString(16).padStart(2, "0"))
+    .join("");
+  return `"${hex}"`;
+}
+
+/** True if the browser's If-None-Match names this ETag (weak or strong). */
+function etagMatches(header: string | undefined, etag: string | null): boolean {
+  if (!header || !etag) return false;
+  return header
+    .split(",")
+    .map((value) => value.trim().replace(/^W\//, ""))
+    .includes(etag);
+}
+
+/** Scans the whole bucket and builds the listing response. */
+async function buildList(c: AppContext): Promise<Response> {
   const files: { path: string; size: number }[] = [];
   let cursor: string | undefined;
   do {
@@ -132,8 +162,40 @@ export async function listFiles(c: AppContext): Promise<Response> {
     cursor = page.truncated ? page.cursor : undefined;
   } while (cursor);
 
-  c.header("Cache-Control", "public, max-age=60");
-  return c.json({ count: files.length, raw: rawBase(c.env), files });
+  const body = JSON.stringify({
+    count: files.length,
+    raw: rawBase(c.env),
+    files,
+  });
+
+  return new Response(body, {
+    headers: {
+      "Content-Type": "application/json",
+      // Browsers revalidate (a 304 when nothing changed); the edge keeps it for LIST_TTL
+      "Cache-Control": `public, max-age=0, s-maxage=${LIST_TTL}`,
+      ETag: await etagOf(body),
+    },
+  });
+}
+
+/**
+ * GET /api/list — flat list of every object, for the browser. Served from the
+ * edge cache when it can be; ?fresh=1 skips the cache and refills it.
+ */
+export async function listFiles(c: AppContext): Promise<Response> {
+  const cacheKey = listCacheKey(c);
+  const fresh = c.req.query("fresh") === "1";
+
+  let response = fresh ? undefined : await caches.default.match(cacheKey);
+  if (!response) {
+    response = await buildList(c);
+    c.executionCtx.waitUntil(caches.default.put(cacheKey, response.clone()));
+  }
+
+  if (etagMatches(c.req.header("If-None-Match"), response.headers.get("ETag"))) {
+    return new Response(null, { status: 304, headers: response.headers });
+  }
+  return response;
 }
 
 /** PUT /api/files/<key> — raw request body becomes the object. */
@@ -156,6 +218,7 @@ export async function uploadFile(c: AppContext, key: string, uploader: string):
     httpMetadata: { contentType },
     customMetadata: { uploadedBy: uploader },
   });
+  await purgeList(c);
   return c.json({ path: obj.key, size: obj.size, url: `${rawBase(c.env)}/${encodeKey(obj.key)}` }, 201);
 }
 
@@ -167,6 +230,7 @@ export async function createFolder(c: AppContext, key: string, uploader: string)
   if (await isFolder(c, key)) return c.json({ error: "That folder already exists." }, 409);
 
   await c.env.BUCKET.put(`${key}/${FOLDER_MARKER}`, "", { customMetadata: { uploadedBy: uploader } });
+  await purgeList(c);
   return c.json({ path: key }, 201);
 }
 
@@ -184,6 +248,7 @@ export async function deleteFile(c: AppContext, key: string, uploader: string):
   if (keep && !(await isFolder(c, keep))) {
     await c.env.BUCKET.put(`${keep}/${FOLDER_MARKER}`, "", { customMetadata: { uploadedBy: uploader } });
   }
+  await purgeList(c);
   return c.body(null, 204);
 }
 
diff --git a/src/main.ts b/src/main.ts
index 08812ac..77020ca 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -101,7 +101,7 @@ app.get("/.well-known/change-password", (c) => c.redirect(`${issuer(c.env)}/acco
 
 app.get("*", async (c) => {
   const asset = await c.env.ASSETS.fetch(c.req.raw);
-  if (asset.status !== 404) return asset;
+  if (asset.status !== 404) return withAssetCache(c, asset);
 
   const key = keyFromPath(c);
   if (key === null) return notFound(c);
@@ -110,6 +110,28 @@ app.get("*", async (c) => {
   return (await isFolder(c, key.replace(/\/+$/, ""))) ? shell(c) : notFound(c);
 });
 
+// Vite's hashed bundle files: a new build gets a new name, so they never change
+const HASHED_ASSET = /^\/_app\/[^/]+-[A-Za-z0-9_-]{8}\.(js|css)$/;
+
+const HASHED_CACHE = "public, max-age=31536000, immutable";
+
+// Fonts and the background keep their names, so they get a month instead
+const APP_CACHE = "public, max-age=2592000";
+
+/** Static assets default to max-age=0; everything under /_app can be kept. */
+function withAssetCache(c: AppContext, asset: Response): Response {
+  const pathname = new URL(c.req.url).pathname;
+  const cacheable = asset.status === 200 || asset.status === 304;
+  if (!cacheable || !pathname.startsWith("/_app/")) return asset;
+
+  const response = new Response(asset.body, asset);
+  response.headers.set(
+    "Cache-Control",
+    HASHED_ASSET.test(pathname) ? HASHED_CACHE : APP_CACHE,
+  );
+  return response;
+}
+
 /** The R2 key a path names (after `prefix`), or null if it doesn't decode. */
 function keyFromPath(c: AppContext, prefix = "/"): string | null {
   try {
diff --git a/web/src/App.svelte b/web/src/App.svelte
index f78638e..1bf5d7b 100644
--- a/web/src/App.svelte
+++ b/web/src/App.svelte
@@ -14,25 +14,39 @@
 
   // Fetched once whatever page the visit starts on, since in-app navigation
   // never reloads. After any change it's refetched fresh.
-  function load(fresh = false) {
+  function load(fresh = false): Promise<void> {
     return fetchList(fresh)
-      .then((l) => {
-        listing = l;
+      .then((loaded) => {
+        // The edge copy can be a minute old: if this page isn't in it, ask again
+        if (!fresh && !hasPath(loaded, currentPath())) return load(true);
+        listing = loaded;
         failed = false;
       })
-      .catch(() => (failed = true));
+      .catch(() => {
+        failed = true;
+      });
   }
-  load();
-  fetchMe().then((m) => (me = m));
 
-  // "/img/avatars/" → "img/avatars"; null if the path doesn't decode.
-  const path = $derived.by(() => {
+  function currentPath(): string | null {
     try {
       return decodeURIComponent(route.path).replace(/^\/+|\/+$/g, "");
     } catch {
       return null;
     }
-  });
+  }
+
+  /** True if `target` is the top level, a file, or a folder in the listing. */
+  function hasPath(loaded: Listing, target: string | null): boolean {
+    if (!target || route.path === "/licence") return true;
+    return loaded.files.some(
+      (entry) => entry.path === target || entry.path.startsWith(`${target}/`),
+    );
+  }
+  load();
+  fetchMe().then((m) => (me = m));
+
+  // "/img/avatars/" → "img/avatars"; null if the path doesn't decode.
+  const path = $derived(currentPath());
 
   // An exact object is a file (unless the URL ends in a slash); anything else browses.
   const file = $derived(
diff --git a/web/src/lib/files.ts b/web/src/lib/files.ts
index e842884..43542c6 100644
--- a/web/src/lib/files.ts
+++ b/web/src/lib/files.ts
@@ -23,7 +23,10 @@ export function encodePath(path: string): string {
 }
 
 export async function fetchList(fresh = false): Promise<Listing> {
-  const res = await fetch("/api/list", { cache: fresh ? "no-store" : "no-cache" });
+  // ?fresh=1 makes the worker skip its edge cache too
+  const res = fresh
+    ? await fetch("/api/list?fresh=1", { cache: "no-store" })
+    : await fetch("/api/list", { cache: "no-cache" });
   if (!res.ok) throw new Error(`list failed: ${res.status}`);
   return res.json();
 }