health.ts 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import { constants } from 'node:fs'
  2. import { access } from 'node:fs/promises'
  3. import path from 'node:path'
  4. import { backgroundJobsState } from '@/lib/background-jobs'
  5. import { db } from '@/lib/db'
  6. import { uploadsRoot } from '@/lib/upload-root'
  7. /**
  8. * What the container's health check asks (HEALTHCHECK in the Dockerfile):
  9. * can this server do its job, not only answer. Each check names what failed,
  10. * so `docker logs` and an uptime monitor say why, not just that.
  11. */
  12. /** Under Docker's own 5 s timeout, so a slow database is reported as such. */
  13. export const DATABASE_TIMEOUT_MS = 3000
  14. /** Three missed beats of the every-minute heartbeat. */
  15. export const JOBS_STALE_MS = 3 * 60 * 1000
  16. export type HealthChecks = {
  17. database: 'ok' | 'timeout' | 'unreachable'
  18. storage: 'ok' | 'not_writable'
  19. jobs: 'ok' | 'disabled' | 'not_started' | 'stalled'
  20. }
  21. export type HealthReport = { healthy: boolean; checks: HealthChecks }
  22. /**
  23. * The query a probe started and nobody has heard back from. A probe that gives
  24. * up after three seconds cannot cancel it, and it keeps one of the app's ten
  25. * pooled connections until the database answers. The next probe waits on that
  26. * same query instead of taking another connection, so a database that stops
  27. * answering costs the health check one connection however long it lasts.
  28. */
  29. let pendingQuery: Promise<unknown> | undefined
  30. async function checkDatabase(): Promise<HealthChecks['database']> {
  31. if (!pendingQuery) {
  32. const query: Promise<unknown> = db.$queryRaw`SELECT 1`.finally(() => {
  33. if (pendingQuery === query) pendingQuery = undefined
  34. })
  35. pendingQuery = query
  36. }
  37. const query = pendingQuery
  38. let timer: ReturnType<typeof setTimeout> | undefined
  39. const timeout = new Promise<'timeout'>((resolve) => {
  40. timer = setTimeout(() => resolve('timeout'), DATABASE_TIMEOUT_MS)
  41. })
  42. try {
  43. return await Promise.race([query.then(() => 'ok' as const), timeout])
  44. } catch {
  45. return 'unreachable'
  46. } finally {
  47. clearTimeout(timer)
  48. }
  49. }
  50. /**
  51. * The uploads folder is made on the first upload, so until it exists the
  52. * nearest folder above it has to take it. Making a folder in a folder takes
  53. * both write and search (execute) permission on it. A volume owned by the
  54. * wrong user is the usual reason this fails: the app starts and every photo is
  55. * refused.
  56. */
  57. async function checkStorage(): Promise<HealthChecks['storage']> {
  58. let dir = uploadsRoot()
  59. for (;;) {
  60. try {
  61. await access(dir, constants.W_OK | constants.X_OK)
  62. return 'ok'
  63. } catch (error) {
  64. const parent = path.dirname(dir)
  65. if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || parent === dir) {
  66. return 'not_writable'
  67. }
  68. dir = parent
  69. }
  70. }
  71. }
  72. /** Reminders, scheduled messages and backups all run on these timers. */
  73. function checkJobs(now: number): HealthChecks['jobs'] {
  74. const state = backgroundJobsState()
  75. if (!state) return 'not_started'
  76. if (state.disabled) return 'disabled'
  77. return now - state.lastBeatAt <= JOBS_STALE_MS ? 'ok' : 'stalled'
  78. }
  79. let lastHealthy: boolean | undefined
  80. export async function checkHealth(now = Date.now()): Promise<HealthReport> {
  81. const [database, storage] = await Promise.all([checkDatabase(), checkStorage()])
  82. const jobs = checkJobs(now)
  83. const checks: HealthChecks = { database, storage, jobs }
  84. const healthy = database === 'ok' && storage === 'ok' && (jobs === 'ok' || jobs === 'disabled')
  85. // One line when the answer changes, not one per probe, so an outage leaves
  86. // its start and end in the log without filling it.
  87. if (healthy !== lastHealthy) {
  88. const failing = Object.entries(checks)
  89. .filter(([, value]) => value !== 'ok' && value !== 'disabled')
  90. .map(([name, value]) => `${name}=${value}`)
  91. .join(' ')
  92. if (!healthy) console.error(`[health] failing: ${failing}`)
  93. else if (lastHealthy === false) console.warn('[health] passing again')
  94. lastHealthy = healthy
  95. }
  96. return { healthy, checks }
  97. }