Skip to content

Commit ef07cce

Browse files
benjamin-elharrarclaude
andcommitted
feat: web UI dashboard, multi-collection, catalog export + bug fixes
Features -------- - Web UI dashboard (FastAPI + Alpine.js + Tailwind) served on port 6547 · Stats cards, sync history table, searchable/filterable concert browser · Item detail modal with full track list · Auto-refreshes every 30 s · REST API: /api/stats /api/syncs /api/items /api/items/{id} /api/catalog/refresh - Multi-collection support: COLLECTION env var now accepts comma-separated values e.g. COLLECTION=aadamjacobs,gratefuldead - Catalog export after every sync: catalog.json + catalog.csv in STATE_DIR · On-demand via GET /api/catalog/refresh Bug fixes --------- - downloader: hash objects now reset when server ignores Range header (HTTP 200 instead of 206) — was producing wrong checksums on resumed downloads - downloader: use os.replace() for atomic .part → final rename (POSIX-safe) - discovery + metadata: replace broad `except Exception` with specific exception types so asyncio.CancelledError propagates correctly on shutdown - database: guard partial connection init — assign self._conn only after schema and migrations succeed; column-name whitelist prevents injection in dynamic UPDATE - database: ALTER TABLE migration adds `collection` column to existing databases - sync: dead skipped_count calculation removed; use DB query result directly - sync: metadata errors now use log.exception() to capture full traceback - sync: webhook POST reuses the pooled httpx client instead of opening a new one - sync: _tag_safe now properly typed and returns bool - tagger: returns bool; checks for empty/missing file before opening - config: directory creation failures now raise RuntimeError with clear message - config: WEB_PORT replaces HEALTH_PORT (HEALTH_PORT still accepted as fallback) - Dockerfile: HEALTHCHECK reads WEB_PORT/HEALTH_PORT from env — no hardcoded port - docker-compose: duplicate HEALTHCHECK block removed (Dockerfile owns it) - health.py: removed — replaced by FastAPI /health endpoint in web.py - main.py: uvicorn + scheduler share one event loop and one DB connection; pending tasks on shutdown catch all exceptions not just CancelledError Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent a602479 commit ef07cce

15 files changed

Lines changed: 1099 additions & 566 deletions

‎Dockerfile‎

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,8 @@ FROM python:3.12-slim AS builder
33

44
WORKDIR /build
55

