diff --git a/claude_code_log/api.py b/claude_code_log/api.py index 6db8ca60..3675bc4b 100644 --- a/claude_code_log/api.py +++ b/claude_code_log/api.py @@ -14,10 +14,12 @@ import sqlite3 import threading +from contextlib import contextmanager +from collections.abc import Iterator from pathlib import Path from typing import Any, Callable, Optional, Sequence -from .cache import get_library_version +from .cache import get_library_version, is_corrupt_database_error from .search import ( DEFAULT_SEARCH_FIELDS, SEARCH_FIELDS, @@ -45,6 +47,20 @@ def _int_param(params: dict[str, str], name: str, default: int) -> int: raise ValueError(f"{name} must be an integer, got {raw!r}") from exc +@contextmanager +def _report_unreadable_cache() -> Iterator[None]: + """Give archive readers the recovery step when a SQLite read detects corruption.""" + try: + yield + except sqlite3.DatabaseError as exc: + if not is_corrupt_database_error(exc): + raise + raise ValueError( + "The cache database is unreadable. Restart the server without " + "--no-convert to rebuild the cache." + ) from exc + + class SearchApi: """Route handlers over one cache database.""" @@ -87,6 +103,7 @@ def ping(self, _params: dict[str, str]) -> dict[str, Any]: "index": status.as_dict(), } + @_report_unreadable_cache() def projects(self, _params: dict[str, str]) -> dict[str, Any]: """Project list for the filter dropdown, newest activity first.""" rows = self.connection().execute( @@ -118,6 +135,7 @@ def _resolve_project_id(self, slug: str) -> Optional[int]: return int(row[0]) return None + @_report_unreadable_cache() def search(self, params: dict[str, str]) -> dict[str, Any]: query = params.get("q", "").strip() if not query: diff --git a/claude_code_log/html/templates/archive_search.html b/claude_code_log/html/templates/archive_search.html index 3a71116e..0becbe9a 100644 --- a/claude_code_log/html/templates/archive_search.html +++ b/claude_code_log/html/templates/archive_search.html @@ -651,7 +651,9 @@

Search all transcripts

if (!index.ready) { statusEl.textContent = 'Search index unavailable: ' + (index.reason || 'not built') + - '. Restart the server to build it.'; + (index.available === false + ? '.' + : '. Restart the server without --no-convert to build the index.'); } else { // `--index-fields` can leave a group out of the index // entirely, and no amount of checking its box will make diff --git a/test/__snapshots__/test_snapshot_html.ambr b/test/__snapshots__/test_snapshot_html.ambr index 3030be18..9e826dd5 100644 --- a/test/__snapshots__/test_snapshot_html.ambr +++ b/test/__snapshots__/test_snapshot_html.ambr @@ -26699,7 +26699,9 @@ if (!index.ready) { statusEl.textContent = 'Search index unavailable: ' + (index.reason || 'not built') + - '. Restart the server to build it.'; + (index.available === false + ? '.' + : '. Restart the server without --no-convert to build the index.'); } else { // `--index-fields` can leave a group out of the index // entirely, and no amount of checking its box will make diff --git a/test/test_archive_search_page.py b/test/test_archive_search_page.py index 035ac3d7..02ebabf0 100644 --- a/test/test_archive_search_page.py +++ b/test/test_archive_search_page.py @@ -162,6 +162,28 @@ def test_search_page_shows_setup_instructions_without_a_server( assert page.is_hidden("#app") assert "claude-code-log serve" in page.inner_text("#setup") + @pytest.mark.parametrize( + ("available", "reason"), + [(True, "index not built"), (False, "SQLite was built without FTS5")], + ) + def test_rebuild_hint_requires_fts5( + self, page: Any, generated_archive: Path, available: bool, reason: str + ) -> None: + page.route( + "**/api/ping", + lambda route: route.fulfill( + json={ + "index": {"ready": False, "available": available, "reason": reason} + } + ), + ) + with self._serve(generated_archive) as server: + page.goto(f"{server.url}/search.html") + _wait_ready(page) + status = page.inner_text("#status") + assert reason in status + assert ("--no-convert" in status) == available + def test_search_finds_results_and_updates_the_url( self, page: Any, generated_archive: Path ) -> None: diff --git a/test/test_server.py b/test/test_server.py index 62b10c59..355376a1 100644 --- a/test/test_server.py +++ b/test/test_server.py @@ -8,6 +8,7 @@ from __future__ import annotations import http.server +import json import os import socket import time @@ -19,6 +20,7 @@ import pytest import claude_code_log.server as server_module +from claude_code_log.api import SearchApi from claude_code_log.server import REVISION_HEADER, ArchiveServer @@ -89,8 +91,6 @@ def test_query_string_on_a_static_path_is_ignored(server: ArchiveServer) -> None def test_api_ping(server: ArchiveServer) -> None: - import json - status, body, headers = _get(f"{server.url}/api/ping") assert status == 200 payload: dict[str, Any] = json.loads(body) @@ -99,11 +99,24 @@ def test_api_ping(server: ArchiveServer) -> None: assert headers.get("Cache-Control") == "no-store" +@pytest.mark.parametrize("endpoint", ["/api/search?q=hello", "/api/projects"]) +def test_archive_queries_explain_how_to_rebuild_a_corrupt_cache( + archive: Path, endpoint: str +) -> None: + db = archive / "cache.db" + db.write_bytes(b"not a SQLite database" * 100) + with ArchiveServer(archive, api_routes=SearchApi(db).routes(), port=0) as srv: + status, body, _ = _get(srv.url + endpoint) + + assert status == 400 + message = json.loads(body)["error"] + assert "cache database is unreadable" in message + assert "--no-convert" in message + + def test_unknown_api_endpoint_is_404_json_not_a_file_lookup( server: ArchiveServer, ) -> None: - import json - status, body, _ = _get(f"{server.url}/api/nope") assert status == 404 assert "error" in json.loads(body) @@ -114,8 +127,6 @@ def test_api_prefix_is_reserved_from_the_filesystem(archive: Path) -> None: api_dir = archive / "api" api_dir.mkdir() (api_dir / "ping").write_text("this is a file, not the endpoint") - import json - with ArchiveServer(archive, port=0) as srv: status, body, _ = _get(f"{srv.url}/api/ping") assert status == 200