Skip to content

refactor(data-api): tag jsonFetch outcomes instead of collapsing to null - #33

Merged
neuromechanist merged 2 commits into
mainfrom
32-refactor-jsonfetch-to-distinguish-error-types-timeout-vs-404-vs-5xx-vs-parse-error
May 19, 2026
Merged

neuromechanist merged 2 commits into
mainfrom
32-refactor-jsonfetch-to-distinguish-error-types-timeout-vs-404-vs-5xx-vs-parse-error

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

Replaces the unconditional `T | null` contract of `jsonFetch` with a `FetchOutcome` discriminated union covering every failure mode: `ok`, `not_found`, `rate_limited`, `upstream_error`, `timeout`, `network_error`, `parse_error`. Every previously-throwing path (`AbortError`, JSON parse, network/DNS failures) is now caught + tagged so callers can distinguish "the resource genuinely doesn't exist" from "the data layer is degraded."

Why

Deferred from PR #30 and PR #31 review threads — silent-failure-hunter flagged the same root cause in both: `jsonFetch` callers couldn't tell whether `null` meant 404, timeout, 5xx, malformed JSON, or a network failure, and several error paths (AbortError, SyntaxError) actually propagated as unhandled exceptions to surface as 500s with no signal.

What changed

`src/lib/data-api.ts`:

  • New `FetchOutcome` type
  • Rewrote `jsonFetch` to catch every error mode and return tagged outcomes (no more unhandled exceptions)
  • Added `jsonFetchOrNull` compat wrapper that logs every non-ok outcome except `not_found` (which is a routine "resource doesn't exist" — not worth log noise)
  • Existing `getLanding` / `getMetadata` / `getSummary` / `getManifest` preserved (delegate to `jsonFetchOrNull`)
  • New `getLandingOutcome` / `getMetadataOutcome` / `getSummaryOutcome` / `getManifestOutcome` for callers that need to disambiguate
  • New `outcomeValue(o)` type-narrowing helper
  • Fixed `archiveZipUrl` comment drift (the old comment referenced a `download//.zip` path that doesn't match the code)

Behavioral changes (user-visible):

  • `/dataset/` SSR: real 404 only when both landing and metadata are `not_found`. Degraded responses (timeout, 5xx, parse error) now return 503 instead of silently 404ing, so monitoring distinguishes typo'd URLs from data-layer outages.
  • `/api/dataset//{readme,tree}`: explicit 404 when landing is `not_found`, short-circuiting the manifest fall-through that would otherwise render a misleading "no manifest" state for missing datasets.

Test plan

  • `vitest run` — 136/136 pass (2 new tests for `outcomeValue` discriminant)
  • `astro check` — 0 errors, 0 warnings, 0 hints
  • `biome check` on changed files — clean
  • `astro build` — succeeds
  • Post-deploy: hit `/dataset/notarealdataset` → should return 404 (currently does, but for the wrong reason)
  • Post-deploy: simulate data.nemar.org being slow → SSR page returns 503 (was 404 before this change)
  • Post-deploy: hit `/api/dataset/notarealdataset/readme?v=v1.0.0` → 404 with body "Dataset not found"

Notes

Replaces the unconditional T|null contract of jsonFetch with a
FetchOutcome<T> discriminated union covering: ok, not_found,
rate_limited, upstream_error, timeout, network_error, parse_error.
Every previously-throwing path (AbortError, JSON parse, network/DNS
failures) is now caught + tagged so callers can distinguish "the
resource genuinely doesn't exist" from "the data layer is degraded."

Legacy T|null API preserved via jsonFetchOrNull (used by the four
existing getX helpers); new *Outcome variants are introduced for
callers that need the discriminant.

Behavioral changes (user-visible):
- /dataset/<id> SSR: real 404 only when BOTH landing and metadata are
  not_found. Degraded responses (timeout, 5xx, parse error) now return
  503 instead of silently 404ing, so monitoring distinguishes typo'd
  URLs from data-layer outages.
- /api/dataset/<id>/{readme,tree}: explicit 404 when landing is
  not_found, short-circuiting the manifest fall-through that would
  otherwise render a misleading "no manifest" state for missing
  datasets.

Also sweeps the archiveZipUrl comment drift flagged on PR #31 — the
old comment referenced a `download/<id>/<v>.zip` path that doesn't
exist in the code.

Closes #32.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented May 19, 2026 •

Copy link
Copy Markdown

Critical:
- Cache-Control on the Response object, not Astro.response. Astro returns
  the inner Response verbatim, so headers set on Astro.response never
  reached the edge and Cloudflare was free to cache the transient 404s
  and 503s. (silent-failure 2)

Important:
- metadata not_found is no longer a 503. metadata.json is OPTIONAL on
  the data side — a fresh dataset can have landing without metadata yet.
  Only landing not_found (alone) is a partial-publish degradation. New
  pure helper resolveDatasetPageStatus encapsulates the 9-cell decision
  table; tests cover every combination. (code-reviewer 1, test-analyzer 1)
- 429 retry now bails on parent abort during the Retry-After sleep so
  caller cancellation doesn't burn the full delay. Parent-aborts also
  map to network_error("request cancelled by caller") instead of
  masquerading as timeout in logs. (code-reviewer 2, silent-failure 1)
- Safety-net 500 path now console.errors + sets Cache-Control: no-store
  before returning. (silent-failure 3)
- resolveCanonical logs non-404 errors instead of silently swallowing
  them. (silent-failure 4)
- outcomeValue exhaustiveness test now uses `satisfies Exclude<
  FetchOutcome<unknown>, {kind:"ok"}>[]` so adding a new outcome kind
  forces an explicit test case. (test-analyzer 3)

Comments:
- Dropped redundant JSDocs on outcomeValue + the first sentence of
  jsonFetch (both restated the type signature). (comment-analyzer 1, 2)
- "Legacy" removed from the section divider comment — both T|null and
  *Outcome variants are first-class now, not deprecated. (comment 4)
- SSR-page comment explains the 404-asymmetry WHY (only confirmed when
  both signals agree). (comment 3)
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review findings addressed (commit 302cdd6)

Critical:

  • Cache-Control now on the Response, not Astro.response. The previous code set the header on Astro.response.headers then returned a separate new Response(null, {...}) — Astro returns the inner object verbatim, so the header never reached the edge. Cloudflare would have cached the transient 404s/503s. Fixed at all 4 return sites by attaching headers directly to the new Response() constructor. (silent-failure-hunter finding 2)

Important — correctness:

  • metadata: not_found no longer 503s. metadata.json is OPTIONAL on the data side; a fresh dataset can have landing without metadata yet. Treating it as a hard failure caused false 503 alarms for normal partial states. (code-reviewer 1)
  • Extracted resolveDatasetPageStatus(landingOut, metadataOut) as a pure helper that encodes the full 9-cell decision table. 7 new unit tests cover: both ok, both not_found = 404, landing-only not_found = degraded, metadata-only not_found = ok, every hard-failure kind on each signal, and the priority order when both fail. The SSR page now consumes this helper instead of inlining the logic. (test-analyzer 1, code-reviewer 1)
  • 429 retry sleep bails on parent abort. Previously the full Retry-After delay (up to 5s) burned even after the caller cancelled. Also parent-aborts now map to network_error("request cancelled by caller") instead of silently masquerading as timeout in logs. (code-reviewer 2, silent-failure 1)
  • Safety-net 500 path now logs + sets Cache-Control: no-store. (silent-failure 3)
  • resolveCanonical logs non-404 errors instead of silently swallowing them. 404 stays silent because "no mirror exists" is the normal case for nm* datasets. (silent-failure 4)

Important — testability:

  • outcomeValue exhaustiveness anchored against the type. The test now uses satisfies Exclude<FetchOutcome<unknown>, {kind:"ok"}>[], so adding a new outcome kind forces an explicit case in the test array. (test-analyzer 3)

Comments:

  • Dropped redundant JSDocs (the ones that restated the type signature).
  • "Legacy" removed from the section divider — both T | null and *Outcome variants are first-class APIs after this PR.
  • SSR-page 404/503 comment now explains the asymmetry WHY (only confirmed when both signals agree). (comment-analyzer 1-4)

Deferred / declined:

  • silent-failure 5 (monitoring docs): not a code defect. The PR description already flags the new 404 behavior; the actual changelog/runbook update belongs in nemarOrg/website's release notes when this PR ships.
  • code-reviewer 3 (SSR vs API inconsistency on degraded paths): deliberate. SSR 503s because the page can't render at all. API endpoints fall through to a manifest path because they CAN still produce useful output (just slower). When SSR 503s, the client-side deferred fetches don't fire at all, so there's no inconsistency from the user's perspective. Documented in the readme.ts/tree.ts comments.

Net result: 143 tests pass (7 new for resolveDatasetPageStatus + 1 anchored exhaustiveness), typecheck clean, biome clean on changed files, build clean.

@neuromechanist
neuromechanist merged commit 4607865 into main May 19, 2026
1 check passed
@neuromechanist
neuromechanist deleted the 32-refactor-jsonfetch-to-distinguish-error-types-timeout-vs-404-vs-5xx-vs-parse-error branch May 19, 2026 04:30
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.

Refactor jsonFetch to distinguish error types (timeout vs 404 vs 5xx vs parse error)

1 participant