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

namespace Handler;

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

class HealthzHandler implements RequestHandlerInterface
{
	public function handle(Request $request): Response
	{
		$status = "ok";
		$errors = [];

		// 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) {
			$status = "degraded";
			$errors["calibre_db"] = "Connection failed: " . $e->getMessage();
		}

		// Test main database (via ORM/Db)
		try {
			Db::pdo()->query("SELECT 1");
		} catch (\PDOException $e) {
			$status = "degraded";
			$errors["main_db"] = "Connection failed: " . $e->getMessage();
		}

		$response = (new Response())
			->withHeader("Content-Type", "application/json")
			->withBody(json_encode([
				"status" => $status,
				"errors" => $errors,
			]));

		if ($status === "degraded") {
			$response = $response->withStatus(503);
		}

		return $response;
	}
}