Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion claude_code_log/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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."""

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 3 additions & 1 deletion claude_code_log/html/templates/archive_search.html
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,9 @@ <h1>Search all transcripts</h1>
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
Expand Down
4 changes: 3 additions & 1 deletion test/__snapshots__/test_snapshot_html.ambr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 22 additions & 0 deletions test/test_archive_search_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
23 changes: 17 additions & 6 deletions test/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from __future__ import annotations

import http.server
import json
import os
import socket
import time
Expand All @@ -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


Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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
Expand Down
Loading