Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/app/api/health/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@ export const maxDuration = 10

async function checkInfraApi(): Promise<boolean> {
try {
const { error } = await infra.GET('/health', {})
if (!error) {
// infra-api answers /health with text/plain, which the default JSON parsing rejects
const { response, error } = await infra.GET('/health', {
parseAs: 'text',
})
if (response.ok) {
return true
}

l.error(
{
key: 'health_check:infra_api_error',
status: response.status,
error,
},
'Infra API health check failed'
Expand Down
104 changes: 79 additions & 25 deletions tests/integration/health-route.test.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,104 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

const { infraGet } = vi.hoisted(() => ({
infraGet: vi.fn(),
}))

vi.mock('@/core/shared/clients/api', () => ({
infra: {
GET: infraGet,
},
const { logError } = vi.hoisted(() => ({
logError: vi.fn(),
}))

vi.mock('@/core/shared/clients/logger/logger', () => ({
l: {
error: vi.fn(),
},
l: { error: logError },
serializeErrorForLog: vi.fn((error) => error),
}))

import { GET } from '@/app/api/health/route'
const fetchMock = vi.fn<typeof fetch>()

describe('/api/health', () => {
beforeEach(() => {
vi.clearAllMocks()
})
// the infra client resolves its base URL at import, so load the route after stubbing env
async function loadRoute() {
vi.resetModules()
return import('@/app/api/health/route')
}

function requestedUrl(): string {
const [input] = fetchMock.mock.calls[0] ?? []
if (input instanceof Request) return input.url
return String(input)
}

beforeEach(() => {
vi.stubEnv('PUBLIC_E2B_DOMAIN', 'example.dev')
vi.stubEnv('E2B_INFRA_API_URL', '')
vi.stubGlobal('fetch', fetchMock)
})

afterEach(() => {
vi.unstubAllEnvs()
vi.unstubAllGlobals()
fetchMock.mockReset()
logError.mockReset()
})

describe('/api/health', () => {
it('returns ok when infra-api is healthy', async () => {
infraGet.mockResolvedValue({ error: null })
fetchMock.mockResolvedValue(
new Response('Health check successful', {
status: 200,
headers: { 'content-type': 'text/plain' },
})
)
const { GET } = await loadRoute()

const response = await GET()
const body = await response.json()

expect(requestedUrl()).toBe('https://api.example.dev/health')
expect(response.status).toBe(200)
expect(body).toEqual({
expect(await response.json()).toEqual({
status: 'ok',
checks: { infraApi: true },
})
expect(logError).not.toHaveBeenCalled()
})

it('returns degraded when infra-api is unhealthy', async () => {
infraGet.mockResolvedValue({ error: { message: 'downstream unavailable' } })
it('returns degraded and logs the status when infra-api is not ok', async () => {
fetchMock.mockResolvedValue(
new Response('downstream unavailable', {
status: 503,
headers: { 'content-type': 'text/plain' },
})
)
const { GET } = await loadRoute()

const response = await GET()
const body = await response.json()

expect(requestedUrl()).toBe('https://api.example.dev/health')
expect(response.status).toBe(503)
expect(body.status).toBe('degraded')
expect(body.checks).toEqual({ infraApi: false })
expect(await response.json()).toEqual({
status: 'degraded',
checks: { infraApi: false },
})
expect(logError).toHaveBeenCalledWith(
expect.objectContaining({
key: 'health_check:infra_api_error',
status: 503,
error: 'downstream unavailable',
}),
'Infra API health check failed'
)
})

it('returns degraded when the request to infra-api fails', async () => {
fetchMock.mockRejectedValue(new TypeError('fetch failed'))
const { GET } = await loadRoute()

const response = await GET()

expect(requestedUrl()).toBe('https://api.example.dev/health')
expect(response.status).toBe(503)
expect(await response.json()).toEqual({
status: 'degraded',
checks: { infraApi: false },
})
expect(logError).toHaveBeenCalledWith(
expect.objectContaining({ key: 'health_check:infra_api_error' }),
'Infra API health check failed'
)
})
})
Loading