Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions backend/src/notify-sale.mjs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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) => {
Expand All @@ -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}`);
Expand Down
2 changes: 1 addition & 1 deletion backend/test/checkout-flow.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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/",
Expand Down
29 changes: 28 additions & 1 deletion deploy/site.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -334,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
Expand All @@ -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/*
Expand Down
2 changes: 1 addition & 1 deletion deploy/stages.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"squareLocationId": "CQ5ZYKRG4KNAQ",
"squareTokenParam": "/updraft/prod/square-access-token",
"newsletterGroupId": "7P07F7ZHJ3BJHT0PV01WJBSV24",
"apiConcurrency": 5,
"apiConcurrency": 15,
"imagesConcurrency": 5,
"alertEmail": "aaronfilson@gmail.com"
},
Expand Down
42 changes: 30 additions & 12 deletions scripts/load-items.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 <folder> overrides the batch file's photoDir.
// Options: --photos <folder> 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";
Expand All @@ -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 <batch.json> [--stage staging] [--photos <folder>] [--go]");
if (!file) throw new Error("Usage: node scripts/load-items.mjs <batch.json> [--stage staging] [--photos <folder>] [--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;
Expand Down Expand Up @@ -52,6 +54,8 @@ 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 = [];
const createdUrls = [];

try {
const existing = new Set();
Expand All @@ -77,7 +81,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)`);
Expand Down Expand Up @@ -127,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,
Expand All @@ -136,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(),
Expand All @@ -155,16 +159,30 @@ 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;
}
// 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 {
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"})`}`);
}
}
31 changes: 27 additions & 4 deletions scripts/replace-photos.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 <folder> overrides the batch file's photoDir; --only "<name>" does one piece.
// Options: --photos <folder> overrides the batch file's photoDir; --only "<name>" 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 <batch.json> [--stage staging] [--photos <folder>] [--only <name>] [--go]");
throw new Error(
"Usage: node scripts/replace-photos.mjs <batch.json> [--stage staging] [--photos <folder>] [--only <name>] [--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;
Expand All @@ -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();
Expand Down Expand Up @@ -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`);
Expand All @@ -71,6 +79,21 @@ 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 {
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;
}
}
}
Loading
Loading