Skip to content

Add maintenance mode middleware (#342) - #343

Merged
neuromechanist merged 2 commits into
mainfrom
feature/issue-342-maintenance-mode
Apr 17, 2026
Merged

neuromechanist merged 2 commits into
mainfrom
feature/issue-342-maintenance-mode

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

  • Adds maintenanceMode middleware with three modes (off | read-only | full) toggled via the MAINTENANCE_MODE env var in wrangler.toml; redeploy to flip
  • read-only blocks POST/PUT/DELETE/PATCH everywhere except /admin/* and /webhooks/*; full blocks everything except /health, /notices, and /
  • 503 response shape: Retry-After: 3600 header plus JSON {error, message, mode, eta}
  • CLI detects the 503 maintenance payload, raises a new MaintenanceError subclass of ApiError, and prints a bordered banner instead of a stack trace
  • 15 unit tests covering each mode and whitelist path (real Hono app, no mocks)

Why

Blocks Epic #314 Phase 6 (D1 data migration) and Phase 8 (DNS cutover). Needed so we can freeze writes on the personal-account backend during the dump/restore window without losing in-flight writes.

Test plan

  • bun test backend/test/maintenance.test.ts (15 pass)
  • tsc --noEmit on both backend/ and root
  • Biome lint clean
  • Deploy to dev (bun run deploy:dev) and smoke-test 503 with curl -X POST
  • After merge, deploy to prod; leave MAINTENANCE_MODE = "off" until the migration window

Closes #342.

Toggle via MAINTENANCE_MODE env var: off | read-only | full.
read-only blocks mutations except /admin/* and /webhooks/*; full blocks
everything except /health, /notices, and /. Response is 503 with
Retry-After header and {error, mode, eta} body.

CLI detects the 503 maintenance payload, raises MaintenanceError, and
prints a bordered banner instead of a stack trace.

Needed for the SCCN Cloudflare migration (Epic #314) to freeze the
personal-account backend during the D1 dump/restore window.
@github-actions

github-actions Bot commented Apr 17, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR343

Version: 0.7.26-PR343.f4e7799
Commit: f4e7799


🤖 Updated on each push.

Code review findings fixed in this commit:

- Extract MaintenanceMode to backend/src/types/maintenance.ts so the
  literal union is defined in one place (was duplicated across 3 files
  plus 2 runtime guards); drift risk removed
- Whitelist POST /auth/login in read-only so admins whose tokens expire
  can re-authenticate to hit /admin/*; signup stays blocked
- parseMode now logs a console.error once per isolate on unknown
  MAINTENANCE_MODE values instead of silently falling back to off;
  a typo like 'readonly' would otherwise leave prod unprotected
- respond503 logs blocked requests so Cloudflare logs confirm why
  503s are being returned during a freeze
- Mark MaintenanceError.mode and .eta readonly; validate eta with
  typeof instead of 'as string | null' cast
- Print maintenance banner from request() itself (once per process via
  module-scoped flag) so per-command catches that swallow errors still
  surface the banner; drops the duplicated banner helper in src/index.ts
- Use errorDetail() in top-level catch instead of err.message || err
- Trim epic/issue references from middleware JSDoc and wrangler.toml
  comment

Test coverage added:

- PATCH/PUT/DELETE/OPTIONS in read-only
- Path-prefix edge cases: /adminfoo, /admin (no slash) both 503
- /auth/login passes in read-only, /auth/signup blocks
- /healthz and /notices/123 confirm exact-match whitelist
- Retry-After asserted in full mode
- Invalid MAINTENANCE_MODE string actually exercises parseMode fallback
- New test/maintenance-client.test.ts covers CLI-side MaintenanceError
  detection against a real local Bun.serve: read-only/full/unknown
  mode, missing body, non-string eta coercion, default message
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review fixes applied (f4e7799)

Addressed the findings from all 5 review agents. Test count: 26 backend + 7 CLI = 33 passing.

Critical

  • [silent-failure] MaintenanceError swallowed by per-command catches: fixed. request() now prints the banner itself (once per process via module-scoped flag) before throwing, so it surfaces even when per-command catches do console.log(err.message); process.exit(1). New src/lib/maintenance-banner.ts.
  • [silent-failure] parseMode silent fallback to "off": fixed. Unknown MAINTENANCE_MODE values log a console.error once per isolate before defaulting; a typo like "readonly" won't silently leave prod unprotected.

Important

  • [code] read-only blocks POST /auth/login: fixed. Added READ_ONLY_EXACT_MUTATIONS whitelist containing just /auth/login so admins can re-auth mid-freeze. Signup remains blocked.
  • [silent-failure] respond503 emits no log: fixed. Every blocked request now logs [maintenance] blocked <METHOD> <path> (mode=<mode>).
  • [tests] CLI-side MaintenanceError untested: fixed. New test/maintenance-client.test.ts stands up a real Bun.serve returning 503 with various mode payloads and asserts MaintenanceError vs ApiError is thrown; 7 tests.
  • [tests] "invalid values" was a false positive: fixed. Widened envWith to accept string, test now passes "readonly" to actually exercise the parseMode fallback.

Improvements

  • [tests] Added PATCH/PUT/DELETE coverage in read-only, OPTIONS preflight, path-prefix edges (/adminfoo, /admin no slash), exact-match whitelist (/healthz, /notices/123), and Retry-After assertion in full mode.
  • [types] Extracted MAINTENANCE_MODES tuple into backend/src/types/maintenance.ts. MaintenanceMode and ActiveMaintenanceMode = Exclude<MaintenanceMode, "off"> derive from one source. Bindings.MAINTENANCE_MODE imports it. No more duplicated literal unions.
  • [types] MaintenanceError.mode and .eta are now readonly. eta validated with typeof data.eta === "string" before construction.
  • [comments] Dropped Epic #314 and issue number references in middleware JSDoc and wrangler.toml. Trimmed the Modes block. Removed the test file header paragraph.
  • [minor] Top-level main().catch now uses errorDetail(err) instead of err.message || err.

Not changed (false-positive or nice-to-have deferred)

  • Code reviewer's note that per-command catches still print raw err.message on top of the banner: cosmetic duplication (banner on stderr, message on stdout). Rewriting all ~90 catches is out of scope; the banner-in-request approach gives the user the context they need.

@neuromechanist
neuromechanist merged commit f40ce36 into main Apr 17, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-342-maintenance-mode branch April 17, 2026 16:55

This branch was previously deployed

1 inactive deployment
npm — f4e7799d Deployed Apr 17, 2026 by neuromechanist via publish #600
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.

Add maintenance mode for SCCN migration window

1 participant