about summary refs log tree commit diff stats
path: root/classes/Handler/HealthzHandler.php
blob: f12649b7bd33e1726663e4f9884cb5de883cbaa7 (plain) (blame)
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
<?php

namespace Handler;

use Config;
use Db;
use PDO;
use Request;
use RequestHandlerInterface;
use Response;

/**
 * Public k8s healthcheck endpoint. Intentionally does NOT implement
 * AuthRequired. Because it is unauthenticated, it must not leak any
 * internals (DSNs, paths, driver errors) — failure details go to the
 * PHP error log, the HTTP response only carries 200/503.
 */
class HealthzHandler implements RequestHandlerInterface
{
    public function handle(Request $request): Response
    {
        $healthy = true;

        // Test Calibre SQLite database
        try {
            $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB));
            $caldb->query("SELECT 1 FROM books LIMIT 1");
        } catch (\PDOException $e) {
            $healthy = false;
            error_log("healthz: calibre db check failed: " . $e->getMessage());
        }

        // Test main database (via ORM/Db)
        try {
            Db::pdo()->query("SELECT 1");
        } catch (\PDOException $e) {
            $healthy = false;
            error_log("healthz: main db check failed: " . $e->getMessage());
        }

        $response = (new Response())
            ->withHeader("Content-Type", "application/json")
            ->withBody(json_encode(["status" => $healthy ? "ok" : "error"]));

        if (!$healthy) {
            $response = $response->withStatus(503);
        }

        return $response;
    }
}