All files / web/src/app/api/smoke-test-status route.ts

0% Statements 0/134
0% Branches 0/1
0% Functions 0/1
0% Lines 0/134

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135                                                                                                                                                                                                                                                                             
/**
 * Smoke test status endpoint for Gatus monitoring
 *
 * GET /api/smoke-test-status
 *
 * Returns the status of the most recent COMPLETED smoke test run:
 * - 200 + {status: 'passed'} if latest completed run passed and is < 25 hours old
 * - 503 if failed, stale, or no data
 *
 * Note: Running tests are ignored - we report the last completed result.
 * This prevents Gatus from showing unhealthy status while tests are running.
 *
 * Used by Gatus to determine if browser smoke tests are passing.
 */

import { NextResponse } from 'next/server'
import { desc, ne } from 'drizzle-orm'
import { db } from '@/db'
import { smokeTestRuns } from '@/db/schema'
import { withAuth } from '@/lib/auth/withAuth'

export const dynamic = 'force-dynamic'

interface SmokeTestStatusResponse {
  status: 'passed' | 'failed' | 'stale' | 'no_data' | 'running'
  lastRunAt?: string
  lastRunId?: string
  totalTests?: number
  passedTests?: number
  failedTests?: number
  durationMs?: number
  errorMessage?: string
  ageMinutes?: number
  currentlyRunning?: boolean
}

// Maximum age of a test run before it's considered stale (25 hours)
// Smoke tests run daily at 2 AM Central, so allow slightly over 24h for schedule drift
const MAX_AGE_MS = 25 * 60 * 60 * 1000

export const GET = withAuth(async (): Promise<NextResponse<SmokeTestStatusResponse>> => {
  try {
    // Get the most recent COMPLETED test run (not "running")
    const latestCompletedRun = await db
      .select()
      .from(smokeTestRuns)
      .where(ne(smokeTestRuns.status, 'running'))
      .orderBy(desc(smokeTestRuns.startedAt))
      .limit(1)
      .get()

    // Check if there's a currently running test (for informational purposes)
    const runningTest = await db
      .select({ id: smokeTestRuns.id })
      .from(smokeTestRuns)
      .where(ne(smokeTestRuns.status, 'passed'))
      .orderBy(desc(smokeTestRuns.startedAt))
      .limit(1)
      .get()
    const currentlyRunning = runningTest?.id !== latestCompletedRun?.id

    if (!latestCompletedRun) {
      // No completed runs yet - if there's a running test, report that
      if (currentlyRunning) {
        return NextResponse.json(
          {
            status: 'running',
            currentlyRunning: true,
          },
          { status: 503 }
        )
      }
      return NextResponse.json({ status: 'no_data' }, { status: 503 })
    }

    const ageMs = Date.now() - latestCompletedRun.startedAt.getTime()
    const ageMinutes = Math.floor(ageMs / 60000)

    // Check if the run is too old
    if (ageMs > MAX_AGE_MS) {
      return NextResponse.json(
        {
          status: 'stale',
          lastRunAt: latestCompletedRun.startedAt.toISOString(),
          lastRunId: latestCompletedRun.id,
          ageMinutes,
          currentlyRunning,
        },
        { status: 503 }
      )
    }

    // Check if the run passed
    if (latestCompletedRun.status === 'passed') {
      return NextResponse.json({
        status: 'passed',
        lastRunAt: latestCompletedRun.startedAt.toISOString(),
        lastRunId: latestCompletedRun.id,
        totalTests: latestCompletedRun.totalTests ?? undefined,
        passedTests: latestCompletedRun.passedTests ?? undefined,
        failedTests: latestCompletedRun.failedTests ?? undefined,
        durationMs: latestCompletedRun.durationMs ?? undefined,
        ageMinutes,
        currentlyRunning,
      })
    }

    // Run failed or errored
    return NextResponse.json(
      {
        status: 'failed',
        lastRunAt: latestCompletedRun.startedAt.toISOString(),
        lastRunId: latestCompletedRun.id,
        totalTests: latestCompletedRun.totalTests ?? undefined,
        passedTests: latestCompletedRun.passedTests ?? undefined,
        failedTests: latestCompletedRun.failedTests ?? undefined,
        durationMs: latestCompletedRun.durationMs ?? undefined,
        errorMessage: latestCompletedRun.errorMessage ?? undefined,
        ageMinutes,
        currentlyRunning,
      },
      { status: 503 }
    )
  } catch (error) {
    console.error('Error checking smoke test status:', error)
    return NextResponse.json(
      {
        status: 'failed',
        errorMessage: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 503 }
    )
  }
})