Skip to content

Refresh public pages when coordinators save content (W6-10) - #153

Merged
calebyhan merged 1 commit into
mainfrom
144/revalidate-public-pages
Nov 16, 2026
Merged

calebyhan merged 1 commit into
mainfrom
144/revalidate-public-pages

Conversation

@maxwellhu9

Copy link
Copy Markdown
Contributor

Public pages are cached for hours (cacheLife("hours") in frontend/src/lib/public-data.ts), so a coordinator's edit wouldn't show up until the cache expires. After each admin save, the backend now tells Next.js which cache tags to drop (TDD 4.6.8).

Changes:

  • POST /api/revalidate (frontend/src/app/api/revalidate/route.ts):

    • Checks the x-revalidate-secret header against REVALIDATE_SECRET in constant time. Both values are SHA-256 hashed first, so timingSafeEqual always compares equal lengths and never throws.
    • Returns 401 for a missing or wrong secret, or when the env var is unset or empty. The secret is checked before the body, so callers without it can't probe the tag list.
    • Returns 400 for bad JSON, a missing or empty tags list, or any tag not on the allow-list.
    • Otherwise calls revalidateTag(tag, { expire: 0 }) for each tag and returns 204.
  • frontend/src/lib/cache-tags.ts holds the 7 allowed tags. getPublicData now takes a CacheTag, so the allow-list can't drift from the tags pages actually use.

  • backend/app/services/revalidate.py:

    • request_revalidation(tags) sends the POST with a 3s timeout. It never raises. On failure it logs only the tags and the status code (or the error type for network errors), never the secret.
    • schedule_revalidation(background, *tags) is the one helper routes call. It adds the request as a FastAPI BackgroundTask, so it runs after the response is sent, which is after the commit. A failed or slow call can't fail or slow the save.
    • It does nothing when REVALIDATE_SECRET is unset or an empty string, matching the frontend.
  • backend/app/config.py adds revalidate_url (dev default http://localhost:3000/api/revalidate) and revalidate_secret (default None).

  • Every admin write schedules its tags right after db.commit():

    Writes Tags
    Hours: weekly PUT, exception create/update/delete hours
    Settings PUT settings
    Content block PUT content
    FAQs create/update/delete faqs
    Fit guide create/update/delete fit-guide
    Resources create/update/delete resources, fit-guide
    Resource tags create/update/delete resources
    Statistics create/update/delete statistics
    Report options, accounts none (not public)
    • Why resource writes also refresh fit-guide: the public /api/fit-guide includes each linked resource's name, URL and phone, and hides unpublished resources. Deleting a resource also clears the link (ON DELETE SET NULL). Refreshing only resources would leave stale or broken resource links on the FAQ page.
    • Resource tags refresh resources because the resources page fetches /api/resource-tags under that tag.
    • Settings send settings on every save, even for non-public keys. It's simpler, the extra refresh costs almost nothing, and it can't miss a public page that reads a setting indirectly.
  • Reorder: the Collection dataclass gets a revalidate field:

    • faqs → faqs, statistics → statistics, fit-guide → fit-guide, resource-tags → resources
    • resources → resources only, since the fit guide has its own order
    • report-options → none
  • Tests:

    • Backend, tests/test_revalidate.py:
      • A table of every admin write (including all 6 reorder collections) and the exact tags it must schedule. Report options must schedule nothing, and a failed write (404) schedules nothing.
      • Guard test: reads every non-GET /api/admin route from the OpenAPI schema and fails unless each one is in the table or in an explicit not-public set (accounts). A future admin write can't skip revalidation without someone deciding its tags. I checked that the table catches mistakes by dropping fit-guide from the resource update: the test failed.
      • The sender sends the right URL, method, header, JSON and timeout. It does nothing with an unset or empty secret.
      • A 500, a 401, a timeout and a connection error each log exactly tags=[...] status=N or error=Type, never the secret, and don't raise.
      • With the HTTP call failing, POST /api/admin/faqs still returns 201 and the row is committed.
      • conftest.py swaps the sender for a recorder in every test. The dev container now sets REVALIDATE_SECRET, so tests would otherwise send real HTTP calls.
    • Frontend, route.test.ts: a missing secret, a wrong secret (same length and different length) and an unset or empty env var all give 401. An unknown tag, an empty list, a bad shape or bad JSON give 400. A valid call gives 204 and calls revalidateTag(tag, { expire: 0 }) once per tag.
  • Env (Replace copied env files with code defaults and devcontainer env #38 convention):

    • REVALIDATE_SECRET gets a dev-only value in .devcontainer/docker-compose.yml. The backend and Next.js run in the same container, so one entry covers both.
    • Both .env.example files list it, and the backend one also lists REVALIDATE_URL.

Decisions:

  1. revalidateTag(tag, { expire: 0 }), not "max". In Next 16, calling revalidateTag with one argument is deprecated. "max" serves stale content while it revalidates, so the first visit after an edit would still show the old page, which is the problem this issue fixes. The bundled Next docs recommend { expire: 0 } for webhook callers, which can't use updateTag.
  2. Standard-library urllib, not httpx2. httpx2 is only a dev dependency, and this is one small POST. Starlette runs sync background tasks in a thread pool, so the blocking call doesn't block the event loop.
  3. No CI env change. The Replace copied env files with code defaults and devcontainer env #38 rule for CI env covers settings the app can't start without. REVALIDATE_SECRET is optional on both sides (unset means off on the backend and 401 on the frontend), and the tests set their own values.

Proof /api/revalidate is served by Next.js, not rewritten to the backend: I ran make dev-frontend with only the dev secret set and no backend running:

no secret                    -> 401
wrong secret                 -> 401
unknown tag                  -> 400
valid (all 7 tags)           -> 204
control: GET /api/health     -> 500   (rewritten: ECONNREFUSED 127.0.0.1:8000)

If the /api/:path* rewrite had caught /api/revalidate, all four calls would have failed like the control. Next serves its own routes before applying rewrites, so next.config.ts needed no change. Next's log showed POST /api/revalidate 204.

I also called the backend's real request_revalidation(["faqs", "fit-guide"]) against that server: it got a 204. With a wrong secret, the backend logged only Revalidation failed: tags=['faqs'] status=401. I didn't run a full admin save from the portal, because my local dev database has no coordinator account.

make check passes (lint, mypy, tsc, 679 backend and 279 frontend tests, build).

Note for reviewers: rebuild the dev container (Dev Containers: Rebuild Container) to pick up REVALIDATE_SECRET. Until then it's unset, so the backend skips revalidation and the route returns 401, and edits only appear after the cache expires. For production, set the same REVALIDATE_SECRET on both App Platform components (TDD 4.11), and set REVALIDATE_URL on the backend to the public site's /api/revalidate.

Closes #144

Add POST /api/revalidate in Next.js, which checks a shared secret in
constant time, allows only the 7 public cache tags, and expires each tag
with revalidateTag(tag, { expire: 0 }).

Every admin write now schedules request_revalidation as a BackgroundTask
after its commit. It uses stdlib urllib with a 3s timeout, logs only the
tags and the status on failure, and does nothing when REVALIDATE_SECRET
is unset or empty. Resource writes also refresh fit-guide, since the
public fit guide shows each linked resource. Reorder maps each collection
to its tag, and report options get none.

A guard test fails when a new admin write isn't in the tag table.
@maxwellhu9 maxwellhu9 self-assigned this Nov 16, 2026
@maxwellhu9
maxwellhu9 requested a review from calebyhan November 16, 2026 18:18
@github-actions

Copy link
Copy Markdown

Backend Test Results

679 tests  +40   679 ✅ +40   20s ⏱️ +2s
  1 suites ± 0     0 💤 ± 0 
  1 files   ± 0     0 ❌ ± 0 

Results for commit 631af4b. ± Comparison against base commit 4cc4d65.

@calebyhan calebyhan left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@calebyhan
calebyhan merged commit cf5ab27 into main Nov 16, 2026
4 checks passed
@calebyhan
calebyhan deleted the 144/revalidate-public-pages branch November 16, 2026 19:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Refresh public pages when coordinators save content (W6-10)

2 participants