-
-
Notifications
You must be signed in to change notification settings - Fork 193
feat: add /api/healthz and /api/readyz endpoints #749
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
hellivan
wants to merge
1
commit into
oss-apps:main
Choose a base branch
from
hellivan:feat/health-ready-endpoints
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.
Open
Changes from all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| import type { NextApiRequest, NextApiResponse } from 'next'; | ||
|
|
||
| /** | ||
| * Liveness check. Deliberately does not touch the database (or any other external | ||
| * dependency) - an orchestrator restarting this process would not fix a database | ||
| * outage, and could cause cascading restarts across all replicas at once. See | ||
| * `/api/readyz` for a database-aware check suitable for readiness/traffic routing. | ||
| */ | ||
| export default function handler(req: NextApiRequest, res: NextApiResponse) { | ||
| if ('GET' !== req.method) { | ||
| res.setHeader('Allow', 'GET'); | ||
| return res.status(405).json({ status: 'error', message: 'Method not allowed' }); | ||
| } | ||
|
|
||
| return res.status(200).json({ status: 'ok' }); | ||
| } | ||
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,39 @@ | ||
| import { Prisma } from '@prisma/client'; | ||
| import type { NextApiRequest, NextApiResponse } from 'next'; | ||
|
|
||
| import { db } from '~/server/db'; | ||
|
|
||
| const DB_CHECK_TIMEOUT_MS = 3000; | ||
|
|
||
| /** | ||
| * Readiness check. Verifies the database is reachable, bounded by a short timeout so a | ||
| * hung connection fails the check quickly instead of leaving the request pending. The | ||
| * timeout is enforced by Postgres itself (`statement_timeout`, scoped to this transaction | ||
| * via `SET LOCAL`) rather than raced client-side, so a slow query is actually cancelled | ||
| * instead of left running against the connection pool. Meant for load balancers/ | ||
| * orchestrators to stop routing traffic here without restarting the process - see | ||
| * `/api/healthz` for the dependency-free liveness check. | ||
| * | ||
| * This only bounds queries that reach Postgres - it can't help if the socket itself is | ||
| * dead (see the `connect_timeout`/`socket_timeout` note in docs/CONFIGURATION.md), so it's | ||
| * a complement to those connection-string options rather than a replacement for them. | ||
| */ | ||
| export default async function handler(req: NextApiRequest, res: NextApiResponse) { | ||
| if ('GET' !== req.method) { | ||
| res.setHeader('Allow', 'GET'); | ||
| return res.status(405).json({ status: 'error', message: 'Method not allowed' }); | ||
| } | ||
|
|
||
| try { | ||
| // DB_CHECK_TIMEOUT_MS is a hardcoded constant, not user input, so inlining it via | ||
| // Prisma.raw is safe here - `SET` does not accept bound query parameters. | ||
| await db.$transaction([ | ||
| db.$executeRaw`SET LOCAL statement_timeout = ${Prisma.raw(String(DB_CHECK_TIMEOUT_MS))}`, | ||
| db.$queryRaw`SELECT 1`, | ||
| ]); | ||
| return res.status(200).json({ status: 'ok' }); | ||
| } catch (error) { | ||
| console.error('Readiness check failed:', error); | ||
| return res.status(503).json({ status: 'error', message: 'Database not reachable' }); | ||
| } | ||
| } |
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,37 @@ | ||
| import type { NextApiRequest, NextApiResponse } from 'next'; | ||
|
|
||
| import handler from '~/pages/api/healthz'; | ||
|
|
||
| const createMockRes = () => { | ||
| const res = {} as NextApiResponse; | ||
| res.status = jest.fn().mockReturnValue(res); | ||
| res.json = jest.fn().mockReturnValue(res); | ||
| res.setHeader = jest.fn().mockReturnValue(res); | ||
| return res; | ||
| }; | ||
|
|
||
| describe('/api/healthz', () => { | ||
| describe('GET requests', () => { | ||
| it('responds with 200 ok for GET requests', () => { | ||
| const req = { method: 'GET' } as NextApiRequest; | ||
| const res = createMockRes(); | ||
|
|
||
| handler(req, res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(200); | ||
| expect(res.json).toHaveBeenCalledWith({ status: 'ok' }); | ||
| }); | ||
| }); | ||
|
|
||
| describe('method validation', () => { | ||
| it('rejects non-GET methods', () => { | ||
| const req = { method: 'POST' } as NextApiRequest; | ||
| const res = createMockRes(); | ||
|
|
||
| handler(req, res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(405); | ||
| expect((res.setHeader as jest.Mock).mock.calls).toContainEqual(['Allow', 'GET']); | ||
| }); | ||
| }); | ||
| }); |
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,118 @@ | ||
| import type { Prisma } from '@prisma/client'; | ||
| import type { NextApiRequest, NextApiResponse } from 'next'; | ||
|
|
||
| jest.mock('~/server/db', () => ({ | ||
| db: { | ||
| $executeRaw: jest.fn(), | ||
| $queryRaw: jest.fn(), | ||
| $transaction: jest.fn(), | ||
| }, | ||
| })); | ||
|
|
||
| import { db } from '~/server/db'; | ||
| import handler from '~/pages/api/readyz'; | ||
|
|
||
| const createMockRes = () => { | ||
| const res = {} as NextApiResponse; | ||
| res.status = jest.fn().mockReturnValue(res); | ||
| res.json = jest.fn().mockReturnValue(res); | ||
| res.setHeader = jest.fn().mockReturnValue(res); | ||
| return res; | ||
| }; | ||
|
|
||
| describe('/api/readyz', () => { | ||
| afterEach(() => { | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| describe('successful checks', () => { | ||
| it('responds with 200 ok when the database is reachable', async () => { | ||
| (db.$transaction as jest.Mock).mockResolvedValue([undefined, [{ '?column?': 1 }]]); | ||
| const req = { method: 'GET' } as NextApiRequest; | ||
| const res = createMockRes(); | ||
|
|
||
| await handler(req, res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(200); | ||
| expect(res.json).toHaveBeenCalledWith({ status: 'ok' }); | ||
| }); | ||
|
|
||
| it('scopes a 3s statement_timeout to the check via SET LOCAL', async () => { | ||
| (db.$executeRaw as jest.Mock).mockReturnValue('SET_STATEMENT_TIMEOUT'); | ||
| (db.$queryRaw as jest.Mock).mockReturnValue('SELECT_1'); | ||
| (db.$transaction as jest.Mock).mockResolvedValue([undefined, [{ '?column?': 1 }]]); | ||
| const req = { method: 'GET' } as NextApiRequest; | ||
| const res = createMockRes(); | ||
|
|
||
| await handler(req, res); | ||
|
|
||
| const executeRawCall = (db.$executeRaw as jest.Mock).mock.calls[0] as | ||
| | [TemplateStringsArray, Prisma.Sql] | ||
| | undefined; | ||
| if (!executeRawCall) { | ||
| throw new Error('Expected db.$executeRaw to have been called'); | ||
| } | ||
| const [setTimeoutStrings, rawTimeoutValue] = executeRawCall; | ||
| expect(setTimeoutStrings.join('')).toContain('SET LOCAL statement_timeout = '); | ||
| expect(rawTimeoutValue.strings.join('')).toBe('3000'); | ||
|
|
||
| const queryRawCall = (db.$queryRaw as jest.Mock).mock.calls[0] as | ||
| | [TemplateStringsArray] | ||
| | undefined; | ||
| if (!queryRawCall) { | ||
| throw new Error('Expected db.$queryRaw to have been called'); | ||
| } | ||
| const [selectStrings] = queryRawCall; | ||
| expect(selectStrings.join('')).toBe('SELECT 1'); | ||
|
|
||
| // Order matters: the timeout must be set before SELECT 1 runs in the same transaction. | ||
| expect((db.$transaction as jest.Mock).mock.calls[0]?.[0]).toEqual([ | ||
| 'SET_STATEMENT_TIMEOUT', | ||
| 'SELECT_1', | ||
| ]); | ||
| }); | ||
| }); | ||
|
|
||
| describe('database failures', () => { | ||
| it('responds with 503 when the database is unreachable', async () => { | ||
| (db.$transaction as jest.Mock).mockRejectedValue(new Error('connection refused')); | ||
| const req = { method: 'GET' } as NextApiRequest; | ||
| const res = createMockRes(); | ||
|
|
||
| await handler(req, res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(503); | ||
| expect(res.json).toHaveBeenCalledWith({ | ||
| status: 'error', | ||
| message: 'Database not reachable', | ||
| }); | ||
| }); | ||
|
|
||
| it('responds with 503 when the database check times out', async () => { | ||
| (db.$transaction as jest.Mock).mockRejectedValue( | ||
| new Error('canceling statement due to statement timeout'), | ||
| ); | ||
| const req = { method: 'GET' } as NextApiRequest; | ||
| const res = createMockRes(); | ||
|
|
||
| await handler(req, res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(503); | ||
| }); | ||
| }); | ||
|
|
||
| describe('method validation', () => { | ||
| it('rejects non-GET methods', async () => { | ||
| const req = { method: 'POST' } as NextApiRequest; | ||
| const res = createMockRes(); | ||
|
|
||
| await handler(req, res); | ||
|
|
||
| expect(res.status).toHaveBeenCalledWith(405); | ||
| expect((res.setHeader as jest.Mock).mock.calls).toContainEqual(['Allow', 'GET']); | ||
| expect((db.$executeRaw as jest.Mock).mock.calls).toHaveLength(0); | ||
| expect((db.$queryRaw as jest.Mock).mock.calls).toHaveLength(0); | ||
| expect((db.$transaction as jest.Mock).mock.calls).toHaveLength(0); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| }); | ||
| }); | ||
| }); | ||
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.
Uh oh!
There was an error while loading. Please reload this page.