Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

docs(api): describe the layered request pipeline

spacesdrivecc9e1c4bd9b0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e980c15..ed4ac87 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,15 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Changed
+**Backend request pipeline in layers**
+- The Worker is organised as middleware, route tables, controllers, services and repositories (`docs/architecture/backend/REQUEST_PIPELINE.md`); every database query is in a repository and every rule in a service
+- Every failed request answers with one body, `{ success, code, message, requestId }`, and a status that matches the failure: 400 invalid input, 401 sign-in, 404 not found, 409 already added, 429 rate limited, 502 platform error, 503 server not configured, 504 platform timeout, 500 server error. Database and unexpected errors no longer show internal messages; server errors in the app show a request id to quote
+- Every response carries `X-Request-Id`, and the Worker writes one JSON log line per request plus error lines tied to the same id
+- Request bodies and query strings are checked before any work starts; malformed JSON is a clear 400
+- Platform calls stop when the browser disconnects or after 30 seconds, and Overview background syncing stops after 25 seconds
+- The API only answers browsers on `FRONTEND_URL` and the new optional `ALLOWED_ORIGINS` list, and sends security headers (content security policy, no framing, no referrer, nosniff, HSTS)
+- Account fields in the analytics responses go through `safeAccount()` like every other account response
+
**TypeScript**
- The backend Worker, the React app, the scheduled publisher script and every test are now TypeScript in strict mode, with no change in behaviour: each file, with its types removed, matches the JavaScript it replaced
- API request and response shapes live once in `shared/types/` and are used by both the Worker routes and `services/api.ts`
@@ -62,6 +71,8 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Fixed
+- The Instagram connection redirected to `//accounts` when `FRONTEND_URL` ended with a slash
+- Refreshing all accounts sent the YouTube API key to YouTube without removing a pasted byte order mark
- Media chips and scrims over photos used a hex colour and `text-white`; they now use the `media-scrim` and `on-media` design tokens. The Overview metric tabs use a declared `none` variant of `TabsList`, and the mobile sidebar keeps the class and HTML attributes passed to `Sidebar` instead of dropping them
- YouTube analytics counted hidden like and comment counts as zero, which pulled averages and engagement rates down; averages and rates now use only the videos that report each count, and hidden counts sort last (see `docs/architecture/data-flows/ANALYTICS.md`). A channel with no videos now returns the same fields and formats as a full result, a Reddit profile without karma totals reports 0 instead of NaN, and date checks use `getTime()`
- Saving the scheduling repository in Settings erased the stored GitHub token and then reported `configured: false` and `patSet: false`. The unused token is no longer stored or reported: `GET /api/settings/github` returns only `repoOwner`, `repoName` and `branch`
diff --git a/DECISIONS.md b/DECISIONS.md
index ceaa087..1e5d847 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -656,3 +656,21 @@ Records every significant architectural decision, the alternatives considered, a
**Trade-offs:**
- The planned GitHub archive feature (ROADMAP.md) will need to add a token field again, with masked responses and a decision on where the secret lives.
- An unused secret is no longer kept in plaintext in the database.
+
+---
+
+## ADR-032: A layered request pipeline with one error contract
+
+**Date:** 2026-10-14
+**Status:** Accepted
+
+**Decision:** The Worker is split into layers with one job each: middleware in a fixed order (`backend/app.ts`: CORS, request id and context, security headers, clients, rate limit by IP, authentication, per-user rate limits), route tables (`routes/`), controllers (`controllers/`, HTTP only), services (`services/`, business rules, no Hono types) and repositories (`repositories/`, one method per Supabase query or cache operation). A composition root (`container.ts`) builds each request's services. Services receive a framework-free `RequestContext` (request id, cancellation signal, logger) and the user id as an argument. Input is validated by Hono's `validator` before the controller runs. Every failure is a typed error (`lib/errors.ts`) that `middleware/errorHandler.ts` turns into one body, `{ success: false, code, message, requestId }`, with the status chosen by the code. CORS allows `FRONTEND_URL` and the optional `ALLOWED_ORIGINS` instead of every origin, and every response carries security headers.
+
+**Context:** Route files mixed HTTP parsing, business rules, platform calls and queries; `lib/db.ts` had functions whose meaning changed with an optional user id; errors came in three shapes, with statuses picked per route and raw database messages sent to the client; nothing tied a log line to a request; and no platform call could be cancelled.
+
+**Trade-offs:**
+- More files per feature (route table, controller, service, validator), in exchange for each one being small and testable on its own.
+- Error statuses changed for some failures (a duplicate account is 409 instead of 400, a missing server key 503, a platform failure 502). The frontend only reads the message, so it is unaffected, but anything else calling the API sees the new statuses.
+- Building every service per request costs a few object allocations; nothing is cached across requests.
+- A browser on an origin that is not `FRONTEND_URL` or listed in `ALLOWED_ORIGINS` can no longer call the API. A local Worker also allows the Vite dev server.
+- The request deadline (30 seconds) and the warm-up deadline (25 seconds) abandon slow platform calls instead of waiting indefinitely.
diff --git a/ROADMAP.md b/ROADMAP.md
index 3e6cbc2..3176b46 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -118,7 +118,6 @@ React Native app using the same Cloudflare Worker backend.
- `wrangler.toml` has no `vars` section for non-secret configuration - any non-sensitive config currently requires a redeploy to change.
- The scheduled publishers (`backend/utils/scheduler` and `scripts/publish-scheduled`) publish due posts one after another in a single run. A large batch due at the same moment can exceed the Worker's or the Actions job's time limit; the rest wait for the next run.
-- CORS allows every origin. Restricting it to `FRONTEND_URL` would block other sites from calling the API with a stolen token.
- Rate limits are counted per Worker isolate when Redis is not configured, which is looser than one global count (see `docs/architecture/backend/RATE_LIMITING.md`).
- The project stays on TypeScript 6.0 until `typescript-eslint` supports TypeScript 7.
- No end-to-end tests; see `docs/workflows/TESTING.md` for the planned Playwright coverage.
diff --git a/claude.md b/claude.md
index 6b88161..b2c30ac 100644
--- a/claude.md
+++ b/claude.md
@@ -38,7 +38,9 @@ eslint.config.mjs shared ESLint config (typescript-eslint, frontend rules, b
.prettierrc.json shared Prettier config matching the existing style (not applied in bulk)
.editorconfig editor defaults (4 spaces in backend, 2 elsewhere)
shared/types/ API contract types shared by backend and frontend (types only, no runtime code)
-backend/ Hono Worker; tests in backend/tests/ mirroring the source folders
+backend/ Hono Worker in layers: middleware/, routes/, controllers/, services/, repositories/,
+ validators/, database/, jobs/, lib/; app.ts builds the pipeline, container.ts wires services;
+ tests in backend/tests/ mirroring the source folders
frontend/ React SPA; tests in frontend/tests/ mirroring frontend/src/
scripts/ publish-scheduled.ts, run by GitHub Actions with no dependencies
```
@@ -77,6 +79,7 @@ docs/
architecture/
OVERVIEW.md System topology, connections, request lifecycle
backend/
+ REQUEST_PIPELINE.md Middleware, route table, controller, service, repository; request context; error contract
HONO.md App structure, middleware, routing pattern
ROUTES.md All routes, method, auth requirement, purpose
SERVICES.md instagram.ts, youtube.ts service layer
@@ -259,7 +262,7 @@ This is not optional for features that touch new UI patterns, new APIs, or new i
**Always read before writing.** Read every file you will modify. Read all files in the same directory that might be affected. Read sibling files to understand conventions before adding new ones.
-**Match the existing pattern.** This project has established conventions for routes, context hooks, db.ts queries, cache.ts patterns, and api.ts methods. Find the nearest existing example and follow it exactly before introducing anything new.
+**Match the existing pattern.** This project has established conventions for route tables, controllers, services, repositories, validators, context hooks and api.ts methods. Find the nearest existing example and follow it exactly before introducing anything new.
**TypeScript only, in strict mode.** The whole project - Worker, React app, shared types, scripts and tests - is TypeScript (`.ts`, and `.tsx` for files with JSX). Never add a `.js` or `.jsx` source file, never use `any`, `@ts-ignore` or `@ts-expect-error`, and only use syntax Node can strip (no enums, namespaces or parameter properties; `import type` for types; relative imports keep their `.ts` extension). Types the API sends or receives live in `shared/types/`; change them there first. `npm run typecheck` must pass before every commit. See `docs/guidelines/TYPESCRIPT.md`.
@@ -269,14 +272,14 @@ This is not optional for features that touch new UI patterns, new APIs, or new i
- `SUPABASE_SERVICE_KEY` is only ever used server-side (backend Worker)
- `SUPABASE_ANON_KEY` on the backend is only for JWT verification
- Instagram `accessToken` is always stripped by `safeAccount()` before any response
-- All user-scoped queries always append `.eq('user_id', userId)` where `userId` comes from a verified JWT, never from user input
+- All user-scoped queries always append `.eq('user_id', userId)` where `userId` comes from a verified JWT, never from user input; only repository methods named `...ForUser` serve requests, and the unscoped ones are for cron jobs
- `backend/.dev.vars` must never be committed
-**Use the established db.ts pattern.** All database operations go through `lib/db.ts`. Never write inline Supabase queries in route handlers. Add new operations to `db.ts` and import them.
+**Keep each layer to its job.** Read `docs/architecture/backend/REQUEST_PIPELINE.md`. Middleware handles cross-cutting work in the order set in `backend/app.ts`. A route table only maps a path to middleware and a controller. A controller reads validated input (`backend/validators/`) and the user id, calls one service method and builds the response; it never queries the database or catches errors to format them. A service holds the rules, receives repositories and a `RequestContext`, never imports `hono`, and throws the typed errors in `lib/errors.ts`. Every Supabase query and every cache read or write lives in a repository in `backend/repositories/`, one method per query.
**Use the established api.ts pattern.** All frontend-to-backend calls go through `frontend/src/services/api.ts`. Never call `fetch()` directly in components. Add new endpoints to the `api` object in `api.ts`.
-**Redis failures are always silent.** Wrap all Redis operations in try/catch. Cache misses must fall back to live API calls. The app must work with Redis completely absent.
+**Redis failures are always silent.** `repositories/analyticsCacheRepository.ts` wraps every Redis operation in try/catch. Cache misses must fall back to live API calls. The app must work with Redis completely absent.
**Documentation is part of implementation.** When any of the following change - routes, DB schema, environment variables, deployment config, cron jobs, data flows, component conventions - update the relevant docs immediately using the table below.
@@ -321,7 +324,9 @@ When anything changes, update every relevant docs file from the table below. The
| Roadmap item started or finished | `ROADMAP.md` (link the issue when work starts; remove the entry and add it to `CHANGELOG.md` when the issue closes) |
| Project goals or priorities changed | `ROADMAP.md` (Goals section), this file (Project Identity section) |
| Issue workflow, labels or templates changed | `docs/workflows/ISSUES.md`, `.github/ISSUE_TEMPLATE/`, `.github/pull_request_template.md`, this file (Issue Tracking section) |
-| New route added | `docs/architecture/backend/ROUTES.md`, `docs/architecture/OVERVIEW.md`, `docs/workflows/TESTING.md` (add to manual verification checklist) |
+| New route added | `docs/architecture/backend/ROUTES.md`, `docs/architecture/OVERVIEW.md`, `docs/workflows/TESTING.md` (add to manual verification checklist); a route test in `backend/tests/routes/` |
+| Request pipeline, middleware order, request context or error contract changed | `docs/architecture/backend/REQUEST_PIPELINE.md`, `docs/architecture/backend/MIDDLEWARE.md`, `docs/guidelines/ERROR_HANDLING.md`, `docs/guidelines/API_CONVENTIONS.md`, `shared/types/domain.ts` (`ApiFailure`) |
+| New repository or repository method | `docs/architecture/backend/REQUEST_PIPELINE.md` (if a new repository), `docs/architecture/database/SECURITY.md` (if it is not user-scoped) |
| Route deleted or changed | `docs/architecture/backend/ROUTES.md`, `docs/architecture/OVERVIEW.md` |
| New DB table | `docs/architecture/database/SCHEMA.md`, `docs/architecture/database/SECURITY.md`, `DECISIONS.md`, `CHANGELOG.md` |
| New DB column | `docs/architecture/database/SCHEMA.md` |
@@ -339,7 +344,7 @@ When anything changes, update every relevant docs file from the table below. The
| New GitHub Actions workflow | `docs/architecture/cloudflare/CI_CD.md`, `docs/workflows/DEPLOYMENT.md` |
| Existing GitHub Actions workflow changed (steps, triggers, Node version) | `docs/architecture/cloudflare/CI_CD.md`, `docs/workflows/DEPLOYMENT.md`, `docs/architecture/cloudflare/PAGES.md` or `WORKERS.md` for the deploy it runs |
| Test added, moved or test command changed | `docs/workflows/TESTING.md` (layout, commands, coverage list) |
-| New backend service file | `docs/architecture/backend/SERVICES.md` |
+| New backend service file | `docs/architecture/backend/SERVICES.md`, `backend/container.ts` |
| New cache key | `docs/architecture/backend/CACHING.md` |
| Rate limit rule, limit or covered route changed | `docs/architecture/backend/RATE_LIMITING.md` (rules table), `backend/tests/middleware/rateLimit.test.ts` (route matchers) |
| Rate limit algorithm or Lua script changed | Both `backend/lib/rateLimit/algorithms.ts` and `scripts.ts` together, `docs/architecture/backend/RATE_LIMITING.md`, `DECISIONS.md` |
diff --git a/docs/architecture/backend/REQUEST_PIPELINE.md b/docs/architecture/backend/REQUEST_PIPELINE.md
new file mode 100644
index 0000000..70b2878
--- /dev/null
+++ b/docs/architecture/backend/REQUEST_PIPELINE.md
@@ -0,0 +1,103 @@
+# Request Pipeline
+
+Every API request passes through the same layers, and each layer has one job:
+
+| Layer | Folder | Job | Knows about |
+|---|---|---|---|
+| Middleware | `backend/middleware/` | Work every request needs: CORS, request id and logging, security headers, clients, rate limits, authentication, validation, errors | HTTP |
+| Route table | `backend/routes/` | Maps a method and path to its middleware and controller | HTTP |
+| Controller | `backend/controllers/` | Reads validated input and the user id, calls one service method, picks the status and builds the response | HTTP |
+| Service | `backend/services/` | Business rules and orchestration: what should happen | Application data only |
+| Repository | `backend/repositories/` | Data access: one method per query on a Supabase table or the Redis cache | The database |
+| Request context | `types/context.ts`, `AppVariables` | Request-scoped metadata: request id, user id, cancellation signal, logger | Nothing else |
+
+The rule of thumb: HTTP concerns stay in middleware and controllers, business concerns in services, database concerns in repositories, cross-cutting work in middleware and request metadata in the request context.
+
+## Order
+
+`backend/app.ts` builds the pipeline. The order matters: each step can answer early, so the cheap checks come first and the expensive work only runs for requests that pass them.
+
+```
+Request
+ 1. CORS middleware/cors.ts answers preflights; allows FRONTEND_URL and ALLOWED_ORIGINS only
+ 2. Request context hono/request-id + middleware/requestContext.ts
+ request id (X-Request-Id), deadline signal, one access log line
+ 3. Security headers middleware/securityHeaders.ts deny-all CSP, no framing, no-referrer, nosniff, HSTS
+ 4. Clients middleware/clients.ts per-request Supabase and Redis clients
+ 5. Rate limit by IP middleware/rateLimit.ts before authentication, so bad tokens never reach Supabase Auth
+ Public routes routes/index.ts /api/health, /api/auth/instagram/callback (with its own oauth limit)
+ 6. Authentication middleware/auth.ts verifies the JWT and sets userId; 401 otherwise
+ 7. Per-user limits middleware/rateLimit.ts user, quota and publish rules
+ 8. Route table routes/<feature>Routes.ts
+ Validation middleware/validate.ts parses and checks the body or query; 400 otherwise
+ Controller controllers/<feature>Controller.ts
+ Service services/<feature>Service.ts
+ Repository repositories/<table>Repository.ts
+Response, or a thrown error -> middleware/errorHandler.ts
+```
+
+Authorization is ownership: every user-scoped repository method filters by the verified user id, so another user's row is simply not found (404). There are no roles.
+
+## Request context
+
+The Hono context carries only small request-scoped values, declared in `AppVariables` (`backend/types/app.ts`): `requestId`, `signal`, `userId`, `userEmail` and the per-request clients. Nothing else is stored there.
+
+Services never see the Hono context. A controller hands them a `RequestContext` (`backend/types/context.ts`), built by `requestContextOf(c)`:
+
+| Field | Source | Used for |
+|---|---|---|
+| `requestId` | `hono/request-id`; an incoming `X-Request-Id` of safe characters is kept | Every log line, the `X-Request-Id` response header, error bodies |
+| `signal` | Client disconnect, or the 30 second request deadline | Passed to every platform `fetch`, so abandoned work stops |
+| `log` | `lib/logger.ts`, bound to the request id and user id | Structured JSON log lines |
+
+The user id is passed to service methods explicitly (`accounts.refresh(userId, accountId)`), never read from the request body.
+
+Cron jobs build the same context in `jobs/scheduled.ts`, with a `cron-` request id and a 14 minute deadline. The Overview's background warming outlives the response, so it uses its own 25 second deadline instead of the request signal.
+
+## Composition
+
+`backend/container.ts` is the composition root. `createServices(clients, config, context)` builds every repository and service for one request (or one cron run); building them is cheap. Controllers call `servicesFor(c)` in `controllers/http.ts`. Services receive their repositories, the cleaned config (`lib/config.ts`) and the request context as dependencies, so a test can pass fakes.
+
+## Errors
+
+Services and repositories throw typed errors from `lib/errors.ts`. An error carries a code, not a status; `middleware/errorHandler.ts` maps the code to a status and writes the one error body every failure gets:
+
+```json
+{ "success": false, "code": "NOT_FOUND", "message": "Account not found", "requestId": "3f2a..." }
+```
+
+| Error | Code | Status | Thrown when |
+|---|---|---|---|
+| `ValidationError` | `VALIDATION_ERROR` | 400 | Input is missing or malformed, or a stored field the request needs is missing |
+| `UnauthorizedError` | `UNAUTHORIZED` | 401 | No token, or an invalid or expired one |
+| `ForbiddenError` | `FORBIDDEN` | 403 | Reserved; ownership failures are 404 |
+| `NotFoundError` | `NOT_FOUND` | 404 | The resource does not exist for this user, or the route does not exist |
+| `ConflictError` | `CONFLICT` | 409 | The account is already added |
+| (rate limiter) | `RATE_LIMITED` | 429 | A rate limit rule is exceeded; the body adds `retryAfter` |
+| `UpstreamError` | `UPSTREAM_ERROR` | 502 | YouTube, Instagram or Reddit answered with an error; its message is kept, URLs are removed |
+| `NotConfiguredError` | `NOT_CONFIGURED` | 503 | A Worker secret the request needs is not set |
+| `UpstreamTimeoutError` | `UPSTREAM_TIMEOUT` | 504 | A platform call was cancelled or timed out |
+| `DatabaseError` | `DATABASE_ERROR` | 500 | A Supabase query failed; the client gets a plain message, the log gets the driver's |
+| anything else | `INTERNAL_ERROR` | 500 | A bug; the client gets a message asking it to quote the request id |
+
+Errors of status 500 and above are logged at `error` level with the request id; 4xx errors at `warn`. The frontend's `request()` shows the message and adds the request id to 5xx messages.
+
+Controllers do not catch errors to format them. The one exception is the Instagram OAuth callback, which must redirect the browser back to the app whatever happens.
+
+## Validation
+
+Hono's `validator` runs before the controller. `middleware/validate.ts` wraps it as `jsonBody(parse)` and `queryParams(parse)`; each parser in `backend/validators/` reads fields with the helpers in `validators/fields.ts` (trimming strings, checking types, applying required-field messages) and throws `ValidationError`. A malformed JSON body is a 400 from Hono's own check. The controller reads the result with `c.req.valid('json')` or `c.req.valid('query')`, so services always receive clean input.
+
+## Adding an endpoint
+
+See `docs/features/NEW_API_ENDPOINT.md`. In short: a parser in `validators/`, a method on a service (and a repository method if it needs a new query), a controller in `controllers/`, a line in the route table, and the shared request and response types in `shared/types/`.
+
+## Tests
+
+| Layer | Test |
+|---|---|
+| Route table to repository | `backend/tests/routes/*Routes.test.ts` mount a route table behind the test harness (request id, error handler, fake Supabase) and compare responses, queries and outgoing requests with golden snapshots |
+| Service | `backend/tests/services/*.test.ts` build a service with repositories over the fake Supabase client |
+| Repository | `backend/tests/repositories/*.test.ts` |
+| Middleware | `backend/tests/middleware/*.test.ts` (error handler, rate limit) |
+| Validators | `backend/tests/validators/*.test.ts` |