6-
# Install only what's needed to compile wheels (mutagen is pure Python,
7-
# but httpx needs hpack if http2 is used)
8-
RUN apt-get update && apt-get install -y --no-install-recommends \
9-
gcc \
10-
&& rm -rf /var/lib/apt/lists/*
6+
RUN apt-get update && apt-get install -y --no-install-recommends gcc \
7+
&& rm -rf /var/lib/apt/lists/*
118

129
COPY requirements.txt .
1310
RUN pip install --upgrade pip \
@@ -19,27 +16,28 @@ FROM python:3.12-slim
1916

2017
LABEL org.opencontainers.image.title="archive-mirror" \
2118
org.opencontainers.image.description="Continuous mirror of an Internet Archive collection" \
22-
org.opencontainers.image.source="https://github.com/your-org/archive-mirror"
19+
org.opencontainers.image.source="https://github.com/sdblepas/archive-mirror"
2320

24-
# Create a non-root user for the service
2521
RUN useradd --system --uid 1000 --create-home mirror
2622

2723
WORKDIR /app
2824

29-
# Copy installed packages from builder
3025
COPY --from=builder /install /usr/local
31-
32-
# Copy source
3326
COPY src/ ./src/
3427

35-
# Create data directories owned by the service user
3628
RUN mkdir -p /data/music /data/state \
3729
&& chown -R mirror:mirror /data
3830

3931
USER mirror
4032

41-
HEALTHCHECK --interval=30s --timeout=10s --start-period=15s --retries=3 \
42-
CMD python -c "import urllib.request,sys; r=urllib.request.urlopen('http://localhost:6547/health',timeout=5); sys.exit(0 if r.status==200 else 1)"
33+
# Healthcheck reads HEALTH_PORT / WEB_PORT from the environment so it works
34+
# regardless of which port the operator configures.
35+
HEALTHCHECK --interval=30s --timeout=10s --start-period=20s --retries=3 \
36+
CMD python -c "\
37+
import urllib.request, sys, os; \
38+
port = os.getenv('WEB_PORT', os.getenv('HEALTH_PORT', '6547')); \
39+
r = urllib.request.urlopen(f'http://localhost:{port}/health', timeout=5); \
40+
sys.exit(0 if r.status == 200 else 1)"
4341

4442
EXPOSE 6547
4543

‎docker-compose.yml‎

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,47 +9,54 @@ services:
99
container_name: archive-mirror
1010
restart: unless-stopped
1111

12-
# ── Volumes ──────────────────────────────────────────────────────────
1312
volumes:
1413
- /volume1/Docker/archive-mirror/music:/data/music
1514
- /volume1/Docker/archive-mirror/state:/data/state
1615

17-
# ── Environment ───────────────────────────────────────────────────────
1816
environment:
17+
# ── Collections (comma-separated for multi-collection) ──────────────
1918
COLLECTION: aadamjacobs
19+
20+
# ── Paths ───────────────────────────────────────────────────────────
2021
OUTPUT_DIR: /data/music
2122
STATE_DIR: /data/state
23+
24+
# ── Scheduling ──────────────────────────────────────────────────────
2225
SYNC_INTERVAL: "3600"
26+
27+
# ── Concurrency ─────────────────────────────────────────────────────
2328
CONCURRENCY: "3"
2429
RATE_LIMIT_DELAY: "1.0"
30+
31+
# ── HTTP ────────────────────────────────────────────────────────────
2532
REQUEST_TIMEOUT: "120"
2633
RETRY_COUNT: "5"
34+
35+
# ── Logging ─────────────────────────────────────────────────────────
2736
LOG_LEVEL: INFO
37+
38+
# ── Flags ───────────────────────────────────────────────────────────
2839
DRY_RUN: "false"
2940
CHECKSUM_MANIFEST: "true"
41+
42+
# ── Notifications ───────────────────────────────────────────────────
3043
WEBHOOK_URL: ""
31-
HEALTH_PORT: "6547"
3244

33-
# ── Health endpoint ───────────────────────────────────────────────────
45+
# ── Web UI ──────────────────────────────────────────────────────────
46+
WEB_PORT: "6547"
47+
3448
ports:
3549
- "6547:6547"
3650

37-
healthcheck:
38-
test: ["CMD", "python", "-c",
39-
"import urllib.request,sys; r=urllib.request.urlopen('http://localhost:6547/health',timeout=5); sys.exit(0 if r.status==200 else 1)"]
40-
interval: 30s
41-
timeout: 10s
42-
retries: 3
43-
start_period: 20s
51+
# Healthcheck is defined in the Dockerfile (reads WEB_PORT automatically).
52+
# No duplicate definition here.
4453

45-
# ── Resource limits (tune to your host) ──────────────────────────────
4654
deploy:
4755
resources:
4856
limits:
4957
cpus: "2.0"
5058
memory: 512M
5159

52-
# ── Logging ───────────────────────────────────────────────────────────
5360
logging:
5461
driver: json-file
5562
options:

‎requirements.txt‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1-
# HTTP client (async, sync, streaming)
2-
httpx[http2]>=0.27.0
1+
# HTTP client (async, streaming)
2+
httpx>=0.27.0
3+
4+
# Web UI + REST API
5+
fastapi>=0.111.0
6+
uvicorn[standard]>=0.29.0
37

48
# Async SQLite
59
aiosqlite>=0.20.0
@@ -12,6 +16,3 @@ mutagen>=1.47.0
1216

1317
# Structured JSON logging
1418
structlog>=24.1.0
15-
16-
# Standard library only beyond this point – no additional pinned deps needed
17-
# for retry logic; we implement it ourselves to avoid version conflicts.

‎src/catalog.py‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
"""
2+
Catalog export — generates a JSON + CSV snapshot of the mirrored library.
3+
4+
Outputs:
5+
{state_dir}/catalog.json – full machine-readable catalog
6+
{state_dir}/catalog.csv – flat CSV for spreadsheet / import tools
7+
8+
Called at the end of each sync run.
9+
"""
10+
from __future__ import annotations
11+
12+
import csv
13+
import json
14+
from datetime import datetime, timezone
15+
from pathlib import Path
16+
from typing import Any
17+
18+
import aiofiles
19+
20+
from .config import Config
21+
from .database import Database
22+
from .logger import get_logger
23+
24+
log = get_logger(__name__)
25+
26+
27+
async def export_catalog(config: Config, db: Database) -> dict[str, int]:
28+
"""Build and write catalog files. Returns summary counts."""
29+
log.info("catalog.export_start")
30+
31+
# Fetch all complete items and their tracks
32+
items, total = await db.get_items_paginated(
33+
status="complete", per_page=100_000
34+
)
35+
36+
rows: list[dict[str, Any]] = []
37+
csv_rows: list[dict[str, str]] = []
38+
39+
for item in items:
40+
tracks = await db.get_tracks_for_item(item["identifier"])
41+
track_list = [
42+
{
43+
"ia_filename": t["ia_filename"],
44+
"local_filename": t["local_filename"],
45+
"local_path": t["local_path"],
46+
"title": t["title"],
47+
"track_number": t["track_number"],
48+
"md5": t["md5"],
49+
}
50+
for t in tracks
51+
if t["status"] == "complete"
52+
]
53+
54+
rows.append(
55+
{
56+
"identifier": item["identifier"],
57+
"collection": item["collection"],
58+
"artist": item["artist"],
59+
"date": item["date"],
60+
"venue": item["venue"],
61+
"title": item["title"],
62+
"folder": item["folder_name"],
63+
"track_count": len(track_list),
64+
"tracks": track_list,
65+
}
66+
)
67+
68+
# One CSV row per track
69+
for t in track_list:
70+
csv_rows.append(
71+
{
72+
"identifier": item["identifier"],
73+
"collection": item["collection"] or "",
74+
"artist": item["artist"] or "",
75+
"date": item["date"] or "",
76+
"venue": item["venue"] or "",
77+
"folder": item["folder_name"] or "",
78+
"track_number": str(t["track_number"] or ""),
79+
"title": t["title"] or "",
80+
"local_filename": t["local_filename"] or "",
81+
"local_path": t["local_path"] or "",
82+
"md5": t["md5"] or "",
83+
}
84+
)
85+
86+
catalog = {
87+
"generated_at": datetime.now(timezone.utc).isoformat(),
88+
"collections": config.collections,
89+
"total_items": len(rows),
90+
"total_tracks": len(csv_rows),
91+
"items": rows,
92+
}
93+
94+
# ── Write JSON ────────────────────────────────────────────────────────
95+
async with aiofiles.open(config.catalog_json_path, "w", encoding="utf-8") as f:
96+
await f.write(json.dumps(catalog, indent=2, ensure_ascii=False))
97+
98+
# ── Write CSV ─────────────────────────────────────────────────────────
99+
fieldnames = [
100+
"identifier", "collection", "artist", "date", "venue",
101+
"folder", "track_number", "title", "local_filename",
102+
"local_path", "md5",
103+
]
104+
csv_text_rows = [",".join(fieldnames)]
105+
for row in csv_rows:
106+
csv_text_rows.append(
107+
",".join(
108+
f'"{row[f].replace(chr(34), chr(34)+chr(34))}"'
109+
for f in fieldnames
110+
)
111+
)
112+
async with aiofiles.open(config.catalog_csv_path, "w", encoding="utf-8") as f:
113+
await f.write("\n".join(csv_text_rows) + "\n")
114+
115+
log.info(
116+
"catalog.export_done",
117+
items=len(rows),
118+
tracks=len(csv_rows),
119+
json_path=str(config.catalog_json_path),
120+
csv_path=str(config.catalog_csv_path),
121+
)
122+
123+
return {"items": len(rows), "tracks": len(csv_rows)}

‎src/config.py‎

Lines changed: 37 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
"""
22
Central configuration loaded entirely from environment variables.
3-
All fields have sane defaults so the service works out of the box.
3+
4+
COLLECTION supports comma-separated values for multi-collection mirroring:
5+
COLLECTION=aadamjacobs
6+
COLLECTION=aadamjacobs,gratefuldead,phish
47
"""
58
from __future__ import annotations
69

@@ -13,6 +16,11 @@ def _bool_env(key: str, default: str = "false") -> bool:
1316
return os.getenv(key, default).strip().lower() in ("1", "true", "yes")
1417

1518

19+
def _parse_collections() -> list[str]:
20+
raw = os.getenv("COLLECTION", "aadamjacobs")
21+
return [c.strip() for c in raw.split(",") if c.strip()]
22+
23+
1624
@dataclass
1725
class Config:
1826
# ── Paths ──────────────────────────────────────────────────────────────
@@ -23,13 +31,10 @@ class Config:
2331
default_factory=lambda: Path(os.getenv("STATE_DIR", "/data/state"))
2432
)
2533

26-
# ── Collection ─────────────────────────────────────────────────────────
27-
collection: str = field(
28-
default_factory=lambda: os.getenv("COLLECTION", "aadamjacobs")
29-
)
34+
# ── Collections (comma-separated) ─────────────────────────────────────
35+
collections: list[str] = field(default_factory=_parse_collections)
3036

3137
# ── Scheduling ─────────────────────────────────────────────────────────
32-
# Seconds between full syncs. 0 = run once then exit.
3338
sync_interval: int = field(
3439
default_factory=lambda: int(os.getenv("SYNC_INTERVAL", "3600"))
3540
)
@@ -38,12 +43,11 @@ class Config:
3843
max_workers: int = field(
3944
default_factory=lambda: int(os.getenv("CONCURRENCY", "3"))
4045
)
41-
# Minimum seconds to wait between HTTP requests (per worker)
4246
rate_limit_delay: float = field(
4347
default_factory=lambda: float(os.getenv("RATE_LIMIT_DELAY", "1.0"))
4448
)
4549

46-
# ── HTTP behaviour ──────────────────────────────────────────────────────
50+
# ── HTTP ───────────────────────────────────────────────────────────────
4751
request_timeout: float = field(
4852
default_factory=lambda: float(os.getenv("REQUEST_TIMEOUT", "120"))
4953
)
@@ -62,25 +66,41 @@ class Config:
6266
default_factory=lambda: _bool_env("CHECKSUM_MANIFEST", "true")
6367
)
6468

65-
# ── Optional notifications ─────────────────────────────────────────────
69+
# ── Notifications ──────────────────────────────────────────────────────
6670
webhook_url: str = field(default_factory=lambda: os.getenv("WEBHOOK_URL", ""))
6771

68-
# ── Health endpoint ────────────────────────────────────────────────────
69-
health_port: int = field(
70-
default_factory=lambda: int(os.getenv("HEALTH_PORT", "8080"))
72+
# ── Web UI / Health port ───────────────────────────────────────────────
73+
web_port: int = field(
74+
default_factory=lambda: int(
75+
os.getenv("WEB_PORT", os.getenv("HEALTH_PORT", "6547"))
76+
)
7177
)
7278

7379
def __post_init__(self) -> None:
7480
self.output_dir = Path(self.output_dir)
7581
self.state_dir = Path(self.state_dir)
76-
self.output_dir.mkdir(parents=True, exist_ok=True)
77-
self.state_dir.mkdir(parents=True, exist_ok=True)
82+
try:
83+
self.output_dir.mkdir(parents=True, exist_ok=True)
84+
self.state_dir.mkdir(parents=True, exist_ok=True)
85+
except OSError as exc:
86+
raise RuntimeError(
87+
f"Cannot create required directories: {exc}"
88+
) from exc
89+
90+
# ── Convenience ───────────────────────────────────────────────────────
91+
@property
92+
def collection(self) -> str:
93+
"""Primary collection (first in list). Used in legacy single-collection contexts."""
94+
return self.collections[0] if self.collections else "aadamjacobs"
7895

79-
# ── Derived paths ──────────────────────────────────────────────────────
8096
@property
8197
def db_path(self) -> Path:
8298
return self.state_dir / "mirror.db"
8399

84100
@property
85-
def health_file(self) -> Path:
86-
return self.state_dir / ".health"
101+
def catalog_json_path(self) -> Path:
102+
return self.state_dir / "catalog.json"
103+
104+
@property
105+
def catalog_csv_path(self) -> Path:
106+
return self.state_dir / "catalog.csv"

0 commit comments

Comments
 (0)