-
Notifications
You must be signed in to change notification settings - Fork 329
feat(web): add /api/health/ready endpoint with dependency health checks #1507
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Harsh23Kashyap
wants to merge
5
commits into
sourcebot-dev:main
Choose a base branch
from
Harsh23Kashyap:feat/health-readiness
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+443
−1
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
8668e52
feat(web): extract lazy Zoekt gRPC client into a shared module
Harsh23Kashyap 8e90c6f
feat(web): add /api/health/ready endpoint with dependency health checks
Harsh23Kashyap 0f04b34
test(web): cover /api/health/ready healthy and degraded paths
Harsh23Kashyap e29ed6b
docs(health): document liveness vs readiness split
Harsh23Kashyap 375f2dd
chore: changelog entry for /api/health/ready
Harsh23Kashyap File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| --- | ||
| title: "Health Endpoints" | ||
| description: "Liveness and readiness probes for orchestrators and monitoring systems." | ||
| --- | ||
|
|
||
| Sourcebot exposes two public health endpoints that follow the standard Kubernetes liveness / readiness split. Both are unauthenticated and return no user data. | ||
|
|
||
| ## Liveness: `GET /api/health` | ||
|
|
||
| Returns `200 OK` with `{ "status": "ok" }` whenever the Next.js process is running and able to handle a request. Does not touch the database, Redis, or Zoekt. Use this for Kubernetes `livenessProbe` or Docker Compose `healthcheck.test`. A failing liveness probe means the process must be restarted. | ||
|
|
||
| ```bash | ||
| curl -fsS https://sourcebot.example.com/api/health | ||
| # {"status":"ok"} | ||
| ``` | ||
|
|
||
| ## Readiness: `GET /api/health/ready` | ||
|
|
||
| Returns `200 OK` with `{"status":"ok", "checks":{...}}` when Postgres, Redis, and Zoekt are all reachable. Returns `503 Service Unavailable` with `{"status":"degraded", "checks":{...}}` if any dependency is unreachable. Each check runs in parallel with a 2-second per-check timeout, so the worst-case request time is bounded even when a dependency hangs. | ||
|
|
||
| Use this for Kubernetes `readinessProbe` or a load balancer health check. A failing readiness probe means the pod should be removed from the load-balancer rotation but not restarted. | ||
|
|
||
| ### Response shape | ||
|
|
||
| ```json | ||
| { | ||
| "status": "ok", | ||
| "checks": { | ||
| "postgres": { "status": "ok", "latencyMs": 3 }, | ||
| "redis": { "status": "ok", "latencyMs": 1 }, | ||
| "zoekt": { "status": "ok", "latencyMs": 12 } | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| When degraded, each failed check carries an `error` field with the underlying message: | ||
|
|
||
| ```json | ||
| { | ||
| "status": "degraded", | ||
| "checks": { | ||
| "postgres": { "status": "ok", "latencyMs": 4 }, | ||
| "redis": { "status": "ok", "latencyMs": 1 }, | ||
| "zoekt": { "status": "error", "latencyMs": 2003, "error": "zoekt check timed out after 2000ms" } | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| | Check | What it probes | | ||
| |-------|---------------| | ||
| | `postgres` | `SELECT 1` via Prisma | | ||
| | `redis` | `PING` (rejects non-`PONG` responses) | | ||
| | `zoekt` | `List` RPC with a 1-second wall-time cap (proves the gRPC channel is alive) | | ||
|
|
||
| ### Example probes | ||
|
|
||
| <Tabs> | ||
| <Tab title="Docker Compose"> | ||
| ```yaml | ||
| services: | ||
| sourcebot: | ||
| image: sourcebot/sourcebot:latest | ||
| healthcheck: | ||
| test: ["CMD", "wget", "-qO-", "http://localhost:3000/api/health"] | ||
| interval: 30s | ||
| timeout: 5s | ||
| retries: 3 | ||
| # For dependency-aware probes, point the orchestrator at /api/health/ready | ||
| # instead. Sourcebot's example compose file does this via a sidecar. | ||
| ``` | ||
| </Tab> | ||
| <Tab title="Kubernetes"> | ||
| ```yaml | ||
| livenessProbe: | ||
| httpGet: | ||
| path: /api/health | ||
| port: 3000 | ||
| initialDelaySeconds: 30 | ||
| periodSeconds: 30 | ||
| timeoutSeconds: 5 | ||
| failureThreshold: 3 | ||
| readinessProbe: | ||
| httpGet: | ||
| path: /api/health/ready | ||
| port: 3000 | ||
| initialDelaySeconds: 10 | ||
| periodSeconds: 10 | ||
| timeoutSeconds: 5 | ||
| successThreshold: 1 | ||
| failureThreshold: 3 | ||
| ``` | ||
| </Tab> | ||
| </Tabs> | ||
|
|
||
| <Note> | ||
| The readiness probe hits the database on every call. On large deployments with many pods, a high-frequency probe interval (sub-5s) can produce noticeable background load. A 10s interval with `failureThreshold: 3` is a good starting point. | ||
| </Note> |
152 changes: 152 additions & 0 deletions
152
packages/web/src/app/api/(server)/health/ready/route.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| import { beforeEach, describe, expect, test, vi } from 'vitest'; | ||
|
|
||
| const mocks = vi.hoisted(() => ({ | ||
| unsafePrisma: { | ||
| $queryRaw: vi.fn(), | ||
| }, | ||
| redisPing: vi.fn(), | ||
| zoektList: vi.fn(), | ||
| })); | ||
|
|
||
| vi.mock('server-only', () => ({})); | ||
|
|
||
| vi.mock('@/prisma', () => ({ | ||
| __unsafePrisma: mocks.unsafePrisma, | ||
| })); | ||
|
|
||
| vi.mock('@/lib/redis', () => ({ | ||
| getRedisClient: () => ({ | ||
| ping: mocks.redisPing, | ||
| }), | ||
| })); | ||
|
|
||
| vi.mock('@/lib/posthog', () => ({ | ||
| captureEvent: vi.fn(), | ||
| })); | ||
|
|
||
| vi.mock('@/lib/zoektClient', () => ({ | ||
| loadZoektClient: () => ({ | ||
| List: mocks.zoektList, | ||
| }), | ||
| })); | ||
|
|
||
| vi.mock('@sourcebot/shared', () => ({ | ||
| createLogger: () => ({ | ||
| debug: vi.fn(), | ||
| info: vi.fn(), | ||
| warn: vi.fn(), | ||
| error: vi.fn(), | ||
| }), | ||
| })); | ||
|
|
||
| const { GET } = await import('./route'); | ||
|
|
||
| describe('GET /api/health/ready', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| mocks.unsafePrisma.$queryRaw.mockResolvedValue([{ '?column?': 1 }]); | ||
| mocks.redisPing.mockResolvedValue('PONG'); | ||
| mocks.zoektList.mockImplementation( | ||
| (_request: unknown, callback: (err: Error | null) => void) => { | ||
| callback(null); | ||
| }, | ||
| ); | ||
| }); | ||
|
|
||
| test('returns 200 with status:ok when all three dependencies are reachable', async () => { | ||
| const response = await GET(); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(200); | ||
| expect(body.status).toBe('ok'); | ||
| expect(body.checks.postgres.status).toBe('ok'); | ||
| expect(body.checks.redis.status).toBe('ok'); | ||
| expect(body.checks.zoekt.status).toBe('ok'); | ||
| expect(typeof body.checks.postgres.latencyMs).toBe('number'); | ||
| expect(typeof body.checks.redis.latencyMs).toBe('number'); | ||
| expect(typeof body.checks.zoekt.latencyMs).toBe('number'); | ||
| }); | ||
|
|
||
| test('returns 503 with status:degraded and a postgres error when Postgres is unreachable', async () => { | ||
| mocks.unsafePrisma.$queryRaw.mockRejectedValue(new Error('connection refused')); | ||
|
|
||
| const response = await GET(); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(503); | ||
| expect(body.status).toBe('degraded'); | ||
| expect(body.checks.postgres.status).toBe('error'); | ||
| expect(body.checks.postgres.error).toBe('connection refused'); | ||
| expect(body.checks.redis.status).toBe('ok'); | ||
| expect(body.checks.zoekt.status).toBe('ok'); | ||
| }); | ||
|
|
||
| test('returns 503 with status:degraded and a redis error when Redis ping fails', async () => { | ||
| mocks.redisPing.mockRejectedValue(new Error('redis down')); | ||
|
|
||
| const response = await GET(); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(503); | ||
| expect(body.status).toBe('degraded'); | ||
| expect(body.checks.postgres.status).toBe('ok'); | ||
| expect(body.checks.redis.status).toBe('error'); | ||
| expect(body.checks.redis.error).toBe('redis down'); | ||
| expect(body.checks.zoekt.status).toBe('ok'); | ||
| }); | ||
|
|
||
| test('returns 503 with status:degraded when the Zoekt gRPC call errors', async () => { | ||
| mocks.zoektList.mockImplementation( | ||
| (_request: unknown, callback: (err: Error | null) => void) => { | ||
| callback(new Error('UNAVAILABLE: zoekt not reachable')); | ||
| }, | ||
| ); | ||
|
|
||
| const response = await GET(); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(503); | ||
| expect(body.status).toBe('degraded'); | ||
| expect(body.checks.zoekt.status).toBe('error'); | ||
| expect(body.checks.zoekt.error).toContain('UNAVAILABLE'); | ||
| expect(body.checks.postgres.status).toBe('ok'); | ||
| expect(body.checks.redis.status).toBe('ok'); | ||
| }); | ||
|
|
||
| test('returns 503 with status:degraded when Redis returns a non-PONG response', async () => { | ||
| mocks.redisPing.mockResolvedValue('NOT-PONG'); | ||
|
|
||
| const response = await GET(); | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(503); | ||
| expect(body.status).toBe('degraded'); | ||
| expect(body.checks.redis.status).toBe('error'); | ||
| expect(body.checks.redis.error).toContain('unexpected ping response'); | ||
| }); | ||
|
|
||
| test('runs all three checks in parallel (Promise.all)', async () => { | ||
| const delay = 50; | ||
| mocks.unsafePrisma.$queryRaw.mockImplementation( | ||
| () => new Promise((resolve) => setTimeout(() => resolve([{}]), delay)), | ||
| ); | ||
| mocks.redisPing.mockImplementation( | ||
| () => new Promise((resolve) => setTimeout(() => resolve('PONG'), delay)), | ||
| ); | ||
| mocks.zoektList.mockImplementation( | ||
| (_request: unknown, callback: (err: Error | null) => void) => { | ||
| setTimeout(() => callback(null), delay); | ||
| }, | ||
| ); | ||
|
|
||
| const start = Date.now(); | ||
| const response = await GET(); | ||
| const elapsed = Date.now() - start; | ||
| const body = await response.json(); | ||
|
|
||
| expect(response.status).toBe(200); | ||
| expect(body.status).toBe('ok'); | ||
| // Generous upper bound to avoid flakes; serial would be ~3x delay. | ||
| expect(elapsed).toBeLessThan(delay * 2.5); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Link the changelog entry to this PR, not issue
#1506.Replace the issue URL with this pull request’s
[#<id>](https://github.com/sourcebot-dev/sourcebot/pull/<id>)link. As per coding guidelines, changelog entries must include the GitHub pull request id at the end of the line.🤖 Prompt for AI Agents
Source: Coding guidelines