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.

5.4 KB
Raw Blame

Architectural Principles

Core Principles

1. Fetch at the edge, not in the client

The Cloudflare Worker sits at the edge, close to the user. All data fetching - from Supabase, from external platform APIs, from Redis - happens in the Worker. The React client fetches from the Worker only. The client never talks to Supabase or platform APIs directly.

Why: Keeps credentials server-side. Enables caching at the edge. Single point of auth enforcement.

2. One source of auth truth

Authentication is Supabase JWTs. The Worker verifies the JWT on every protected request by asking Supabase Auth (auth.getUser(token) with the anon key, in requireAuth), which checks the signature, the expiry and whether the session was revoked. userId derived from the verified JWT is the only identity that matters. No session state in the Worker. No cookies. The per-IP rate limit runs before this check, so a flood of bad tokens never reaches Supabase Auth.

Why: The Worker keeps no auth state of its own, and a signed-out session stops working at once.

3. Application-layer isolation instead of RLS

Every user-scoped repository method (named ...ForUser) appends .eq('user_id', userId) where userId comes from the verified JWT and is passed down from the controller. The Worker uses the service-role key (which bypasses RLS). RLS is enabled with no policies and the browser roles have no grants, only to keep the public anon key and members' own tokens away from the tables; it is not relied upon for isolation. The schema adds a second guard: composite foreign keys tie a post's account to the same user (ADR-038).

Why: RLS adds complexity without benefit when the application layer already enforces isolation. The service-role key is needed for admin operations (cron jobs, token refresh) that run without a user JWT. See ADR-011.

Constraint: Never relax the .eq('user_id', userId) pattern. If you write a query without it, you have a data exposure bug.

4. Fail silently on the cache

Redis is optional infrastructure. The cache repository (analyticsCacheRepository.ts) always catches errors and returns null on failure. The application falls through to the source of truth (Supabase / platform API). A Redis outage is invisible to users.

Why: Cache is a performance optimization, not a correctness requirement. Making it optional makes the system more resilient. See ADR-008.

5. Credentials stay in the Worker

Platform API credentials (Instagram app secret, YouTube API key) are Worker secrets - not in code, not in the database, not in the frontend. The only credential that goes near the frontend is the Supabase anon key, which is public by design.

User-specific credentials (Instagram access tokens) live in accounts.data in the database. They are read by the Worker and never returned to the frontend. See ADR-004.

6. Schemas bend before tables multiply

New platform-specific fields go into the data jsonb column on accounts or scheduled_posts. Adding a new table requires a clear reason: the data has a lifecycle of its own, or it needs to be queried/filtered by a column that can't be in jsonb. See ADR-005.

7. Strict TypeScript, stripped rather than compiled

Every layer is TypeScript in strict mode, and the API contract lives once in shared/types/, used by both the Worker and the frontend. Nothing is compiled ahead of time: Wrangler, Vite and Node strip the types, and npm run typecheck gates every deploy and pull request. Only erasable syntax is allowed, so any file can run directly under Node. See ADR-030 (which replaces ADR-010) and docs/guidelines/TYPESCRIPT.md.

8. One job per layer, one error contract

A request passes through middleware, a route table, a controller, a service and a repository, and each layer has one job: HTTP concerns in middleware and controllers, business rules in services, queries in repositories. Services never see the Hono context, so a cron job runs the same code with its own request context. Every failure is a typed error that one error handler turns into { success: false, code, message, requestId }. See ADR-032 and docs/architecture/backend/REQUEST_PIPELINE.md.

Why: Each rule has one place to live and one place to test, and the client handles every failure the same way.

What This Architecture Is Not

Not a microservices architecture. One Worker serves all backend routes. One Hono app. One entry point.

Not a real-time system. There are no WebSockets, no Server-Sent Events. Analytics pages refresh on load. Scheduled post status updates on poll.

Not a multi-tenant platform. Every user has their own credentials, their own accounts. There is no concept of organizations, teams, or shared accounts at the data layer. (This is a known constraint - see ROADMAP.md.)

When to Break These Rules

These principles guide the initial implementation. Breaking them requires an explicit ADR:

  • Adding a second Worker: write ADR-013 explaining why one Worker is insufficient
  • Enabling RLS: write an ADR explaining why application-layer isolation failed
  • Adding a compile step or non-erasable TypeScript syntax (enum, parameter properties): write an ADR with clear measurable benefit
  • Adding a state management library: write an ADR showing that context + local state is insufficient

The cost of documenting the decision is intentionally low. The point is to make the tradeoff visible, not to prevent evolution.