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: describe the circuit breaker and the accounts identity index
spacesdrivec896d9186213
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f96bd90..8dc127c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,8 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).- New table `automation_public_replies` and new columns and functions; existing instances run `npm run db:push` before deploying (#107)- `GET /api/health/ready`, a readiness check for monitors: it confirms the Supabase secrets are set and the database answers, and reports how long the database took (#110)- A recovery runbook, `docs/workflows/RECOVERY.md`: finding a failed request, pausing automation, rolling back, and backing up and restoring the database (#114)+- When YouTube, Instagram or Reddit fails five times in a row, Twiligent stops calling it for 30 seconds and answers at once that it is not answering, instead of waiting on every request; scheduled posts that meet it are retried (#117, ADR-045)+- A unique index on accounts, so adding the same account twice at the same moment stores it once; existing instances run `npm run db:push` (#116)### Changeddiff --git a/DECISIONS.md b/DECISIONS.mdindex 0da66d6..74c8de9 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -968,3 +968,24 @@ New row ids come from `crypto.randomUUID()` (`newRowId()` in `backend/lib/ids.ts- The activity list's status filter follows the private reply; public replies count in the Needs attention and Waiting numbers, and each row shows both.- Twenty-three migrations, one entity each, and three more SQL functions to keep in step with the fake queue in the tests.- The migrations must be applied before the new Worker is deployed; the old Worker keeps working with them, since replaced functions only gain columns and keys.++## ADR-045: A circuit breaker per platform, and a unique index for accounts++**Date:** 2026-10-17+**Status:** Accepted++**Decision:** The YouTube, Instagram and Reddit request helpers run every call through a circuit breaker (`lib/circuitBreaker.ts`, #117). Five outages in a row (a timeout the caller did not cause, an unreachable host, a 5xx) pause calls to that platform for 30 seconds; paused calls fail at once with an `UpstreamError` of reason `unreachable`; one trial call then closes or reopens it. Accounts get a unique index on the user, the platform and the account's identity in `data` (#116); an insert that breaks it becomes the same `ConflictError` the list check gives, and a racing Instagram connect renews the stored token.++**Context:** A reliability review (#109) found that a platform outage made every request wait for its error or timeout, and refreshing all accounts called the failing platform once per account. Adding an account was a check then an insert, so two adds at the same moment could store the account twice. Production held no duplicates when the index was added.++**Why in memory:** The breaker lives in the Worker isolate, with no Redis or database state, so it costs nothing per call and works when Redis is absent. Each isolate learns about an outage on its own, which is enough to stop one isolate hammering a platform during a burst such as a refresh of every account.++**Alternatives considered:**+- A breaker shared through Redis. Every call would pay a Redis round trip, and Redis is optional.+- A breaker on comment replies too. `instagramMessaging.ts` already classifies every answer, waits out rate limits with per-account cooldowns and never resends an unknown outcome; a breaker would change those rules.+- Cloudflare Queues for platform work. The work that needs a queue (comment replies, follow-ups, public replies, scheduled posts) already has one in Postgres with claims and leases; a second queue would duplicate it.+- A unique constraint on new columns. The identity already lives in `data`, so an expression index needs no column or backfill.++**Trade-offs:**+- A paused platform answers "try again in a minute" even if it recovered a few seconds earlier.+- Reddit usernames are compared exactly, as the service already did, so a different capitalisation counts as a different account.diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.mdindex 6809e14..5e3d18a 100644--- a/docs/architecture/backend/SERVICES.md+++ b/docs/architecture/backend/SERVICES.md@@ -144,7 +144,7 @@ There is no barrel: services and tests import each module directly, and each mod| Module | Contents ||---|---|-| `instagramApi.ts` | `igFetch(endpoint, params, retries, signal)` GET transport (15 s timeout, one retry on a network blip, never after the request signal aborted; no API version prefix for `/oauth`, `/access_token`, `/refresh_access_token`), `igPost(endpoint, params, signal)` (never retried, so a publish cannot run twice), `readGraphResponse` and `fetchInstagramProfile` |+| `instagramApi.ts` | `igFetch(endpoint, params, retries, signal)` GET transport (through the Instagram circuit breaker, 15 s timeout, one retry on a network blip, never after the request signal aborted; no API version prefix for `/oauth`, `/access_token`, `/refresh_access_token`), `igPost(endpoint, params, signal)` (never retried, so a publish cannot run twice), `readGraphResponse` and `fetchInstagramProfile` || `instagramTokens.ts` | `exchangeForLongLivedToken`, `refreshLongLivedToken` || `instagramOAuth.ts` | `isOAuthConfigured`, `buildAuthorizationUrl`, `exchangeCodeForToken`, `upgradeToLongLivedToken` || `instagramMedia.ts` | `classifyInstagramMedia`, `extractInstagramViews`, `normalizeInstagramMedia`, paged `fetchInstagramMedia` |@@ -214,7 +214,7 @@ There is no barrel: services and tests import each module directly.| Module | Contents ||---|---|-| `youtubeApi.ts` | `ytFetch(endpoint, params, apiKey, signal)` (adds `key` to the params object it is given; an API error becomes an `UpstreamError` carrying `reason` and `status`, a cancelled call an `UpstreamTimeoutError`) and `optionalCount` (null for a hidden or missing count) |+| `youtubeApi.ts` | `ytFetch(endpoint, params, apiKey, signal)` (through the YouTube circuit breaker; adds `key` to the params object it is given; an API error becomes an `UpstreamError` carrying `reason` and `status`, a cancelled call an `UpstreamTimeoutError`) and `optionalCount` (null for a hidden or missing count) || `youtubeChannels.ts` | Channel id extraction from URLs and handles, the handle, username, search lookup chain, `resolveChannelId`, `fetchChannelData` || `youtubeVideos.ts` | `normalizeYouTubeVideo`, the playlist page fetch that treats `playlistNotFound` as no videos, `fetchAllVideos` || `youtubeTracked.ts` | `extractYouTubeVideoId`, `fetchTrackedYouTubeData` |@@ -258,7 +258,7 @@ There is no barrel: services and tests import each module directly.### HTTP Client-`redditApi.ts` holds the API code. All Reddit public JSON API calls go through `redditFetch(path, cookie, signal)`, and `normalizeRedditPost()` maps each submitted post to the cached post shape. Requests include a descriptive `User-Agent` header (required by Reddit). When a cookie is passed, it is sent as `Cookie: reddit_session=<value>` for private account access and higher rate limits. A 404 becomes a `NotFoundError` (the user does not exist); a 403 (expired cookie), a 429 and other failures become an `UpstreamError` with a message that says what to do.+`redditApi.ts` holds the API code. All Reddit public JSON API calls go through `redditFetch(path, cookie, signal)`, which runs them through the Reddit circuit breaker (`lib/circuitBreaker.ts`), and `normalizeRedditPost()` maps each submitted post to the cached post shape. Requests include a descriptive `User-Agent` header (required by Reddit). When a cookie is passed, it is sent as `Cookie: reddit_session=<value>` for private account access and higher rate limits. A 404 becomes a `NotFoundError` (the user does not exist); a 403 (expired cookie), a 429 and other failures become an `UpstreamError` with a message that says what to do.### Key Functionsdiff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.mdindex deecdff..f9bb45b 100644--- a/docs/architecture/database/SCHEMA.md+++ b/docs/architecture/database/SCHEMA.md@@ -64,6 +64,7 @@ Stores connected YouTube channels, Instagram accounts and Reddit profiles.| `accounts_platform_check` | `platform in ('youtube', 'instagram', 'reddit')` || `accounts_data_check` | `data` is a JSON object || `accounts_id_user_id_key` | `unique (id, user_id)`, so posts can reference an account together with its owner |+| `accounts_identity_key` | Unique index on `(user_id, platform, identity)`, where the identity is `data ->> 'channelId'` for YouTube, `data ->> 'username'` for Reddit and `data ->> 'igUserId'` for Instagram. Two adds of the same account at the same moment store one row; the other gets the usual 409 |### `data` jsonb shape for YouTube accounts@@ -468,6 +469,7 @@ An index exists because a frequent query filters or orders on its columns. Each| `scheduled_posts_claimed_idx` | `scheduled_posts (claimed_at) where status = 'publishing'` | `listStale`: publishing posts whose claim is older than the lease | Partial, the same reason || `tracked_posts_user_id_created_at_idx` | `tracked_posts (user_id, created_at desc)` | `trackedPosts.listForUser`: `where user_id = $1 order by created_at desc` | Replaces `tracked_posts_user_id_idx` || `accounts_instagram_user_idx` | `accounts ((data ->> 'igUserId')) where platform = 'instagram'` | `automation_rules_for_ig_user`: the accounts a webhook names | An expression index, since the id lives in `data` |+| `accounts_identity_key` | `accounts (user_id, platform, <identity>)`, unique | Not a read path: it stops a second row for the same account | An expression on `data`, chosen per platform with `case` || `automation_rules_user_id_created_at_idx` | `automation_rules (user_id, created_at, id)` | `automationRules.listForUser` | || `automation_rules_enabled_account_idx` | `automation_rules (account_id) where enabled` | The webhook's rule lookup | Partial: only enabled rules are read || `automation_comments_due_idx` | `automation_comments (next_attempt_at) where status in ('queued', 'retry_wait')` | Due jobs by time; the queue health | Partial, so the growing history is left out |diff --git a/docs/guidelines/ERROR_HANDLING.md b/docs/guidelines/ERROR_HANDLING.mdindex 090aace..0da5b8f 100644--- a/docs/guidelines/ERROR_HANDLING.md+++ b/docs/guidelines/ERROR_HANDLING.md@@ -10,7 +10,7 @@ Every backend failure is a typed error thrown where the problem is found and for| `UnauthorizedError` | `UNAUTHORIZED` | 401 | No token, or an invalid or expired one (thrown by `requireAuth`), or a Send Email hook call without a valid signature (thrown by `verifyAuthHook`) || `ForbiddenError` | `FORBIDDEN` | 403 | Reserved; another user's record is a `NotFoundError` || `NotFoundError` | `NOT_FOUND` | 404 | The record does not exist for this user, or is on the wrong platform |-| `ConflictError` | `CONFLICT` | 409 | The account is already added |+| `ConflictError` | `CONFLICT` | 409 | The account is already added, found by the list check or, for an add at the same moment, by the unique index (`isUniqueViolation`) || `RateLimitedError` | `RATE_LIMITED` | 429 | A daily allowance is used up: the auth email caps in `authEmailService.ts`. Per-request limits are the rate limiter's job, not this error || `UpstreamError` | `UPSTREAM_ERROR` | 502 | YouTube, Instagram, Reddit or Resend answered with an error || `NotConfiguredError` | `NOT_CONFIGURED` | 503 | A Worker secret the request needs is not set, or a core Supabase secret is missing (thrown by `injectClients` for every request) |@@ -32,6 +32,8 @@ if (data.error) {}```+Each platform's request helper (`ytFetch`, `igFetch` and `igPost`, `redditFetch`) runs its call through a circuit breaker (`lib/circuitBreaker.ts`, one per platform and Worker isolate). Five outages in a row, meaning a timeout the caller did not cause, an unreachable host or a 5xx, pause calls for 30 seconds: they fail at once with an `UpstreamError` (reason `unreachable`, so a scheduled post that meets it is retried) whose message says to try again in a minute. One trial call then decides whether the platform is back. A 4xx, such as an expired token, never opens it, and Instagram's Graph error codes are not read as HTTP statuses. Comment replies (`instagramMessaging.ts`) keep their own cooldowns and do not use it.+`UpstreamError` passes its message through `redactSecrets` (`lib/redact.ts`), which removes URLs, `Bearer` tokens and token-like `name=value` pairs and JSON fields, because a platform error can echo the request URL, a header or the form body with the API key or token in it. Cast the parsed JSON once to an interface that covers the fields the module reads (see `docs/guidelines/TYPESCRIPT.md`).Pass the request's `AbortSignal` to every `fetch`. A cancelled or timed out call becomes an `UpstreamTimeoutError`; a network failure an `UpstreamError`:@@ -73,7 +75,7 @@ The repository keeps this in three private helpers (`readKey`, `writeKey`, `dele### Services (`services/*Service.ts`)-Services hold the rules, so they throw most errors: `NotFoundError` when a `...ForUser` lookup returns `null`, `ValidationError` when a stored field the call needs is missing or a business rule fails, `ConflictError` for a duplicate, `NotConfiguredError` when a Worker secret is not set. Let platform and database errors propagate unchanged.+Services hold the rules, so they throw most errors: `NotFoundError` when a `...ForUser` lookup returns `null`, `ValidationError` when a stored field the call needs is missing or a business rule fails, `ConflictError` for a duplicate, `NotConfiguredError` when a Worker secret is not set. Let platform and database errors propagate unchanged, with one exception: an insert that breaks a unique index (`isUniqueViolation(err)` in `lib/errors.ts`, Postgres code `23505`) is a duplicate the service already has a message for, so it becomes that `ConflictError`.Catch only when one failure must not stop other work, and say why:diff --git a/docs/workflows/RECOVERY.md b/docs/workflows/RECOVERY.mdindex d1de876..3cce864 100644--- a/docs/workflows/RECOVERY.md+++ b/docs/workflows/RECOVERY.md@@ -10,6 +10,8 @@ What to do when something breaks in production. Each section names the check tha| `curl -i <backend-url>/api/health/ready` | The Supabase secrets are set and the database answers; `databaseMs` shows how long the database took. A `503 NOT_CONFIGURED` names the missing secret, a `500 DATABASE_ERROR` means the database did not answer || `npx wrangler tail` (from `backend/`) | The Worker's log lines as they happen: one access line per request, every failure with its request id, and the cron runs (`scheduled publish run`, `automation dispatch`, `automation reconcile`, `cron run skipped`) |+A message such as "YouTube is not answering, so calls to it are paused for a moment" comes from the circuit breaker: that platform failed five times in a row, and calls to it fail at once for 30 seconds before one trial call checks again. It clears on its own; check the platform's status page if it keeps coming back.+A person who reports an error can quote the request id at the end of the error message. Search the tail output for it. Logs are streamed, not stored: turn on Workers Logs for the Worker in the Cloudflare dashboard to keep them.## 2. Stop the damagediff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.mdindex f494219..94cb566 100644--- a/docs/workflows/TESTING.md+++ b/docs/workflows/TESTING.md@@ -36,6 +36,9 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that| `backend/routes/index.ts` (health checks) | `backend/tests/routes/healthRoutes.test.ts` || `backend/database/supabase.ts` | `backend/tests/database/supabase.test.ts` || `backend/lib/redact.ts` | `backend/tests/lib/redact.test.ts` |+| `backend/lib/circuitBreaker.ts` | `backend/tests/lib/circuitBreaker.test.ts` |+| `backend/services/accountService.ts` | `backend/tests/services/accountService.test.ts` (and the account route tests) |+| `backend/services/instagramConnectService.ts` | `backend/tests/services/instagramConnectService.test.ts` || `backend/validators/fields.ts` | `backend/tests/validators/fields.test.ts` || `supabase/migrations/*.sql` and `supabase/rollbacks/*.sql` | `backend/tests/database/migrations.test.ts` || `frontend/src/lib/accounts.ts` | `frontend/tests/lib/accounts.test.ts` |@@ -81,7 +84,7 @@ Site tests are in `site/tests/docs/` and `site/tests/lib/`. `chart.test.ts` checTest files import the code under test the same way, by relative path with the `.ts` extension (`../../src/lib/accounts.ts`). Type test fakes narrowly: cast a fake once to the interface it stands in for, rather than using `any`, which is a lint error.-The error contract has its own tests: `tests/middleware/errorHandler.test.ts` (the status and body for each error code, platform messages without URLs, database and unexpected errors hidden from the client, validation and malformed JSON, and unknown routes) and, on the frontend, `tests/lib/apiErrors.test.ts` (the message `request()` throws, with the request id on 5xx). Repository tests (`tests/repositories/*.test.ts`) check the user filter, the `data` merge and the `DatabaseError` for a failed query against the fake Supabase client, and `analyticsCacheRepository.test.ts` the cache keys, versions and failure cooldown. Validator tests (`tests/validators/*.test.ts`) check the field helpers and their messages. The failure paths around them have tests too: `tests/middleware/clients.test.ts` (a missing Supabase secret answers `NOT_CONFIGURED` naming it), `tests/lib/config.test.ts` (which secrets count as missing), `tests/jobs/scheduled.test.ts` (a cron run without them logs and stops), `tests/database/supabase.test.ts` (a query that never answers is cut off at the timeout, with mocked timers), `tests/routes/healthRoutes.test.ts` (liveness without the database, readiness, and a database failure hidden from the client) and `tests/lib/redact.test.ts` (URLs, Bearer tokens and token parameters removed, ordinary messages unchanged).+The error contract has its own tests: `tests/middleware/errorHandler.test.ts` (the status and body for each error code, platform messages without URLs, database and unexpected errors hidden from the client, validation and malformed JSON, and unknown routes) and, on the frontend, `tests/lib/apiErrors.test.ts` (the message `request()` throws, with the request id on 5xx). Repository tests (`tests/repositories/*.test.ts`) check the user filter, the `data` merge and the `DatabaseError` for a failed query against the fake Supabase client, and `analyticsCacheRepository.test.ts` the cache keys, versions and failure cooldown. Validator tests (`tests/validators/*.test.ts`) check the field helpers and their messages. The failure paths around them have tests too: `tests/middleware/clients.test.ts` (a missing Supabase secret answers `NOT_CONFIGURED` naming it), `tests/lib/config.test.ts` (which secrets count as missing), `tests/jobs/scheduled.test.ts` (a cron run without them logs and stops), `tests/database/supabase.test.ts` (a query that never answers is cut off at the timeout, with mocked timers), `tests/routes/healthRoutes.test.ts` (liveness without the database, readiness, and a database failure hidden from the client) and `tests/lib/redact.test.ts` (URLs, Bearer tokens and token parameters removed, ordinary messages unchanged). `tests/lib/circuitBreaker.test.ts` covers the breaker with an injected clock: four failures still pass, the fifth pauses calls with a temporary error, the trial after 30 seconds closes or reopens it, other calls fail during the trial, client errors and cancelled calls never count, and an Instagram Graph code such as 506 is not a server error. `tests/services/accountService.test.ts` and `instagramConnectService.test.ts` cover an add or a connect that loses a race to the unique index: the add answers the usual 409, any other failed insert stays a database error, and the connect renews the stored token.Rate limiting has its own tests: `tests/lib/rateLimit/algorithms.test.ts` (each algorithm's decisions, retry and reset times), `tests/lib/rateLimit/limiter.test.ts` (Redis path, memory fallback, circuit breaker, deny cache, eviction) and `tests/middleware/rateLimit.test.ts` (headers, the 429 body, route filters, IPv6 keys). The Lua scripts in `lib/rateLimit/scripts.ts` cannot run in Node; when you change one, change the twin function in `algorithms.ts` the same way and check both against each other in a Lua VM (see `docs/architecture/backend/RATE_LIMITING.md`).