Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
feat(api): add a readiness check at /api/health/ready
spacesdrive23fc6087e175
diff --git a/backend/container.ts b/backend/container.tsindex 7c3c45c..7105718 100644--- a/backend/container.ts+++ b/backend/container.ts@@ -10,6 +10,7 @@ import { createAutomationCommentRepository } from './repositories/automationCommimport { createAutomationAccountRepository } from './repositories/automationAccountRepository.ts';import { createAutomationFollowupRepository } from './repositories/automationFollowupRepository.ts';import { createAutomationPublicReplyRepository } from './repositories/automationPublicReplyRepository.ts';+import { createHealthRepository } from './repositories/healthRepository.ts';import { createAccountService } from './services/accountService.ts';import { createYouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';import { createInstagramAnalyticsService } from './services/instagramAnalyticsService.ts';@@ -30,7 +31,9 @@ import { createAutomationFollowupProcessor } from './services/automationFollowupimport { createAutomationPublicReplyProcessor } from './services/automationPublicReplyProcessor.ts';import { createAutomationReconciler } from './services/automationReconciler.ts';import { createRetentionService } from './services/retentionService.ts';+import { createHealthService } from './services/healthService.ts';import type { AccountService } from './services/accountService.ts';+import type { HealthService } from './services/healthService.ts';import type { YouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';import type { InstagramAnalyticsService } from './services/instagramAnalyticsService.ts';import type { RedditAnalyticsService } from './services/redditAnalyticsService.ts';@@ -82,6 +85,7 @@ export interface Services {automationPublicReplies: AutomationPublicReplyProcessor;automationReconciler: AutomationReconciler;retention: RetentionService;+ health: HealthService;}// the composition root: wires repositories into services for one request or one cron run; building them is cheap@@ -120,5 +124,6 @@ export function createServices(clients: Clients, config: AppConfig, context: ReqautomationPublicReplies: createAutomationPublicReplyProcessor({ publicReplies, automation, context }),automationReconciler: createAutomationReconciler({ comments, publicReplies, context }),retention: createRetentionService({ comments, audit, context }),+ health: createHealthService({ health: createHealthRepository(clients.supabase) }),};}diff --git a/backend/controllers/healthController.ts b/backend/controllers/healthController.tsindex 45b5471..ec7727c 100644--- a/backend/controllers/healthController.ts+++ b/backend/controllers/healthController.ts@@ -1,6 +1,13 @@-import { controller } from './http.ts';-import type { HealthResponse } from '../../shared/types/domain.ts';+import { controller, servicesFor } from './http.ts';+import type { HealthResponse, ReadinessResponse } from '../../shared/types/domain.ts';+// liveness: the Worker answers; it never touches the database, so it stays cheap for frequent checksexport const getHealth = controller.createHandlers(c => {return c.json({ status: 'ok', timestamp: new Date().toISOString() } satisfies HealthResponse);});++// readiness: the secrets are set and the database answers+export const getReadiness = controller.createHandlers(async c => {+ const result = await servicesFor(c).health.readiness();+ return c.json(result satisfies ReadinessResponse);+});diff --git a/backend/repositories/healthRepository.ts b/backend/repositories/healthRepository.tsnew file mode 100644index 0000000..b1067ca--- /dev/null+++ b/backend/repositories/healthRepository.ts@@ -0,0 +1,15 @@+import { execute } from './query.ts';+import type { SupabaseClient } from '../types/app.ts';++export interface HealthRepository {+ ping(): Promise<void>;+}++export function createHealthRepository(db: SupabaseClient): HealthRepository {+ return {+ // the smallest read the service key can make; it proves the database answers, not that every query is healthy+ async ping() {+ await execute('health.ping', () => db.from('accounts').select('id').limit(1));+ },+ };+}diff --git a/backend/routes/index.ts b/backend/routes/index.tsindex 924503f..a2fb22e 100644--- a/backend/routes/index.ts+++ b/backend/routes/index.ts@@ -11,16 +11,17 @@ import redditRoutes from './redditRoutes.ts';import scheduledPostRoutes from './scheduledPostRoutes.ts';import settingsRoutes from './settingsRoutes.ts';import trackedContentRoutes from './trackedContentRoutes.ts';-import { getHealth } from '../controllers/healthController.ts';+import { getHealth, getReadiness } from '../controllers/healthController.ts';import { handleInstagramCallback } from '../controllers/instagramAuthController.ts';import { rateLimit, clientIp } from '../middleware/rateLimit.ts';import { RATE_LIMIT_RULES } from '../lib/rateLimit/rules.ts';import type { AppEnv } from '../types/app.ts';-// reachable without a token: the health check, the OAuth redirect, whose signed state names the user,+// reachable without a token: the health checks, the OAuth redirect, whose signed state names the user,// and the Supabase Auth email hook and Instagram webhook, whose signatures prove where they came fromexport const publicRoutes = new Hono<AppEnv>();publicRoutes.get('/health', ...getHealth);+publicRoutes.get('/health/ready', ...getReadiness);publicRoutes.get('/auth/instagram/callback', rateLimit(RATE_LIMIT_RULES.oauth, clientIp), ...handleInstagramCallback);publicRoutes.route('/', authHookRoutes);publicRoutes.route('/', instagramWebhookRoutes);diff --git a/backend/services/healthService.ts b/backend/services/healthService.tsnew file mode 100644index 0000000..9fa0f06--- /dev/null+++ b/backend/services/healthService.ts@@ -0,0 +1,21 @@+import type { HealthRepository } from '../repositories/healthRepository.ts';+import type { ReadinessResponse } from '../../shared/types/domain.ts';++export interface HealthDeps {+ health: HealthRepository;+}++export interface HealthService {+ readiness(): Promise<ReadinessResponse>;+}++// the core secrets are checked before any service is built, so ready means the database answered too+export function createHealthService({ health }: HealthDeps): HealthService {+ return {+ async readiness() {+ const started = Date.now();+ await health.ping();+ return { status: 'ready', databaseMs: Date.now() - started, timestamp: new Date().toISOString() };+ },+ };+}diff --git a/backend/tests/routes/healthRoutes.test.ts b/backend/tests/routes/healthRoutes.test.tsnew file mode 100644index 0000000..e8f4414--- /dev/null+++ b/backend/tests/routes/healthRoutes.test.ts@@ -0,0 +1,39 @@+import { test, describe } from 'node:test';+import assert from 'node:assert/strict';+import { publicRoutes } from '../../routes/index.ts';+import { fakeSupabase, tableRow } from '../fixtures/fakeSupabase.ts';+import { mountWithContext, callRoute } from '../fixtures/routeHarness.ts';++const brokenSupabase = { calls: [], from() { throw new Error('connect ECONNREFUSED'); } };++describe('health routes', () => {+ test('liveness answers without touching the database', async () => {+ const app = mountWithContext(app => app.route('/', publicRoutes), { supabase: brokenSupabase });+ const response = await callRoute(app, 'GET', '/health');+ assert.equal(response.status, 200);+ assert.equal(JSON.parse(response.body).status, 'ok');+ });++ test('readiness answers ready once the database returns a row, with how long it took', async () => {+ const supabase = fakeSupabase([tableRow('accounts', { id: 'a-1', user_id: 'user-1' })]);+ const app = mountWithContext(app => app.route('/', publicRoutes), { supabase });+ const response = await callRoute(app, 'GET', '/health/ready');+ assert.equal(response.status, 200);+ const body = JSON.parse(response.body);+ assert.equal(body.status, 'ready');+ assert.equal(typeof body.databaseMs, 'number');+ assert.deepEqual(supabase.calls.map(call => [call.type, call.table]), [['select', 'accounts']]);+ });++ test('readiness fails with the usual database error, never the driver message, when the database is down', async () => {+ const app = mountWithContext(app => app.route('/', publicRoutes), { supabase: brokenSupabase });+ const response = await callRoute(app, 'GET', '/health/ready');+ assert.equal(response.status, 500);+ assert.deepEqual(JSON.parse(response.body), {+ success: false,+ code: 'DATABASE_ERROR',+ message: 'The database request failed. Try again in a moment.',+ requestId: 'req-test',+ });+ });+});diff --git a/shared/types/domain.ts b/shared/types/domain.tsindex a804018..0af1bad 100644--- a/shared/types/domain.ts+++ b/shared/types/domain.ts@@ -312,6 +312,14 @@ export interface HealthResponse {timestamp: string;}+// GET /api/health/ready; a missing secret or a failed database check answers the usual ApiFailure instead+export interface ReadinessResponse {+ status: 'ready';+ // how long the database check took, so a monitor can see it slowing before it fails+ databaseMs: number;+ timestamp: string;+}+// body of POST /api/scheduled-posts; the route fills in defaults for the optional fieldsexport interface ScheduledPostRequest {accountId: string;