Skip to content

fix(api): return a graceful 503 badge instead of an unhandled 500 when the loader throws#8403

Merged
loopover-orb[bot] merged 1 commit into
JSONbored:mainfrom
kai392:fix/critical-issue-badge-route-error-handling
Jul 24, 2026
Merged

fix(api): return a graceful 503 badge instead of an unhandled 500 when the loader throws#8403
loopover-orb[bot] merged 1 commit into
JSONbored:mainfrom
kai392:fix/critical-issue-badge-route-error-handling

Conversation

@kai392

@kai392 kai392 commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Summary

GET /v1/public/repos/:owner/:repo/badge.svg and badge.json were the only public GET routes with no error handling: loadPublicRepoBadge is not fail-safe (two D1 reads plus, per its own doc, an occasional cold-cache GitHub fetch while resolving the manifest), so any transient failure escaped as Hono's bare, unstructured 500 — with no app.onError registered anywhere. Unusually visible here: these badges are unauthenticated, embedded in third-party READMEs, and served through GitHub's camo proxy, so a blip showed a broken image instead of the graceful "unavailable" badge these routes already render.

  • Both routes now wrap the loader call in the same route-level try/catch the sibling /quality route (and the fix(orb): drainOrbRelay returns HTTP 500 repeatedly (872 Sentry events, escalating) #4995 relay fix) already use. loadPublicRepoBadge and everything it calls are untouched, per the issue's Requirements.
  • The failure branch returns each route's existing unavailable rendering — renderUnavailableBadgeSvg() / the { schemaVersion: 1, label, message: "unavailable", color, cacheSeconds } shape — with 503, not 404, so a monitoring consumer can still tell "this repo has no public badge" (404, unchanged) apart from "the backend is having a transient problem", exactly the split /quality already makes.
  • The 503 branch uses the short public, max-age=300 cache (mirroring the existing 404 branch) so a transient failure is never cached for the long max-age=600, stale-while-revalidate=86400 window. Success/404 cache semantics are unchanged.

Closes #8377

Test plan

  • New regression assertions in test/integration/api.test.ts's existing badge test: with a forced D1 read failure, .svg returns 503 with image/svg+xml, Cache-Control: public, max-age=300, and the "unavailable" body; .json returns 503 with the same short cache and the full unavailable shields payload; and the healthy path still returns 200 with the long stale-while-revalidate cache
  • The failure is injected with the file's own established technique — a targeted prepare wrapper (withRepositoryReadFailure, mirroring the existing withProductUsageInsertFailure) — so the route's own catch is what produces the response
  • Every pre-existing badge assertion (200 success, and the four 404 cases: not-opted-in, private, uninstalled, unknown) passes unmodified
  • test/integration/api.test.ts fully green (50/50); npm run typecheck clean
  • CI validate

@kai392
kai392 requested a review from JSONbored as a code owner July 24, 2026 11:41
@superagent-security

Copy link
Copy Markdown
Contributor

Superagent didn't find any vulnerabilities or security issues in this PR.

@codecov

codecov Bot commented Jul 24, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.16%. Comparing base (fab2fce) to head (2792c4b).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8403      +/-   ##
==========================================
- Coverage   92.17%   90.16%   -2.01%     
==========================================
  Files         791       98     -693     
  Lines       79249    25281   -53968     
  Branches    23945     4712   -19233     
==========================================
- Hits        73048    22795   -50253     
+ Misses       5062     2214    -2848     
+ Partials     1139      272     -867     
Flag Coverage Δ
shard-1 30.44% <0.00%> (-28.31%) ⬇️
shard-2 43.26% <0.00%> (-7.26%) ⬇️
shard-3 70.75% <100.00%> (+17.46%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/api/routes.ts 95.30% <100.00%> (+0.01%) ⬆️

... and 693 files with indirect coverage changes

@loopover-orb loopover-orb Bot added the gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier. label Jul 24, 2026
@loopover-orb

loopover-orb Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Tip

✅ LoopOver review result - approve/merge recommended

Review updated: 2026-07-24 12:11:15 UTC

2 files · 1 AI reviewer · no blockers · readiness 93/100 · CI green · clean

✅ Suggested Action - Approve/Merge

  • safe to merge

Review summary
This PR wraps the two public badge routes (`badge.svg`/`badge.json`) in try/catch so a loader failure returns the existing 'unavailable' rendering with a 503 status and short cache, instead of an unhandled 500 — mirroring the pattern already used by the sibling `/quality` route. The change is narrow, correctly scoped to only the two routes named in the linked issue #8377, and the diff is internally consistent: SVG failures get `image/svg+xml` + 503 + `max-age=300`, JSON failures get the same shields-badge unavailable shape + 503 + `max-age=300`, while the healthy path (200, long stale-while-revalidate cache) is untouched. The added regression test uses a targeted `D1Database.prepare` override that throws only on `repositories`-table SQL, which forces `loadPublicRepoBadge`'s first D1 read (`getRepository`) to throw — that's a real, reachable failure path (not fabricated), and it correctly asserts status, content-type, cache-control, and body for both routes plus confirms the healthy path is unaffected.

Nits — 4 non-blocking
  • The magic numbers 404/503/300/600 duplicated across both route branches (src/api/routes.ts:1309-1330) could be named constants, though this mirrors the existing pre-diff style in the same file so it's consistent, not a regression.
  • The bare `catch {}` swallows the actual error without logging it anywhere (src/api/routes.ts catch blocks), which could make diagnosing a recurring transient failure harder in production — consider at least a `console.error` or Sentry capture given `@​sentry/hono/cloudflare` is already imported in this file.
  • Consider extracting a small shared helper for the two near-identical try/catch bodies (SVG vs JSON) to avoid the duplicated cache-header/status logic drifting apart later.
  • Log the caught error (e.g. via the already-imported Sentry integration) before returning the 503 fallback so transient failures are observable, not just silently swallowed.

Decision drivers

  • ✅ Code review — No blockers (1 reviewer)
  • ✅ Gate result — Passing (No configured blocker found.)
Context & advisory signals — never blocks the verdict
Signal Result Evidence
Linked issue ✅ Linked #8377
Related work ✅ No active overlap found No same-issue or scoped active PR overlap found.
Change scope ✅ 20/20 Low review scope from cached public metadata (1 linked issue).
Validation posture ✅ 25/25 PR body includes validation/test evidence.
Contributor workload ✅ 10/10 Author activity: 117 registered-repo PR(s), 62 merged, 4 issue(s).
Contributor context ✅ Confirmed Gittensor contributor kai392; Gittensor profile; 117 PR(s), 4 issue(s).
Improvement ✅ Minor risk: clean · value: minor · LLM: moderate
Linked issue satisfaction

Addressed
Both badge.svg and badge.json routes now wrap loadPublicRepoBadge in try/catch returning 503 with the existing unavailable renderings and short max-age=300 cache, leaving the 404 null-case and success cache semantics untouched, matching every requirement in the issue.

Review context
  • Author: kai392
  • Role context: outside_contributor
  • Public audience mode: oss maintainer
  • Lane context: Repository is configured for direct PR review.
  • Public profile languages: JavaScript, Kotlin, Perl, Python, TypeScript, Vue
  • Official Gittensor activity: 117 PR(s), 4 issue(s).
  • PR-specific overlap: none found.
Contributor next steps
  • Start here: Triage stale or unlinked PRs.
Signal definitions
  • Related work = same linked issue, overlapping active PRs, or title/path similarity.
  • Change scope = cached public metadata such as size labels, draft state, and review-burden hints.
  • Validation posture = whether the PR provides enough public validation/test evidence for maintainer review.
  • Contributor workload = public contributor activity and cleanup pressure, not a repo-wide quality failure.
  • Contributor context = public GitHub/Gittensor identity context; non-Gittensor status is not a blocker.
🧪 Chat with LoopOver

Ask LoopOver a question about this PR directly in a comment — grounded only in the same cached, public-safe facts shown above, never a new claim.

  • @loopover ask &lt;question&gt; answers contribution-quality Q&A with source citations and freshness.
  • @loopover chat &lt;question&gt; answers in natural prose from cached decision-pack facts via local inference (maintainer/collaborator; read-only).
  • A plain-language @loopover mention with a real question is routed to the closest matching read-only command automatically — no exact syntax required.

Full command reference: https://loopover.ai/docs/loopover-commands

🧪 Experimental — new and may change.

🟩 Safe / merged · 🟦 Advisory · 🟨 Held for review · 🟥 Blocked / closed


💰 Earn for open-source contributions like this. Gittensor lets GitHub contributors earn for the work they already do — register to start earning →.

Checked by LoopOver, a quiet PR intelligence layer for OSS maintainers.

  • Re-run LoopOver review

@loopover-orb loopover-orb Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LoopOver approves — the gate is satisfied and CI is green.

@loopover-orb
loopover-orb Bot merged commit 4b6e3fc into JSONbored:main Jul 24, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(api): badge.svg/badge.json have no error handling, unlike sibling public routes

2 participants