Repository navigation
refactor(server): one helper for the custom-endpoint SahajCloud reads - #129
Conversation
… helper Five reads of custom CMS root endpoints each hand-rolled the same preamble: `getCmsContext()`, a `fetch` carrying the API key, a `[PayloadCMS] GET … → <status>` line, and a throw on a non-OK response. The copies had drifted three ways, and each drift was a diagnostic lost in production. `server/cms-fetch.ts` now owns the preamble. `cmsFetch` takes a path, not a URL: handed a URL, every site would still call `getCmsContext()` to build one, and nothing would be removed. `fetchWithErrorDetails` moves here from `payload-client.ts`, so the SDK path and the custom-endpoint path share one log-and-dump. It cannot live in `payload-client.ts`: `cms-client.test.ts` and `atlas-client.test.ts` replace that module wholesale, so anything exported from it is `undefined` under test, and `content-index.ts` pulls in no SDK. The three drifts this closes: - `fetchContentIndexDocs` emitted no request log at all, so one CMS read was invisible in the dev log the debugging workflow is written around. - No custom-endpoint read dumped the CMS error body, so a 400 said `→ 400` and never which field the CMS refused. The SDK path already did this. - All four throwing sites threw a plain `Error`. `detectErrorType` reads `.status` structurally and otherwise falls back to matching `50[0-9]` in the message, so a Cloudflare-origin 520, 522 or 524 classified as UNKNOWN and `withRetry` refused it — exactly the shape a Railway restart behind the edge produces. `CmsResponseError` carries the status. Each call site keeps its own 404 policy, its own empty-result shape, its own Sentry warnings, and its own retry wrapper. Those genuinely differ, and `withRetryUnlessPreview` is private to `cms-client.ts` on purpose. The test fakes gain a `clone()`, which `fetchWithErrorDetails` calls on a non-OK response. A production `Response` always has one, so teaching the helper to skip the dump without it would only hide the test gap. Closes #127 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01CjcCtxLsKBwh8guS8X4x4H
`server/AGENTS.md` described the custom root endpoints as plain `fetch` calls, which each shaped their own preamble. It now names `cmsFetch` and adds the rule the third drift cost: throw a `CmsResponseError`, so a Cloudflare-origin 5xx keeps the retry `detectErrorType` would otherwise refuse it. The retry rule that section already carried is now true of every read but one, so it names #128 rather than reading as satisfied. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01CjcCtxLsKBwh8guS8X4x4H
Review of the first commit landed four changes, each removing a way the next custom-endpoint read could reintroduce #127. `throwIfNotOk(response, label)` replaces four hand-built `CmsResponseError`s. The rule "the status must ride on the error" was stated in `server/AGENTS.md` prose and enforced nowhere, which is the shape of rule that decays. It is now the only construction path. `cmsFetch` drops the `init` parameter and the exported `CmsFetchInit`. No call site passed one, every custom root endpoint is a GET, and the type's own doc line ("Authorization is not a caller's to set") was untrue: the caller's headers spread last and would have won. `cmsAuthHeaders` is shared with `payload-client.ts`, so the CMS auth scheme is composed in exactly one place. A second header, or a change of scheme, can no longer reach the SDK path and miss the custom-endpoint path. `cmsFetch` refuses a path that is not site-relative. The URL is built by concatenation, so `baseURL` fixes the authority — except for a path starting `@`, which turns the host into userinfo and would send the API key to whatever follows. `content-index.ts` passes an endpoint the CMS computed, so the one chokepoint checks rather than trusts. The same string was built the same way before this branch; the chokepoint is what makes a guard cheap. Also: a 404 no longer dumps a response body at error level. It is a documented answer at four of the five reads — an unknown id, a stale inbound link, no songs route — and it carries none of the field-level detail the dump exists for, so the first commit put a body read and a `console.error` on a hot path. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01CjcCtxLsKBwh8guS8X4x4H
The custom-endpoint section stated the status rule as a convention to follow. It now names the helper that enforces it, records that a 404 returns rather than throws, and states the path contract `cmsFetch` refuses to break. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01CjcCtxLsKBwh8guS8X4x4H
Deploying wemeditate-design with
|
| Latest commit: |
f88a55a
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://00008e19.wm-design.pages.dev |
| Branch Preview URL: | https://claude-refactor-127-cms-fetc.wm-design.pages.dev |
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The diff matches the ticket. Five hand-rolled preambles become one helper, each call site keeps its own 404 policy and retry wrapper, and both acceptance greps come back clean. cmsFetch fetches and does not retry, so it avoids the readCms naming trap from #107.
One change reaches past the ticket. The 404 exemption sits in the wrapper the SDK also uses, so every collection read loses its 404 error body too — the path the ticket named as the standard to match.
Findings
- should-fix — the 404 dump exemption also narrows the SDK path.
server/cms-fetch.ts:83 - consider — a five-line threat model above a three-line guard.
server/cms-fetch.ts:120
What was checked
Ticket #127 against the diff, then the five touched modules and four test files, read whole. In SahajCloud, computeApiEndpoint builds every endpoint from a fixed basePath map, and /api/atlas/seo returns two distinct 404 messages (src/endpoints/atlas/seo/index.ts:422,433). #126 is still open on an older base, so five sites is right.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
`fetchWithErrorDetails` is also the SDK's `fetch` (payload-client.ts:105), so exempting a 404 there silenced every collection read's error body too — wider than the custom-endpoint reads the change was argued from, and untested. The exemption moves to the one caller that wants it. `cmsFetch` passes its own quiet status; the wrapper dumps everything by default, as it did on main. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Ws14AjKse4AnichnWMfrYs
Five lines of threat model sat above a three-line guard. The reachability argument belongs in the PR body, which already carries it; the line a reader needs at the guard is why concatenation makes the prefix dangerous. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Ws14AjKse4AnichnWMfrYs
Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Ws14AjKse4AnichnWMfrYs
|
Both review findings adopted, pushed as
Nothing rebutted, nothing to ask. Lean gate green: lint, 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Deploying with
|
| Status | Name | Latest Commit | Preview URL | Updated (UTC) |
|---|---|---|---|---|
| ✅ Deployment successful! View logs |
wemeditate-web | f88a55a | Commit Preview URL Branch Preview URL |
Sep 21 2026, 11:48 PM |
Ardnived
left a comment
There was a problem hiding this comment.
Instead of having throwIfNotOk wouldn't it be simpler to just make cmsFetch throw directly whenever it's no ok, and then catch the error where appropriate?
However, maybe this PR needs to go a step further, why are we implementing our own fetch for CMS data? Shouldn't we be using a PayloadCMS client library which returns type safe data? Aren't we already taking that approach in SahajAtlasWeb?
|
No code change. A throwing The SDK. We already use it — every collection read goes through 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
@sydevs-bot Could we simplify things by standardizing the behaviour and handling across the call sites? We are willing to consider behaviour changes if they make sense |
Ardnived asked for one behaviour across the call sites, and accepted a behaviour change to get it. `cmsFetch` now throws a `CmsResponseError` on every non-OK response and returns the parsed body, so `throwIfNotOk`, the `if (response.status === 404)` branch, and the `await response.json()` cast leave all five sites. No call site branches on a status any more. `cmsFetchOptional` is the same read where a 404 is an answer — an unknown id, a stale inbound link, no songs route. It resolves to `null`, which is what keeps that case off the retry ladder and out of Sentry: thrown, a 404 classifies CLIENT, so `withRetry` refuses it and reports it as a permanent failure. Four reads take that form. `fetchContentIndexDocs` takes the throwing form, which is the behaviour change. Its endpoint is one the CMS computed for the block, so nothing answering it is a data gap, not an answer: its 404 now dumps a body and warns. Its two Sentry branches collapse into the one catch, which carries the status off the error. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Bpp2dX8KyUhoKWVDPouHdy
Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Bpp2dX8KyUhoKWVDPouHdy
|
Adopted, pushed as No call site branches on a status now.
The behaviour change you allowed: Lean gate green: lint, The SDK question stays open as its own ticket — see the PR body. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Ardnived
left a comment
There was a problem hiding this comment.
Let's change the naming convention. Instead of using the term "CMS", switch to SahajCloud across the code base
Ardnived asked for `SahajCloud` in place of `CMS` across the code base. This commit renames only what this PR introduces, so the convention change does not bury an eleven-file refactor under a sweep of 653 occurrences in 165 files. That sweep is #130. `cms-fetch.ts` becomes `sahajcloud-fetch.ts`, and `cmsFetch`, `cmsFetchOptional`, `CmsResponseError` and `cmsAuthHeaders` take the `sahajCloud` spelling. The env vars already read `SAHAJCLOUD_API_KEY` and `PUBLIC__SAHAJCLOUD_URL`, so the file name now matches them. `getCmsContext`, the `cms-client.ts` and `cms-types.ts` file names, and the `[PayloadCMS]` log prefix are untouched. The first two predate this branch; the third names the product, and the debugging workflow in AGENTS.md greps for it. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_019M9HvUHQQNoQU2L5XQQGjR
The convention now has a written home, so the next new file does not inherit the `cms-` prefix by matching a neighbour. It names the two exceptions that survive the rename — `PayloadCMS` and `@payloadcms/sdk` name the product, and the `[PayloadCMS]` log prefix is what the debugging workflow greps for — and points at #130 for the 165 files still spelled the old way. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_019M9HvUHQQNoQU2L5XQQGjR
|
Adopted in part, pushed as Renamed what this PR introduces: The rest is #130. 653 occurrences across 165 files: seven more filenames, Three decisions are yours either way, and #130 lists them. Whether
Lean gate green: lint, ⚠ This branch conflicts with 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
#126 added a second custom root endpoint, `GET /api/atlas/sitemap`, to the file this branch was converting to the shared read path. - `server/atlas-client.ts` — `getAtlasSeo` keeps this branch's `sahajCloudFetchOptional` read. #126 changed only the shape of the error it throws, and `SahajCloudResponseError` already carries `status`, so the 52x retry both sides wanted survives. `getAtlasSitemapUrls` stays on its own `fetch`, unconverted, as the PR body says. It still calls `getCmsContext()`, so that import comes back — the import block auto-merged to this branch's and dropped it. - `server/atlas-client.test.ts` — both sides grew a capture for the error the retry ladder was handed. Kept `thrownSpy`, and pointed the 522 spec at it. Dropped `find.mockReset()`: `find` mocked the SDK read #126 replaced, and nothing declares it any more. Deduped an import both sides added. - `server/AGENTS.md` — the shared-helper paragraph now names the sitemap endpoint as the one read still assembling its own `fetch`. #126's ownership warning kept verbatim. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01CKDSUZUoYyX87AFr7wFDiX
|
Merged Three files conflicted, and two hid a break that compiles away from the conflict markers:
🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Summary
server/sahajcloud-fetch.ts) instead of five hand-rolled copies that had drifted three ways.sahajCloudFetchthrows on every non-OK response and returns the parsed body;sahajCloudFetchOptionalis the same read where a 404 is an answer and resolves tonull.SahajCloud, notCMS, per #129 (review). The 165 files still spelled the old way are refactor: use SahajCloud, not CMS, as the backend's name in code #130.UNKNOWNbefore, sowithRetryrefused exactly the shape a Railway restart behind the edge produces.Changes
server/sahajcloud-fetch.ts— new.sahajCloudFetch<T>(path, label)throws aSahajCloudResponseErroron any non-OK response and returns the parsed body.sahajCloudFetchOptional<T>(path, label)is the same read withnullfor a 404.sahajCloudAuthHeaders(apiKey)andfetchWithErrorDetailsmoved here frompayload-client.ts; the wrapper takes an optionalquietStatuses, and onlysahajCloudFetchOptionalasks for one.server/atlas-client.ts,server/cms-client.ts(×3),server/content-index.ts— each read loses itsgetCmsContext(), its URL assembly, its header, its log line, itsif (response.status === 404)branch, itsthrowIfNotOkcall and itsawait response.json()cast. Each keeps its own retry wrapper, degrade value, and Sentry warnings.server/payload-client.ts— imports the shared fetch wrapper and the shared auth header, so the SDK path and the custom-endpoint path cannot drift apart. Its behaviour is unchanged frommain: every non-OK response, 404 included, still dumps its body.AGENTS.md— the naming convention now has a written home, with its two exceptions and the refactor: use SahajCloud, not CMS, as the backend's name in code #130 breadcrumb.server/AGENTS.md,docs/rules/rest-api.md— the custom-endpoint section named plainfetchcalls, thenthrowIfNotOk.Preview
The Ladle preview is live at the branch alias. The web Worker preview follows CI.
Test results
c8496d8: ✓ lint +tsc --noEmit+test:run(742 passed, up from 733 onmain)server/— 177 passedpnpm build, last run on7bd4cbe. The rename since then adds no import the build had not already resolved.Manual verification
pnpm dev, load a page carrying a content-index block and a meditation with songs, and confirm one[PayloadCMS] GET … → 200line per custom-endpoint read. Not done here — this environment has no.env.local, so no key reaches SahajCloud./mapand confirm thegetAtlasSeoread still returns server-rendered content. The atlas endpoints 403 locally (server/AGENTS.md), so this is the only place to check them./songs) logs its request line and no[PayloadCMS] Error responseblock.Notes for reviewer
mainsince fix(server): lift the 2,000-doc ceiling on the atlas sitemap read #126 landed, so GitHub schedules zero CI runs for it. The conflict is theatlas-client.tsimport block, as predicted. Resolving it is its own pass.sahajCloudFetch,sahajCloudFetchOptional,SahajCloudResponseError,sahajCloudAuthHeaders. The rest is 653 occurrences across 165 files — 7 more filenames,getCmsContext,cmsHref,cmsOrigin,discoverFromCms, and 355 bareCMSin prose — filed as refactor: use SahajCloud, not CMS, as the backend's name in code #130 rather than folded in here, because a 165-file rename would bury an 11-file refactor and conflict with every open branch. Say the word and I will do the sweep on this branch instead. Three decisions need you either way, and refactor: use SahajCloud, not CMS, as the backend's name in code #130 lists them: whetherpnpm types:cmsis renamed, whatcmsHref/cmsOriginbecome, and that.claude/settings.jsonand.claude/workflow.jsonare protected paths an unattended run cannot write.CMS:PayloadCMSand@payloadcms/sdkname the product, and the[PayloadCMS] <method> <url> → <status>log prefix is what the debugging workflow inAGENTS.mdandtests/smoke/grep for.fetchContentIndexDocstakes the throwingsahajCloudFetch, so a 404 there now dumps its body and warns, where it was previously quiet. Its endpoint is one SahajCloud computed for the block, so nothing answering it is a data gap rather than an answer. Its two Sentry branches collapse into one catch, which carries the status off the error — one message where there were two, distinguished byextra.status.CLIENT(error-utils.ts:82), sowithRetryrefuses it, logsRequest failed permanently, and callsSentry.captureExceptionatlevel: 'error'. Four of the five reads answer a 404 with a value —nullforgetAtlasSeo,[]for songs and the two related feeds — so throwing there would page us on every stale inbound link.sahajCloudFetchOptionalresolves that case before it can become an error, which is what keeps it off the ladder without a nested try/catch at each site.getAtlasSitemapUrlsinto a sixth custom-endpoint copy. That copy stays unconverted; converting it belongs with refactor: use SahajCloud, not CMS, as the backend's name in code #130 or its own pass.cmsFetch(path, init?). No call site passes aninit, every custom root endpoint is a GET, and the merge order let a caller overrideAuthorization— so the parameter is gone. Re-add it when a POST needs one, with the auth header spread last.fetchContentIndexDocsis still the one SahajCloud read with no retry wrapper.SahajCloud .../Meditations/endpoints/songs.ts:58), whichfindcannot express; every collection read already goes through@payloadcms/sdk. SahajCloud publishes an OpenAPI spec covering the custom endpoints (src/plugins/openapi/customEndpoints.ts), so a generated client is the real route to type safety — its own ticket. SahajAtlasWeb is outside this session's repo scope, so whether it already generates one is unconfirmed.SahajCloudResponseErrortheresponse: { status }shapePayloadConfigErroruses. Kept as a barestatus— that is whatPayloadSDKErrorcarries (server/payload-client.test.ts:57).fetchResponsestub and thewithRetrymock shared bycms-client.test.tsandatlas-client.test.ts. The duplication predates this branch; extracting a shared test module is its own change.Detail
Why a new module rather than
payload-client.ts.cms-client.test.ts:14andatlas-client.test.ts:12replace./payload-clientwith a factory exporting onlycreatePayloadClient, so anything exported from there isundefinedin both suites. The ticket also citedcontent-index.tspulling in no SDK; that reason does not hold — it already importsaudienceIdListfromcms-client.ts, which imports the SDK — so the module header states only the test-mocking reason.Why a path and not a URL. Every site built
${baseURL}/api/…itself, so asahajCloudFetch(url)would have leftgetCmsContext()at all five and removed nothing.A security review found nothing exploitable, and one thing worth closing anyway. The URL is built by concatenation, so
baseURLfixes the authority — except that a path starting@turns the host into userinfo, andhttps://cms/+@evil.example/xresolves toevil.example, with the API key attached.content-index.tspasses an endpoint SahajCloud computes (ContentIndexBlock.tsbuilds it from a fixed four-entry path map, so it is not reachable today, andmainbuilt the identical string). Both readers refuse a path that is not site-relative: the consolidation is what makes that a one-place guard.Which 404s are quiet, and why only those. A 404 is a documented answer at four of the five reads — an unknown id, a stale inbound link, no songs route — and carries none of the field-level detail the dump exists for. Only
sahajCloudFetchOptionalpasses[404]as a quiet status, so the exemption now covers exactly the callers that treat one as an answer. It first sat infetchWithErrorDetails, which is also the SDK'sfetch, so it silenced every collection read's 404 body too — wider than the reads it was argued from. A spec pins the wrapper's default, because a collection read has no caller-side 404 policy and its body is the only record of which read missed.The test fakes needed a
clone(), whichfetchWithErrorDetailscalls on a non-OK response. Teaching the helper to skip the dump whencloneis missing would only have hidden the test gap — a productionResponsealways has one.The rename is prose and identifiers only.
git diff 7bd4cbe..c8496d8touches no control flow: twogit mvs, the symbol names, the doc lines that name them, and one new conventions bullet. The suite count is unchanged at 742.Not addressed, pre-existing:
getCmsContext()re-runs a ZodsafeParseper read, so a page with N content-index blocks pays N+3 identical parses of two request-invariant strings. Memoizing it on the Hono context is a separate change.Closes #127
🤖 Written by the sydevs autonomous loop — see what this is
🤖 Generated with Claude Code
https://claude.ai/code/session_019M9HvUHQQNoQU2L5XQQGjR