about summary refs log tree commit diff stats
path: root/classes/Handler/HealthzHandler.php
diff options
context:
space:
mode:
Diffstat (limited to 'classes/Handler/HealthzHandler.php')
-rw-r--r--classes/Handler/HealthzHandler.php49
1 files changed, 49 insertions, 0 deletions
diff --git a/classes/Handler/HealthzHandler.php b/classes/Handler/HealthzHandler.php
new file mode 100644
index 0000000..722422c
--- /dev/null
+++ b/classes/Handler/HealthzHandler.php
@@ -0,0 +1,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;
+    }
+}