From 8526676945393625a9c87a196d27c825a24314aa Mon Sep 17 00:00:00 2001 From: Aaron Filson Date: Sun, 29 Nov 2026 11:59:16 -0800 Subject: [PATCH 1/2] Improve traffic-spike resilience and auto-warm uploaded photos --- backend/src/notify-sale.mjs | 12 +-- backend/test/checkout-flow.test.mjs | 2 +- deploy/site.yaml | 27 ++++++ deploy/stages.json | 2 +- scripts/load-items.mjs | 21 +++-- scripts/replace-photos.mjs | 25 +++++- scripts/warm-photos.mjs | 123 ++++++++++++++++++++-------- site/js/api.js | 17 +++- site/js/shop.js | 18 ++-- site/js/test/api.test.mjs | 20 ++++- site/js/test/seo.test.mjs | 29 +++++++ 11 files changed, 238 insertions(+), 58 deletions(-) diff --git a/backend/src/notify-sale.mjs b/backend/src/notify-sale.mjs index 220e469..fd74908 100644 --- a/backend/src/notify-sale.mjs +++ b/backend/src/notify-sale.mjs @@ -1,6 +1,6 @@ -// Best-effort post-sale refresh: clears CloudFront's 5-minute /p/* cache for sold pieces and their -// feeds, and notifies IndexNow on production. Never throws, so a CDN or IndexNow hiccup cannot affect -// an already-completed payment response. +// Best-effort post-sale refresh: clears CloudFront's /p/* and 15-second /api/catalog caches for +// sold pieces and feeds, and notifies IndexNow on production. Never throws, so a CDN or IndexNow +// hiccup cannot affect an already-completed payment response. const INDEXNOW_KEY = "b8f4c2e9a1d740639e5c82b1f7a3d904"; let cfClientPromise; @@ -18,7 +18,7 @@ function cloudFrontInvalidate(distributionId, paths) { Paths: { Quantity: items.length, Items: items }, }, }), - { abortSignal: AbortSignal.timeout(3_000) }, + { abortSignal: AbortSignal.timeout(1_500) }, ); })().catch((err) => { cfClientPromise = undefined; @@ -47,7 +47,7 @@ export async function afterSale(itemIds) { const tasks = []; if (distId) { - const paths = [...ids.map((id) => `/p/${encodeURIComponent(id)}`), "/p/sitemap.xml", "/p/feed.xml", "/p/merchant.xml"]; + const paths = ["/p/*", "/api/catalog"]; const run = customInvalidator ?? cloudFrontInvalidate; tasks.push( run(distId, paths).catch((err) => { @@ -69,7 +69,7 @@ export async function afterSale(itemIds) { keyLocation: `${origin}/${INDEXNOW_KEY}.txt`, urlList, }), - signal: AbortSignal.timeout(3_000), + signal: AbortSignal.timeout(1_500), }) .then((res) => { if (res.status >= 400) console.error("SALE_INDEXNOW_FAILED", `HTTP ${res.status}`); diff --git a/backend/test/checkout-flow.test.mjs b/backend/test/checkout-flow.test.mjs index 1927de4..101bdc5 100644 --- a/backend/test/checkout-flow.test.mjs +++ b/backend/test/checkout-flow.test.mjs @@ -319,7 +319,7 @@ test("a completed sale clears /p/* caches and pings IndexNow on production witho fresh(); assert.equal((await post(body("sale-1"))).status, 200); - assert.deepEqual(invalidations, [["EDIST123", ["/p/I1", "/p/sitemap.xml", "/p/feed.xml", "/p/merchant.xml"]]]); + assert.deepEqual(invalidations, [["EDIST123", ["/p/*", "/api/catalog"]]]); assert.equal(indexNowBodies.length, 1); assert.deepEqual(indexNowBodies[0].urlList, [ "https://updraftpotterystudio.com/", diff --git a/deploy/site.yaml b/deploy/site.yaml index cf2b8dd..ee36ab6 100644 --- a/deploy/site.yaml +++ b/deploy/site.yaml @@ -201,6 +201,23 @@ Resources: HeadersConfig: { HeaderBehavior: none } CookiesConfig: { CookieBehavior: none } QueryStringsConfig: { QueryStringBehavior: none } + # Catalog JSON (/api/catalog) follows the origin's 15s cache-control so traffic spikes hit the edge + # instead of the Api Lambda; completed checkouts invalidate /api/catalog immediately. + CatalogCachePolicy: + Type: AWS::CloudFront::CachePolicy + Condition: HasApi + Properties: + CachePolicyConfig: + Name: !Sub updraft-catalog${NameSuffix} + MinTTL: 0 + DefaultTTL: 15 + MaxTTL: 15 + ParametersInCacheKeyAndForwardedToOrigin: + EnableAcceptEncodingGzip: true + EnableAcceptEncodingBrotli: true + HeadersConfig: { HeaderBehavior: none } + CookiesConfig: { CookieBehavior: none } + QueryStringsConfig: { QueryStringBehavior: none } SecurityHeaders: Type: AWS::CloudFront::ResponseHeadersPolicy @@ -356,6 +373,16 @@ Resources: CachePolicyId: !Ref ImageCachePolicy ResponseHeadersPolicyId: !Ref SecurityHeaders - !Ref AWS::NoValue + - !If + - HasApi + - PathPattern: /api/catalog + TargetOriginId: api + ViewerProtocolPolicy: https-only + AllowedMethods: [GET, HEAD] + Compress: true + CachePolicyId: !Ref CatalogCachePolicy + ResponseHeadersPolicyId: !Ref SecurityHeaders + - !Ref AWS::NoValue - !If - HasApi - PathPattern: /api/* diff --git a/deploy/stages.json b/deploy/stages.json index 77cc53f..b04bb2f 100644 --- a/deploy/stages.json +++ b/deploy/stages.json @@ -11,7 +11,7 @@ "squareLocationId": "CQ5ZYKRG4KNAQ", "squareTokenParam": "/updraft/prod/square-access-token", "newsletterGroupId": "7P07F7ZHJ3BJHT0PV01WJBSV24", - "apiConcurrency": 5, + "apiConcurrency": 15, "imagesConcurrency": 5, "alertEmail": "aaronfilson@gmail.com" }, diff --git a/scripts/load-items.mjs b/scripts/load-items.mjs index 566f7bb..b14bffe 100644 --- a/scripts/load-items.mjs +++ b/scripts/load-items.mjs @@ -7,7 +7,7 @@ // node scripts/load-items.mjs scripts/items/2026-10-13.json --stage staging dry run // node scripts/load-items.mjs scripts/items/2026-10-13.json --stage staging --go load // node scripts/load-items.mjs scripts/items/2026-10-13.json --go production -// Options: --photos overrides the batch file's photoDir. +// Options: --photos overrides the batch file's photoDir; --no-warm skips auto-warming photo caches. import { readFileSync, existsSync } from "node:fs"; import { randomUUID } from "node:crypto"; import path from "node:path"; @@ -16,13 +16,15 @@ import { squareClient, squareErrorMessage } from "./square-client.mjs"; import { ensureCatalogAttributes, SHIP_LB_KEY, ITEM_LB_KEY } from "./ship-weight-attribute.mjs"; import { listingJpeg } from "./listing-photo.mjs"; import { submitIndexNow } from "./indexnow.mjs"; +import { warmPhotos } from "./warm-photos.mjs"; import { parseDimensions, googleCategoryFor } from "../backend/src/piece-page.mjs"; const args = process.argv.slice(2); const opt = (name) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined); const file = args.find((a) => a.endsWith(".json")); -if (!file) throw new Error("Usage: node scripts/load-items.mjs [--stage staging] [--photos ] [--go]"); +if (!file) throw new Error("Usage: node scripts/load-items.mjs [--stage staging] [--photos ] [--no-warm] [--go]"); const GO = args.includes("--go"); +const NO_WARM = args.includes("--no-warm"); const stage = currentStage(); const batch = JSON.parse(readFileSync(file, "utf8")); const photoDir = opt("--photos") ?? batch.photoDir; @@ -52,6 +54,7 @@ console.log( `${GO ? "Loading" : "Dry run (add --go to load)"}: ${batch.items.length} items into Square ${stage.squareEnv} for stage "${stage.name}", location ${stage.squareLocationId}`, ); const square = await squareClient(stage); +const createdIds = []; try { const existing = new Set(); @@ -77,7 +80,6 @@ try { categories.set(name, catalogObject.id); } - const createdIds = []; for (const it of batch.items) { if (existing.has(it.name)) { console.log(`skip ${it.name} (already in the catalog)`); @@ -165,6 +167,15 @@ try { console.error(squareErrorMessage(err)); process.exitCode = 1; } -// The first visitors would otherwise all wait on the resizer at once (see scripts/warm-photos.mjs). const warmCmd = `npm run warm-photos${stage.name === "prod" ? "" : ` -- --stage ${stage.name}`}`; -if (GO && !process.exitCode) console.log(`In a minute, once the shop shows the new photos, run: ${warmCmd}`); +if (GO && !process.exitCode && createdIds.length) { + if (NO_WARM) { + console.log(`In a minute, once the shop shows the new photos, run: ${warmCmd}`); + } else { + const tally = await warmPhotos(stage, { waitForIds: createdIds }); + if (tally.failed.length) { + console.log(`Some photos failed to warm; re-run: ${warmCmd}`); + process.exitCode = 1; + } + } +} diff --git a/scripts/replace-photos.mjs b/scripts/replace-photos.mjs index f7caa93..75039e7 100644 --- a/scripts/replace-photos.mjs +++ b/scripts/replace-photos.mjs @@ -4,20 +4,24 @@ // node scripts/replace-photos.mjs scripts/items/2026-10-13.json --stage staging dry run // node scripts/replace-photos.mjs scripts/items/2026-10-13.json --stage staging --go replace // node scripts/replace-photos.mjs scripts/items/2026-10-13.json --go production -// Options: --photos overrides the batch file's photoDir; --only "" does one piece. +// Options: --photos overrides the batch file's photoDir; --only "" does one piece; --no-warm skips auto-warming. import { readFileSync, existsSync } from "node:fs"; import { randomUUID } from "node:crypto"; import path from "node:path"; import { currentStage } from "./stage.mjs"; import { squareClient, squareErrorMessage } from "./square-client.mjs"; import { listingJpeg } from "./listing-photo.mjs"; +import { warmPhotos } from "./warm-photos.mjs"; const args = process.argv.slice(2); const opt = (name) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined); const file = args.find((a) => a.endsWith(".json")); if (!file) - throw new Error("Usage: node scripts/replace-photos.mjs [--stage staging] [--photos ] [--only ] [--go]"); + throw new Error( + "Usage: node scripts/replace-photos.mjs [--stage staging] [--photos ] [--only ] [--no-warm] [--go]", + ); const GO = args.includes("--go"); +const NO_WARM = args.includes("--no-warm"); const stage = currentStage(); const batch = JSON.parse(readFileSync(file, "utf8")); const photoDir = opt("--photos") ?? batch.photoDir; @@ -31,6 +35,8 @@ console.log( `${GO ? "Replacing" : "Dry run (add --go to replace)"}: photos of ${items.length} items in Square ${stage.squareEnv} for stage "${stage.name}"`, ); const square = await squareClient(stage); +const replacedIds = []; +const uploadedUrls = []; try { const byName = new Map(); @@ -59,10 +65,12 @@ try { imageFile: new Blob([jpeg], { type: "image/jpeg" }), }); fresh.push(image.id); + if (image.imageData?.url) uploadedUrls.push(image.imageData.url); } const { object: item } = await square.catalog.object.get({ objectId: id }); item.itemData.imageIds = fresh; await square.catalog.object.upsert({ idempotencyKey: randomUUID(), object: item }); + replacedIds.push(id); const stale = old.filter((x) => !fresh.includes(x)); if (stale.length) await square.catalog.batchDelete({ objectIds: stale }); console.log(` done: ${fresh.length} new, ${stale.length} old deleted`); @@ -71,6 +79,15 @@ try { console.error(squareErrorMessage(err)); process.exitCode = 1; } -// The first visitors would otherwise all wait on the resizer at once (see scripts/warm-photos.mjs). const warmCmd = `npm run warm-photos${stage.name === "prod" ? "" : ` -- --stage ${stage.name}`}`; -if (GO && !process.exitCode) console.log(`In a minute, once the shop shows the new photos, run: ${warmCmd}`); +if (GO && !process.exitCode && replacedIds.length) { + if (NO_WARM) { + console.log(`In a minute, once the shop shows the new photos, run: ${warmCmd}`); + } else { + const tally = await warmPhotos(stage, { waitForIds: replacedIds, waitForUrls: uploadedUrls }); + if (tally.failed.length) { + console.log(`Some photos failed to warm; re-run: ${warmCmd}`); + process.exitCode = 1; + } + } +} diff --git a/scripts/warm-photos.mjs b/scripts/warm-photos.mjs index 5c02aac..5e786b3 100644 --- a/scripts/warm-photos.mjs +++ b/scripts/warm-photos.mjs @@ -1,13 +1,13 @@ // Makes every resized copy of the shop's photos that the site asks for, so the first visitors after // new pieces go up get them from CloudFront's cache instead of all waiting on the resizer at once (it // handles imagesConcurrency at a time, deploy/stages.json; past that it answers 429). -// Asks two at a time, through the site like a visitor. Run it a minute after photos change in -// Square (load-items, replace-photos or the Dashboard), once the shop shows the new photos. +// Run automatically at the end of load-items and replace-photos, or manually via: // npm run warm-photos production // npm run warm-photos -- --stage staging staging +import path from "node:path"; +import { fileURLToPath } from "node:url"; import { currentStage } from "./stage.mjs"; -const stage = currentStage(); const AT_ONCE = 2; // The sizes the site uses (site/js/shop.js cards, site/js/piece-view.js, and backend/src/piece-page.mjs: @@ -23,38 +23,93 @@ const MAIN = [ ]; const OTHER = MAIN; -const res = await fetch(`${stage.siteUrl}/api/catalog`); -if (!res.ok) throw new Error(`${stage.siteUrl}/api/catalog answered ${res.status}`); -const body = await res.json(); -const urls = (body.items ?? body).flatMap((item) => - (item.images?.length ? item.images : [item.image].filter(Boolean)).flatMap((photo, i) => - (i === 0 ? MAIN : OTHER).map(([w, f]) => `${stage.siteUrl}/api/img?u=${encodeURIComponent(photo)}&w=${w}&f=${f}`), - ), -); -console.log(`Warming ${urls.length} photo copies on ${stage.siteUrl}, ${AT_ONCE} at a time`); - const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); -const tally = { hit: 0, made: 0, failed: [] }; -async function warm(url) { - for (let attempt = 1; attempt <= 5; attempt++) { - const r = await fetch(url); - await r.arrayBuffer(); - if (r.ok) return tally[/hit/i.test(r.headers.get("x-cache") ?? "") ? "hit" : "made"]++; - // 429/5xx: the resizer is busy. 404: the resizer hasn't seen the new catalog yet, and CloudFront - // keeps that answer for a minute. - if (r.status === 404 && attempt < 3) await sleep(65_000); - else if ((r.status === 429 || r.status >= 500) && attempt < 5) await sleep(1000 * 2 ** attempt); - else return tally.failed.push(`${r.status} ${url}`); + +/** + * Polls `/api/catalog` until optional newly uploaded item IDs / photo URLs are visible, then warms + * every resized `/api/img` variant for the stage's catalog through CloudFront. + * @param {{ siteUrl: string }} stage + * @param {{ waitForIds?: string[], waitForUrls?: string[], pollMs?: number, maxWaitMs?: number, retryNotFoundMs?: number, retryBusyBaseMs?: number, fetchImpl?: typeof fetch }} [opts] + */ +export async function warmPhotos( + stage, + { + waitForIds = [], + waitForUrls = [], + pollMs = 5_000, + maxWaitMs = 45_000, + retryNotFoundMs = 65_000, + retryBusyBaseMs = 1000, + fetchImpl = fetch, + } = {}, +) { + const readCatalog = async () => { + const res = await fetchImpl(`${stage.siteUrl}/api/catalog`); + if (!res.ok) throw new Error(`${stage.siteUrl}/api/catalog answered ${res.status}`); + const body = await res.json(); + return body.items ?? body; + }; + const ready = (items) => { + const itemIds = new Set(items.map((i) => i.id)); + const photoUrls = new Set(items.flatMap((i) => (i.images?.length ? i.images : [i.image].filter(Boolean)))); + return waitForIds.every((id) => itemIds.has(id)) && waitForUrls.every((u) => photoUrls.has(u)); + }; + + let items = []; + const needWait = waitForIds.length > 0 || waitForUrls.length > 0; + const deadline = Date.now() + maxWaitMs; + let waited = false; + for (;;) { + try { + items = await readCatalog(); + if (!needWait || ready(items)) break; + } catch (err) { + if (!needWait || Date.now() >= deadline) throw err; + } + if (Date.now() >= deadline) { + console.warn("Catalog did not show all newly uploaded items/photos yet; warming current catalog."); + break; + } + if (!waited) { + console.log(`Waiting for ${stage.siteUrl}/api/catalog to pick up newly uploaded pieces/photos...`); + waited = true; + } + await sleep(pollMs); } + + const urls = items.flatMap((item) => + (item.images?.length ? item.images : [item.image].filter(Boolean)).flatMap((photo, i) => + (i === 0 ? MAIN : OTHER).map(([w, f]) => `${stage.siteUrl}/api/img?u=${encodeURIComponent(photo)}&w=${w}&f=${f}`), + ), + ); + console.log(`Warming ${urls.length} photo copies on ${stage.siteUrl}, ${AT_ONCE} at a time`); + + const tally = { hit: 0, made: 0, failed: [] }; + async function warm(url) { + for (let attempt = 1; attempt <= 5; attempt++) { + const r = await fetchImpl(url); + await r.arrayBuffer(); + if (r.ok) return tally[/hit/i.test(r.headers.get("x-cache") ?? "") ? "hit" : "made"]++; + // 429/5xx: the resizer is busy. 404: the resizer hasn't seen the new catalog yet, and CloudFront + // keeps that answer for a minute. + if (r.status === 404 && attempt < 3) await sleep(retryNotFoundMs); + else if ((r.status === 429 || r.status >= 500) && attempt < 5) await sleep(retryBusyBaseMs * 2 ** attempt); + else return tally.failed.push(`${r.status} ${url}`); + } + } + const queue = [...urls]; + await Promise.all( + Array.from({ length: AT_ONCE }, async () => { + while (queue.length) await warm(queue.shift()); + }), + ); + console.log(`Done: ${tally.made} made, ${tally.hit} already cached, ${tally.failed.length} failed`); + if (tally.failed.length) console.log(tally.failed.join("\n")); + return tally; } -const queue = [...urls]; -await Promise.all( - Array.from({ length: AT_ONCE }, async () => { - while (queue.length) await warm(queue.shift()); - }), -); -console.log(`Done: ${tally.made} made, ${tally.hit} already cached, ${tally.failed.length} failed`); -if (tally.failed.length) { - console.log(tally.failed.join("\n")); - process.exitCode = 1; + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const stage = currentStage(); + const tally = await warmPhotos(stage); + if (tally.failed.length) process.exitCode = 1; } diff --git a/site/js/api.js b/site/js/api.js index 29c5e24..02a1085 100644 --- a/site/js/api.js +++ b/site/js/api.js @@ -8,7 +8,22 @@ export async function sha256Hex(text) { return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); } -export const getJson = (path) => fetch(`${config.apiBase}${path}`); +/** + * Fetches JSON from the shop API with short jittered retries on transient 429/5xx or network errors. + * @param {string} path + * @param {{ retries?: number, baseMs?: number }} [opts] + */ +export async function getJson(path, { retries = 2, baseMs = 250 } = {}) { + for (let attempt = 1; ; attempt++) { + try { + const res = await fetch(`${config.apiBase}${path}`); + if ((res.status !== 429 && res.status < 500) || attempt > retries) return res; + } catch (err) { + if (attempt > retries) throw err; + } + await new Promise((ok) => setTimeout(ok, baseMs * 2 ** (attempt - 1) * (0.5 + Math.random()))); + } +} export async function postJson(path, data) { const body = JSON.stringify(data); diff --git a/site/js/shop.js b/site/js/shop.js index 1329cf6..e905872 100644 --- a/site/js/shop.js +++ b/site/js/shop.js @@ -479,12 +479,20 @@ function requestQuote() { // Short debounce so clicking + several times sends one request. quoteTimer = setTimeout(async () => { const seq = ++quoteSeq; + const payload = { + lines: getCart().map((l) => ({ variationId: l.variationId, quantity: l.quantity })), + fulfillment: form.fulfillment.value, + destination: shipDestination() ?? undefined, + }; try { - const res = await postJson("/api/quote", { - lines: getCart().map((l) => ({ variationId: l.variationId, quantity: l.quantity })), - fulfillment: form.fulfillment.value, - destination: shipDestination() ?? undefined, - }); + let res; + for (let attempt = 1; ; attempt++) { + res = await postJson("/api/quote", payload); + if (seq !== quoteSeq) return; // a newer cart change is already being looked up + if (res.status !== 429 || attempt >= 3) break; + await new Promise((ok) => setTimeout(ok, 250 * attempt + Math.random() * 250)); + if (seq !== quoteSeq) return; + } const out = await res.json().catch(() => ({})); if (seq !== quoteSeq) return; // a newer cart change is already being looked up if (res.status === 409 && out.sold) { diff --git a/site/js/test/api.test.mjs b/site/js/test/api.test.mjs index 4778abe..48f8df0 100644 --- a/site/js/test/api.test.mjs +++ b/site/js/test/api.test.mjs @@ -2,7 +2,7 @@ import "./setup.mjs"; import test from "node:test"; import assert from "node:assert/strict"; -const { sha256Hex, postJson } = await import("../api.js"); +const { sha256Hex, getJson, postJson } = await import("../api.js"); test("sha256Hex matches the standard test vectors", async () => { assert.equal(await sha256Hex(""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); @@ -20,3 +20,21 @@ test("POSTs carry the body's hash, which CloudFront-signed Lambda URLs require", assert.equal(seen.init.method, "POST"); assert.equal(seen.init.headers["x-amz-content-sha256"], await sha256Hex(seen.init.body)); }); + +test("getJson retries transient 429 and 5xx answers and returns the first success", async () => { + const statuses = [429, 503, 200]; + let calls = 0; + globalThis.fetch = async () => new Response("{}", { status: statuses[calls++] }); + const res = await getJson("/api/catalog", { retries: 2, baseMs: 1 }); + assert.equal(res.status, 200); + assert.equal(calls, 3); + + let exhausted = 0; + globalThis.fetch = async () => { + exhausted++; + return new Response("{}", { status: 502 }); + }; + const fail = await getJson("/api/catalog", { retries: 2, baseMs: 1 }); + assert.equal(fail.status, 502); + assert.equal(exhausted, 3); +}); diff --git a/site/js/test/seo.test.mjs b/site/js/test/seo.test.mjs index 2fc547c..8737076 100644 --- a/site/js/test/seo.test.mjs +++ b/site/js/test/seo.test.mjs @@ -3,6 +3,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { INDEXNOW_KEY, submitIndexNow } from "../../../scripts/indexnow.mjs"; +import { warmPhotos } from "../../../scripts/warm-photos.mjs"; const SITE = path.resolve(import.meta.dirname, "..", ".."); const PAGES = [ @@ -93,3 +94,31 @@ test("submitIndexNow sends deduplicated same-host URLs and never throws on netwo assert.equal(failed.sent, 0); assert.equal(failed.error, "offline"); }); + +test("warmPhotos polls catalog until newly uploaded items/photos appear and warms all variants", async () => { + let reads = 0; + const warmed = []; + const tally = await warmPhotos( + { siteUrl: "https://example.test" }, + { + waitForIds: ["ITEM_NEW"], + waitForUrls: ["https://cdn.example/p1.jpeg"], + pollMs: 1, + maxWaitMs: 200, + retryBusyBaseMs: 1, + fetchImpl: async (url) => { + if (url === "https://example.test/api/catalog") { + reads++; + const items = reads === 1 ? [] : [{ id: "ITEM_NEW", images: ["https://cdn.example/p1.jpeg"] }]; + return Response.json({ items }); + } + warmed.push(url); + const hit = url.includes("f=jpeg"); + return new Response("ok", { status: 200, headers: hit ? { "x-cache": "Hit from cloudfront" } : {} }); + }, + }, + ); + assert.equal(reads, 2); + assert.equal(warmed.length, 7); + assert.deepEqual(tally, { hit: 1, made: 6, failed: [] }); +}); From a3811698752f322bea2f0c274ec9b149e1cafd78 Mon Sep 17 00:00:00 2001 From: Aaron Filson Date: Sun, 29 Nov 2026 12:57:31 -0800 Subject: [PATCH 2/2] Harden photo warming and expand tests from code review --- deploy/site.yaml | 2 +- scripts/load-items.mjs | 25 +++++++++++++-------- scripts/replace-photos.mjs | 10 +++++++-- scripts/warm-photos.mjs | 21 ++++++++++++----- site/js/test/api.test.mjs | 32 ++++++++++++++++++++++++-- site/js/test/seo.test.mjs | 46 +++++++++++++++++++++++++++++++++++++- 6 files changed, 116 insertions(+), 20 deletions(-) diff --git a/deploy/site.yaml b/deploy/site.yaml index ee36ab6..12b48f4 100644 --- a/deploy/site.yaml +++ b/deploy/site.yaml @@ -351,7 +351,7 @@ Resources: - - EventType: viewer-request FunctionARN: !GetAtt CanonicalRedirects.FunctionARN - !Ref AWS::NoValue - # Order matters: CloudFront uses the first matching pattern, so /api/checkout and /api/img come before /api/*. + # Order matters: CloudFront uses the first matching pattern, so /api/checkout, /api/img and /api/catalog come before /api/*. CacheBehaviors: - !If - HasCheckout diff --git a/scripts/load-items.mjs b/scripts/load-items.mjs index b14bffe..d6bf24e 100644 --- a/scripts/load-items.mjs +++ b/scripts/load-items.mjs @@ -55,6 +55,7 @@ console.log( ); const square = await squareClient(stage); const createdIds = []; +const createdUrls = []; try { const existing = new Set(); @@ -129,7 +130,7 @@ try { // Photos in the order listed; the first is the main one. for (const [i, photo] of it.photos.entries()) { const jpeg = await listingJpeg(path.join(photoDir, photo), batch.crops?.[photo], batch.fill); - await square.catalog.images.create({ + const { image } = await square.catalog.images.create({ request: { idempotencyKey: randomUUID(), objectId: item.id, @@ -138,6 +139,7 @@ try { }, imageFile: new Blob([jpeg], { type: "image/jpeg" }), }); + if (image?.imageData?.url) createdUrls.push(image.imageData.url); } await square.inventory.batchCreateChanges({ idempotencyKey: randomUUID(), @@ -157,12 +159,6 @@ try { createdIds.push(item.id); console.log(` done: ${item.id}`); } - - if (GO && stage.indexable && createdIds.length) { - const urls = [`${stage.siteUrl}/`, `${stage.siteUrl}/shop.html`, ...createdIds.map((id) => `${stage.siteUrl}/p/${id}`)]; - const ix = await submitIndexNow(stage.siteUrl, urls); - console.log(`IndexNow: ${ix.sent ? `notified (${ix.sent} URLs, HTTP ${ix.status})` : `skipped (${ix.error ?? "no URLs"})`}`); - } } catch (err) { console.error(squareErrorMessage(err)); process.exitCode = 1; @@ -172,10 +168,21 @@ if (GO && !process.exitCode && createdIds.length) { if (NO_WARM) { console.log(`In a minute, once the shop shows the new photos, run: ${warmCmd}`); } else { - const tally = await warmPhotos(stage, { waitForIds: createdIds }); - if (tally.failed.length) { + try { + const tally = await warmPhotos(stage, { waitForIds: createdIds, waitForUrls: createdUrls }); + if (tally.failed.length || tally.timedOut) { + console.log(`Some photos failed to warm; re-run: ${warmCmd}`); + process.exitCode = 1; + } + } catch (err) { + console.error(err?.message ?? err); console.log(`Some photos failed to warm; re-run: ${warmCmd}`); process.exitCode = 1; } } + if (stage.indexable) { + const urls = [`${stage.siteUrl}/`, `${stage.siteUrl}/shop.html`, ...createdIds.map((id) => `${stage.siteUrl}/p/${id}`)]; + const ix = await submitIndexNow(stage.siteUrl, urls); + console.log(`IndexNow: ${ix.sent ? `notified (${ix.sent} URLs, HTTP ${ix.status})` : `skipped (${ix.error ?? "no URLs"})`}`); + } } diff --git a/scripts/replace-photos.mjs b/scripts/replace-photos.mjs index 75039e7..5ce73d2 100644 --- a/scripts/replace-photos.mjs +++ b/scripts/replace-photos.mjs @@ -84,8 +84,14 @@ if (GO && !process.exitCode && replacedIds.length) { if (NO_WARM) { console.log(`In a minute, once the shop shows the new photos, run: ${warmCmd}`); } else { - const tally = await warmPhotos(stage, { waitForIds: replacedIds, waitForUrls: uploadedUrls }); - if (tally.failed.length) { + try { + const tally = await warmPhotos(stage, { waitForIds: replacedIds, waitForUrls: uploadedUrls }); + if (tally.failed.length || tally.timedOut) { + console.log(`Some photos failed to warm; re-run: ${warmCmd}`); + process.exitCode = 1; + } + } catch (err) { + console.error(err?.message ?? err); console.log(`Some photos failed to warm; re-run: ${warmCmd}`); process.exitCode = 1; } diff --git a/scripts/warm-photos.mjs b/scripts/warm-photos.mjs index 5e786b3..f041225 100644 --- a/scripts/warm-photos.mjs +++ b/scripts/warm-photos.mjs @@ -37,7 +37,7 @@ export async function warmPhotos( waitForIds = [], waitForUrls = [], pollMs = 5_000, - maxWaitMs = 45_000, + maxWaitMs = 60_000, retryNotFoundMs = 65_000, retryBusyBaseMs = 1000, fetchImpl = fetch, @@ -59,6 +59,7 @@ export async function warmPhotos( const needWait = waitForIds.length > 0 || waitForUrls.length > 0; const deadline = Date.now() + maxWaitMs; let waited = false; + let timedOut = false; for (;;) { try { items = await readCatalog(); @@ -68,6 +69,7 @@ export async function warmPhotos( } if (Date.now() >= deadline) { console.warn("Catalog did not show all newly uploaded items/photos yet; warming current catalog."); + timedOut = true; break; } if (!waited) { @@ -84,11 +86,20 @@ export async function warmPhotos( ); console.log(`Warming ${urls.length} photo copies on ${stage.siteUrl}, ${AT_ONCE} at a time`); - const tally = { hit: 0, made: 0, failed: [] }; + const tally = { hit: 0, made: 0, failed: [], timedOut }; async function warm(url) { for (let attempt = 1; attempt <= 5; attempt++) { - const r = await fetchImpl(url); - await r.arrayBuffer(); + let r; + try { + r = await fetchImpl(url); + await r.arrayBuffer(); + } catch (err) { + if (attempt < 5) { + await sleep(retryBusyBaseMs * 2 ** attempt); + continue; + } + return tally.failed.push(`${err?.message ?? err} ${url}`); + } if (r.ok) return tally[/hit/i.test(r.headers.get("x-cache") ?? "") ? "hit" : "made"]++; // 429/5xx: the resizer is busy. 404: the resizer hasn't seen the new catalog yet, and CloudFront // keeps that answer for a minute. @@ -111,5 +122,5 @@ export async function warmPhotos( if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { const stage = currentStage(); const tally = await warmPhotos(stage); - if (tally.failed.length) process.exitCode = 1; + if (tally.failed.length || tally.timedOut) process.exitCode = 1; } diff --git a/site/js/test/api.test.mjs b/site/js/test/api.test.mjs index 48f8df0..4a86b66 100644 --- a/site/js/test/api.test.mjs +++ b/site/js/test/api.test.mjs @@ -9,7 +9,11 @@ test("sha256Hex matches the standard test vectors", async () => { assert.equal(await sha256Hex("abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); }); -test("POSTs carry the body's hash, which CloudFront-signed Lambda URLs require", async () => { +test("POSTs carry the body's hash, which CloudFront-signed Lambda URLs require", async (t) => { + const originalFetch = globalThis.fetch; + t.after(() => { + globalThis.fetch = originalFetch; + }); let seen; globalThis.fetch = async (url, init) => { seen = { url, init }; @@ -21,7 +25,12 @@ test("POSTs carry the body's hash, which CloudFront-signed Lambda URLs require", assert.equal(seen.init.headers["x-amz-content-sha256"], await sha256Hex(seen.init.body)); }); -test("getJson retries transient 429 and 5xx answers and returns the first success", async () => { +test("getJson retries transient 429, 5xx, and network errors, and skips retry on 404", async (t) => { + const originalFetch = globalThis.fetch; + t.after(() => { + globalThis.fetch = originalFetch; + }); + const statuses = [429, 503, 200]; let calls = 0; globalThis.fetch = async () => new Response("{}", { status: statuses[calls++] }); @@ -37,4 +46,23 @@ test("getJson retries transient 429 and 5xx answers and returns the first succes const fail = await getJson("/api/catalog", { retries: 2, baseMs: 1 }); assert.equal(fail.status, 502); assert.equal(exhausted, 3); + + let netCalls = 0; + globalThis.fetch = async () => { + netCalls++; + if (netCalls < 3) throw new Error("socket hang up"); + return new Response("{}", { status: 200 }); + }; + const recovered = await getJson("/api/catalog", { retries: 2, baseMs: 1 }); + assert.equal(recovered.status, 200); + assert.equal(netCalls, 3); + + let notFoundCalls = 0; + globalThis.fetch = async () => { + notFoundCalls++; + return new Response("{}", { status: 404 }); + }; + const notFound = await getJson("/api/catalog", { retries: 2, baseMs: 1 }); + assert.equal(notFound.status, 404); + assert.equal(notFoundCalls, 1); }); diff --git a/site/js/test/seo.test.mjs b/site/js/test/seo.test.mjs index 8737076..38aa7be 100644 --- a/site/js/test/seo.test.mjs +++ b/site/js/test/seo.test.mjs @@ -120,5 +120,49 @@ test("warmPhotos polls catalog until newly uploaded items/photos appear and warm ); assert.equal(reads, 2); assert.equal(warmed.length, 7); - assert.deepEqual(tally, { hit: 1, made: 6, failed: [] }); + assert.deepEqual(tally, { hit: 1, made: 6, failed: [], timedOut: false }); +}); + +test("warmPhotos retries network errors without aborting other variants", async () => { + let brokenAttempts = 0; + const tally = await warmPhotos( + { siteUrl: "https://example.test" }, + { + pollMs: 1, + maxWaitMs: 50, + retryBusyBaseMs: 1, + fetchImpl: async (url) => { + if (url === "https://example.test/api/catalog") { + return Response.json({ items: [{ id: "I1", images: ["https://cdn.example/p1.jpeg"] }] }); + } + if (url.includes("f=jpeg")) { + brokenAttempts++; + throw new Error("socket reset"); + } + return new Response("ok", { status: 200 }); + }, + }, + ); + assert.equal(brokenAttempts, 5); + assert.equal(tally.made, 6); + assert.equal(tally.failed.length, 1); + assert.match(tally.failed[0], /^socket reset .*f=jpeg$/); + assert.equal(tally.timedOut, false); +}); + +test("warmPhotos sets timedOut when catalog propagation misses the deadline", async () => { + const tally = await warmPhotos( + { siteUrl: "https://example.test" }, + { + waitForIds: ["ITEM_MISSING"], + pollMs: 1, + maxWaitMs: 5, + retryBusyBaseMs: 1, + fetchImpl: async (url) => { + if (url === "https://example.test/api/catalog") return Response.json({ items: [] }); + throw new Error(`unexpected fetch ${url}`); + }, + }, + ); + assert.deepEqual(tally, { hit: 0, made: 0, failed: [], timedOut: true }); });