diff --git a/static/cx-core/cx_core/adapters/calibre.py b/static/cx-core/cx_core/adapters/calibre.py index 42f256443..c8cf2c5e8 100644 --- a/static/cx-core/cx_core/adapters/calibre.py +++ b/static/cx-core/cx_core/adapters/calibre.py @@ -162,6 +162,46 @@ def _upload_files(self, files: List[str]) -> int: done += 1 return done + def delete(self, local_ref: str) -> dict: + # calibredb is absent, so delete through Calibre-Web's own remove (POST /delete/{id}), + # which drops the book row plus its FK rows and files. Its delete keys on the integer + # library id, so resolve it from the uuid first. A book is self-contained (no shared + # files), so freedBytes is the item's KNOWN size (already summed from data, like Kiwix + # uses the file size): no need for a racy free-space delta. + item = self.get(local_ref) + book_id = self._book_id(local_ref) + if item is None or book_id is None: + return {"ok": False, "reason": "item not found"} + if not self._remove_book(book_id): + return {"ok": False, "reason": "calibre delete failed"} + return {"ok": True, "app": "calibre", "localRef": local_ref, "freedBytes": item.bytes} + + def _book_id(self, uuid: str) -> Optional[int]: + """The integer books.id for a book uuid, from metadata.db. None if absent. Calibre-Web + delete keys on this id, not the uuid.""" + if not uuid or not os.path.exists(self._db): + return None + try: + con = sqlite3.connect(f"file:{self._db}?mode=ro", uri=True) + except sqlite3.Error: + return None + try: + row = con.execute("SELECT id FROM books WHERE uuid = ?", (uuid,)).fetchone() + except sqlite3.Error: + return None + finally: + con.close() + return int(row[0]) if row and row[0] is not None else None + + def _remove_book(self, book_id: int) -> bool: + """Log into Calibre-Web and remove one book. A seam, like _upload_files, so a test need + not run a live Calibre-Web. Returns True on success.""" + user, password = resolve_calibre_credentials(self._credentials_file) + client = CalibreWebClient(self._url, user, password) + if not client.login(): + return False + return client.remove(book_id) + def _book_path(self, uuid: str) -> Optional[str]: """The relative on-disk directory for a book uuid, from metadata.db. None if absent.""" if not uuid or not os.path.exists(self._db): diff --git a/static/cx-core/cx_core/adapters/calibreweb.py b/static/cx-core/cx_core/adapters/calibreweb.py index 732c64ab7..5735efaac 100644 --- a/static/cx-core/cx_core/adapters/calibreweb.py +++ b/static/cx-core/cx_core/adapters/calibreweb.py @@ -157,3 +157,23 @@ def upload(self, file_path: str, filename: str) -> bool: return 200 <= exc.code < 400 finally: body.close() + + def remove(self, book_id: int) -> bool: + """POST /delete/{id} to remove a book (calibredb is absent), exactly as dash-node does + (sockets/books.query.ts removeBook): a logged-in session + CSRF token. ``book_id`` is + the Calibre-Web library id (integer), not the book uuid. Returns True on a 2xx/redirect. + Deleting the row also drops its FK rows (data / authors / identifiers) and its files, + so Calibre-Web stays the one owner of its library.""" + form = urllib.parse.urlencode({"csrf_token": self._csrf}).encode("utf-8") + req = urllib.request.Request( + f"{self._base}/delete/{book_id}", data=form, + headers={ + "Content-Type": "application/x-www-form-urlencoded", + "Referer": f"{self._base}/", + }, + ) + try: + with self._opener.open(req, timeout=self._timeout) as resp: + return 200 <= resp.status < 400 + except urllib.error.HTTPError as exc: + return 200 <= exc.code < 400 diff --git a/static/cx-core/cx_core/adapters/kiwix.py b/static/cx-core/cx_core/adapters/kiwix.py index 626f98c57..1586fe6a0 100644 --- a/static/cx-core/cx_core/adapters/kiwix.py +++ b/static/cx-core/cx_core/adapters/kiwix.py @@ -208,6 +208,26 @@ def import_item(self, entry: dict, payload_path: str) -> dict: self._reindex() return {"ok": True, "app": "kiwix", "localRef": local_ref, "bytes": os.path.getsize(dest)} + def delete(self, local_ref: str) -> dict: + # A ZIM is self-contained, so the file IS the unit: remove it, then re-run the indexer + # to drop its library.xml entry. freedBytes is the file size exactly (no shared bytes). + # Same containment guard as get(), so a traversal ref never reaches the filesystem. + if not is_safe_local_ref(local_ref) or not local_ref.lower().endswith(".zim"): + return {"ok": False, "reason": "invalid localRef"} + path = os.path.join(self._dir, local_ref) + if not os.path.isfile(path): + return {"ok": False, "reason": "item not found"} + try: + freed = os.path.getsize(path) + except OSError: + freed = 0 + try: + os.remove(path) + except OSError as exc: + return {"ok": False, "reason": f"delete failed: {exc}"} + self._reindex() + return {"ok": True, "app": "kiwix", "localRef": local_ref, "freedBytes": freed} + def _reindex(self) -> None: """Rebuild the Kiwix library index. A seam, so a test need not run the real indexer. NOTE: this runs outside the dash-node jobs engine, so a concurrent kiwix download + diff --git a/static/cx-core/cx_core/adapters/kolibri.py b/static/cx-core/cx_core/adapters/kolibri.py index 9725b23ab..2b806758e 100644 --- a/static/cx-core/cx_core/adapters/kolibri.py +++ b/static/cx-core/cx_core/adapters/kolibri.py @@ -21,7 +21,7 @@ import tempfile from typing import List, Optional -from ..export import has_room, tar_stream +from ..export import free_bytes, has_room, tar_stream from ..importing import safe_extract_tar, single_child_dir from ..model import ( ABSENT, @@ -61,6 +61,20 @@ def import_commands(channel_id: str, source: str, kolibri_bin: str) -> List[List ] +def delete_command(channel_id: str, kolibri_bin: str) -> List[str]: + """The Kolibri management command that deletes a channel and its unused content files. + Pure (builds argv only). This is Kolibri's OWN delete: it does the shared-file refcounting, + so it frees only files no other channel still uses (a direct rm would corrupt other + channels, since the content store is content-addressed and shared). + + dash-node runs the equivalent delete as the async Kolibri REST TASK + (kolibri.core.content.tasks.deletechannel) because it is a long-lived Node service that + must not block. cx-core reaches Kolibri through the CLI (as its export / import do), where + the command is synchronous: we wait for it inherently and then report the reclaimed bytes. + """ + return [kolibri_bin, "manage", "deletechannel", channel_id] + + def _to_int(*values) -> Optional[int]: """First value that parses as an int, else None. The version may arrive as an int or a string over JSON, and the build mirrors it.""" @@ -244,3 +258,35 @@ def _stage_import(self, channel_id: str, source: str) -> bool: if result.returncode != 0: return False return True + + def delete(self, local_ref: str) -> dict: + # Delegate to Kolibri's own delete (it refcounts shared files). Measure the reclaim as a + # free-space delta around the CLI call: the filesystem is the one source for bytes + # actually freed, so we never re-derive the refcount here (ADR-5343 guard). + # freedBytes is APPROXIMATE: the delta reads the WHOLE content volume, and the front + # serializes only cx-core's OWN deletes, so a concurrent box process (a download, log + # writes) can skew it. totalBytes / freeBytes from GET /v1/storage stay authoritative. + # NOT yet confirmed on-device: that `kolibri manage deletechannel` is synchronous and + # removes the content FILES (not just metadata). If it is async, freedBytes reads ~0 and + # the channel may still be deleting after this returns: verify on the box, and if needed + # swap _delete_channel to also run `deletecontent` or to the REST task dash-node uses. + if not _CHANNEL_ID_RE.match(local_ref or ""): + return {"ok": False, "reason": "invalid channel id"} + if not self._query(local_ref): + return {"ok": False, "reason": "item not found"} + before = free_bytes(self._home) + if not self._delete_channel(local_ref): + return {"ok": False, "reason": "kolibri delete failed"} + after = free_bytes(self._home) + freed = max(0, after - before) if before is not None and after is not None else None + return {"ok": True, "app": "kolibri", "localRef": local_ref, "freedBytes": freed} + + def _delete_channel(self, channel_id: str) -> bool: + """Run the Kolibri delete CLI (synchronous). A seam, like _stage_export / _stage_import, + so a test need not run a live Kolibri. Returns True on success.""" + env = dict(os.environ, KOLIBRI_HOME=self._home) + result = subprocess.run( + delete_command(channel_id, self._bin), + env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, + ) + return result.returncode == 0 diff --git a/static/cx-core/cx_core/config.py b/static/cx-core/cx_core/config.py index c4bb5f05a..4a26107fb 100644 --- a/static/cx-core/cx_core/config.py +++ b/static/cx-core/cx_core/config.py @@ -23,6 +23,9 @@ def _parse_port(raw: str) -> int: class Config: host: str = "127.0.0.1" # localhost only, like dash-node; the front reaches it in-box port: int = DEFAULT_PORT + # The content volume: the disk the storage summary measures (GET /v1/storage). All app + # content (zims, kolibri, calibre) lives under it, so one disk_usage read is the box total. + content_dir: str = "/library" zims_dir: str = "/library/zims/content/" kiwix_indexer: str = "/usr/bin/iiab-make-kiwix-lib" kolibri_db: str = "/library/kolibri/db.sqlite3" @@ -40,6 +43,7 @@ def from_env() -> "Config": return Config( host=os.environ.get("CX_HOST", "127.0.0.1"), port=_parse_port(os.environ.get("CX_PORT", str(DEFAULT_PORT))), + content_dir=os.environ.get("CX_CONTENT_DIR", "/library"), zims_dir=os.environ.get("CX_ZIMS_DIR", "/library/zims/content/"), kiwix_indexer=os.environ.get("CX_KIWIX_INDEXER", "/usr/bin/iiab-make-kiwix-lib"), kolibri_db=os.environ.get("CX_KOLIBRI_DB", "/library/kolibri/db.sqlite3"), diff --git a/static/cx-core/cx_core/export.py b/static/cx-core/cx_core/export.py index 67afaf9be..821bd15cf 100644 --- a/static/cx-core/cx_core/export.py +++ b/static/cx-core/cx_core/export.py @@ -31,6 +31,26 @@ def has_room(path: str, needed_bytes: int) -> bool: return free >= int(needed_bytes * 1.05) +def disk_total_free(path: str) -> Tuple[int, int]: + """(total, free) bytes of the volume holding path, or (0, 0) when it is unmeasurable. + Used by the storage summary (GET /v1/storage).""" + try: + usage = shutil.disk_usage(path) + except OSError: + return 0, 0 + return usage.total, usage.free + + +def free_bytes(path: str) -> Optional[int]: + """Free bytes of the volume holding path, or None when it is unmeasurable. Used to + measure delete reclaim as a free-space delta, so shared-file refcounting (Kolibri) is + reflected honestly: the filesystem is the single source for space actually freed.""" + try: + return shutil.disk_usage(path).free + except OSError: + return None + + def file_stream(path: str, chunk: int = CHUNK) -> Iterator[bytes]: """Yield a file's bytes in chunks. Opens lazily (on first iteration), read-only.""" with open(path, "rb") as f: diff --git a/static/cx-core/cx_core/ports.py b/static/cx-core/cx_core/ports.py index fd48bd1a1..e1c664530 100644 --- a/static/cx-core/cx_core/ports.py +++ b/static/cx-core/cx_core/ports.py @@ -3,10 +3,9 @@ One adapter owns "how THIS app identifies, stores, exports, imports and deletes its content". The core and the manifest stay app-agnostic; a new app = a new adapter. -This slice is the READ side only, so the port declares the read methods. The full -port in the ADR also has check / export / importItem / delete; those arrive with the -later pillars and are added here then. Where an app has an authoritative mechanism, -the adapter DELEGATES to it rather than re-deriving: one source of truth. +The port now carries the full lifecycle: read, check, export, importItem and delete. +Where an app has an authoritative mechanism, the adapter DELEGATES to it rather than +re-deriving: one source of truth. """ from __future__ import annotations @@ -68,6 +67,16 @@ def check(self, dedup: dict) -> str: def import_item(self, entry: dict, payload_path: str) -> dict: """Ingest one already-local item archive into the app index, delegating to the app's own import. Idempotent: a re-import must not double-count or corrupt. ``payload_path`` - is a box-visible local file the front placed. Default: not supported. - (The full ADR port also has delete; it arrives with its own slice.)""" + is a box-visible local file the front placed. Default: not supported.""" return {"ok": False, "reason": "import not supported"} + + def delete(self, local_ref: str) -> dict: + """Remove one item to reclaim space, delegating to the app's own delete (never driving + the app DB + files directly): the app owns its storage invariants and the next list() + reflects the removal, so there is no separate state to track. Returns + {ok: True, freedBytes: int, ...} on success, or {ok: False, reason} on failure. + ``freedBytes`` is what the app ACTUALLY reclaimed, not the item's nominal size (a + Kolibri channel shares files, so only non-shared bytes are freed). The front confirms + the destructive action with the user first; the core only executes. Default: not + supported.""" + return {"ok": False, "reason": "delete not supported"} diff --git a/static/cx-core/cx_core/registry.py b/static/cx-core/cx_core/registry.py index 90d8b18da..500467b8d 100644 --- a/static/cx-core/cx_core/registry.py +++ b/static/cx-core/cx_core/registry.py @@ -23,11 +23,16 @@ class Registry: - def __init__(self, adapters: List[ContentAdapter], import_root: str = "/library/.cx-staging"): + def __init__( + self, adapters: List[ContentAdapter], import_root: str = "/library/.cx-staging", + content_volume: str = "/library", + ): self._by_app: Dict[str, ContentAdapter] = {a.app: a for a in adapters} # The only directory an import payload may live in: the core refuses a payloadPath # outside it (containment). The front places the payload here. self.import_root = import_root + # The disk the storage summary measures (GET /v1/storage). + self.content_volume = content_volume @staticmethod def load(config: Config) -> "Registry": @@ -36,7 +41,8 @@ def load(config: Config) -> "Registry": KolibriAdapter(config.kolibri_db, config.kolibri_bin, config.staging_dir), CalibreAdapter(config.calibre_db, config.calibre_url, config.credentials_file, config.staging_dir), ] - return Registry([a for a in candidates if a.is_installed()], config.staging_dir) + return Registry( + [a for a in candidates if a.is_installed()], config.staging_dir, config.content_dir) def apps(self) -> List[str]: return sorted(self._by_app.keys()) diff --git a/static/cx-core/cx_core/router.py b/static/cx-core/cx_core/router.py index ec66a82bd..d7592cf70 100644 --- a/static/cx-core/cx_core/router.py +++ b/static/cx-core/cx_core/router.py @@ -10,7 +10,7 @@ from typing import Any, List, Optional, Tuple from urllib.parse import unquote -from .export import has_room +from .export import disk_total_free, has_room from .importing import is_within_dir from .registry import Registry @@ -114,6 +114,41 @@ def _import_item(registry: Registry, body: Any) -> Response: return (200, result) if result.get("ok") else (422, result) +def _delete_item(registry: Registry, app: str, local_ref: str) -> Response: + """Delete one item, delegating to the app's own delete. 404 when the item is absent, so a + repeated delete is idempotent-safe. The destructive confirm is the front's (D1c); the core + only executes.""" + if not registry.has(app): + return 404, {"error": f"unknown app: {app}"} + adapter = registry.get(app) + if adapter.get(local_ref) is None: + return 404, {"error": "item not found"} + result = adapter.delete(local_ref) + return (200, result) if result.get("ok") else (422, result) + + +def _storage(registry: Registry) -> Response: + """Box storage summary: the content volume's total / free disk, plus how much of it the + loaded adapters account for (per app and in total). totalBytes / freeBytes come from the + filesystem and are authoritative; usedByContentBytes (and perApp) is an ESTIMATE: it sums + per-app item bytes, so a Kolibri file shared across channels is counted once per channel. + The PHONE's own free disk is app-side (StatFs), not here.""" + total, free = disk_total_free(registry.content_volume) + per_app: List[dict] = [] + used = 0 + for adapter in registry.adapters(): + app_bytes = sum(item.bytes for item in adapter.list()) + per_app.append({"app": adapter.app, "bytes": app_bytes}) + used += app_bytes + return 200, { + "volume": registry.content_volume, + "totalBytes": total, + "freeBytes": free, + "usedByContentBytes": used, + "perApp": per_app, + } + + def dispatch(registry: Registry, method: str, path: str, query: dict, body: Any = None) -> Response: """Route one request. ``query`` is a dict of first values; ``body`` is the parsed JSON for a POST.""" @@ -135,6 +170,12 @@ def dispatch(registry: Registry, method: str, path: str, query: dict, body: Any return _import_item(registry, body) return 404, {"error": "not found"} + if method == "DELETE": + # DELETE /v1/content/{app}/{localRef} : reclaim space by removing one item. + if len(segments) == 4 and segments[0] == "v1" and segments[1] == "content": + return _delete_item(registry, segments[2], segments[3]) + return 405, {"error": "method not allowed"} + if method != "GET": return 405, {"error": "method not allowed"} @@ -142,6 +183,10 @@ def dispatch(registry: Registry, method: str, path: str, query: dict, body: Any if segments == ["v1", "apps"]: return 200, {"apps": registry.apps()} + # GET /v1/storage : box content-volume disk summary + per-app content totals. + if segments == ["v1", "storage"]: + return _storage(registry) + # GET /v1/content[?app=] : everything this box has, optionally filtered by app. if segments == ["v1", "content"]: return _content_rows(registry, query.get("app")) diff --git a/static/cx-core/cx_core/server.py b/static/cx-core/cx_core/server.py index d664c2a53..9c9dc7b82 100644 --- a/static/cx-core/cx_core/server.py +++ b/static/cx-core/cx_core/server.py @@ -49,6 +49,12 @@ def do_POST(self) -> None: # noqa: N802 (http.server naming) status, payload = dispatch(registry, "POST", parts.path, {}, body) self._send(status, payload) + def do_DELETE(self) -> None: # noqa: N802 (http.server naming) + parts = urlsplit(self.path) + query = {k: v[0] for k, v in parse_qs(parts.query).items()} + status, payload = dispatch(registry, "DELETE", parts.path, query) + self._send(status, payload) + def _read_json_body(self): try: length = int(self.headers.get("Content-Length", 0)) diff --git a/static/cx-core/tests/test_calibre.py b/static/cx-core/tests/test_calibre.py index 1a5c4b8d2..561fcd03b 100644 --- a/static/cx-core/tests/test_calibre.py +++ b/static/cx-core/tests/test_calibre.py @@ -223,5 +223,55 @@ def test_import_rejects_bad_archive(self): self.assertFalse(result["ok"]) +class _DeleteStubCalibre(CalibreAdapter): + """Overrides the Calibre-Web seam so delete delegation is testable without a live service.""" + + def __init__(self, *args, succeed=True, **kwargs): + super().__init__(*args, **kwargs) + self._succeed = succeed + + def _remove_book(self, book_id): + self.removed = book_id + return self._succeed + + +class CalibreBookIdTest(unittest.TestCase): + def test_resolves_integer_id_from_uuid(self): + with tempfile.TemporaryDirectory() as lib: + db = os.path.join(lib, "metadata.db") + _make_db(db) + adapter = CalibreAdapter(db) + self.assertEqual(adapter._book_id("u-1"), 1) + self.assertIsNone(adapter._book_id("nope")) + + +class CalibreDeleteTest(unittest.TestCase): + def test_delete_delegates_to_calibreweb_by_integer_id(self): + with tempfile.TemporaryDirectory() as lib: + db = os.path.join(lib, "metadata.db") + _make_db(db) + adapter = _DeleteStubCalibre(db) + result = adapter.delete("u-1") + self.assertTrue(result["ok"]) + self.assertEqual(adapter.removed, 1) # the integer library id, not the uuid + # A book is self-contained, so freedBytes is its known size (EPUB 1000 + PDF 2000). + self.assertEqual(result["freedBytes"], 3000) + + def test_delete_missing_book_is_not_ok(self): + with tempfile.TemporaryDirectory() as lib: + db = os.path.join(lib, "metadata.db") + _make_db(db) + result = _DeleteStubCalibre(db).delete("no-such-uuid") + self.assertFalse(result["ok"]) + self.assertEqual(result["reason"], "item not found") + + def test_delete_calibreweb_failure_is_not_ok(self): + with tempfile.TemporaryDirectory() as lib: + db = os.path.join(lib, "metadata.db") + _make_db(db) + result = _DeleteStubCalibre(db, succeed=False).delete("u-1") + self.assertFalse(result["ok"]) + + if __name__ == "__main__": unittest.main() diff --git a/static/cx-core/tests/test_config.py b/static/cx-core/tests/test_config.py index f8bb7db27..25c083d36 100644 --- a/static/cx-core/tests/test_config.py +++ b/static/cx-core/tests/test_config.py @@ -1,6 +1,7 @@ +import os import unittest -from cx_core.config import DEFAULT_PORT, _parse_port +from cx_core.config import DEFAULT_PORT, Config, _parse_port class ParsePortTest(unittest.TestCase): @@ -18,5 +19,23 @@ def test_out_of_range_falls_back(self): self.assertEqual(_parse_port("70000"), DEFAULT_PORT) +class ContentDirTest(unittest.TestCase): + def setUp(self): + self._saved = os.environ.pop("CX_CONTENT_DIR", None) + + def tearDown(self): + if self._saved is not None: + os.environ["CX_CONTENT_DIR"] = self._saved + else: + os.environ.pop("CX_CONTENT_DIR", None) + + def test_defaults_to_library(self): + self.assertEqual(Config.from_env().content_dir, "/library") + + def test_env_override(self): + os.environ["CX_CONTENT_DIR"] = "/data/content" + self.assertEqual(Config.from_env().content_dir, "/data/content") + + if __name__ == "__main__": unittest.main() diff --git a/static/cx-core/tests/test_kiwix.py b/static/cx-core/tests/test_kiwix.py index bce62ca22..9907d6fbf 100644 --- a/static/cx-core/tests/test_kiwix.py +++ b/static/cx-core/tests/test_kiwix.py @@ -217,5 +217,29 @@ def test_import_rejects_traversal_localref(self): self.assertFalse(os.path.exists(os.path.join(os.path.dirname(zdir), "evil.zim"))) +class KiwixDeleteTest(unittest.TestCase): + def test_delete_removes_file_and_reports_exact_size(self): + with tempfile.TemporaryDirectory() as zdir: + name = "wikipedia_en_all_2024-01.zim" + data = _zim_header(uuid.uuid4()) + os.urandom(321) + with open(os.path.join(zdir, name), "wb") as f: + f.write(data) + adapter = KiwixAdapter(zdir, indexer="/nonexistent/indexer") # reindex is a no-op + result = adapter.delete(name) + self.assertTrue(result["ok"]) + self.assertEqual(result["freedBytes"], len(data)) # a ZIM is self-contained + self.assertFalse(os.path.exists(os.path.join(zdir, name))) + + def test_delete_missing_item_is_not_ok(self): + with tempfile.TemporaryDirectory() as zdir: + result = KiwixAdapter(zdir, indexer="/nonexistent").delete("absent.zim") + self.assertFalse(result["ok"]) + + def test_delete_rejects_traversal(self): + with tempfile.TemporaryDirectory() as zdir: + result = KiwixAdapter(zdir, indexer="/nonexistent").delete("../evil.zim") + self.assertFalse(result["ok"]) + + if __name__ == "__main__": unittest.main() diff --git a/static/cx-core/tests/test_kolibri.py b/static/cx-core/tests/test_kolibri.py index c202d67cc..924ec0aee 100644 --- a/static/cx-core/tests/test_kolibri.py +++ b/static/cx-core/tests/test_kolibri.py @@ -6,9 +6,11 @@ import io import tarfile +import cx_core.adapters.kolibri as kolibri_mod from cx_core.adapters.kolibri import ( KolibriAdapter, build_channel_item, + delete_command, export_commands, import_commands, ) @@ -235,5 +237,62 @@ def test_open_export_fails_when_staging_disk_is_short(self): k.shutil.disk_usage = orig +class DeleteCommandTest(unittest.TestCase): + def test_builds_the_delegated_delete_command(self): + self.assertEqual( + delete_command(VALID_ID, "/usr/bin/kolibri"), + ["/usr/bin/kolibri", "manage", "deletechannel", VALID_ID], + ) + + +class _DeleteStubKolibri(KolibriAdapter): + """Overrides the CLI seam so delete delegation is testable without a live Kolibri.""" + + def __init__(self, *args, succeed=True, **kwargs): + super().__init__(*args, **kwargs) + self._succeed = succeed + + def _delete_channel(self, channel_id): + self.deleted = channel_id + return self._succeed + + +class KolibriDeleteTest(unittest.TestCase): + def setUp(self): + self._d = tempfile.TemporaryDirectory() + self.db = os.path.join(self._d.name, "db.sqlite3") + _make_db(self.db, cid=VALID_ID) + # Measure the reclaim as a free-space delta: 1000 before, 1300 after -> 300 freed. + self._free = [1000, 1300] + self._orig_free = kolibri_mod.free_bytes + kolibri_mod.free_bytes = lambda path: self._free.pop(0) + + def tearDown(self): + kolibri_mod.free_bytes = self._orig_free + self._d.cleanup() + + def test_delete_delegates_and_reports_freed_delta(self): + adapter = _DeleteStubKolibri(self.db) + result = adapter.delete(VALID_ID) + self.assertTrue(result["ok"]) + self.assertEqual(adapter.deleted, VALID_ID) + self.assertEqual(result["freedBytes"], 300) + + def test_delete_failure_is_not_ok(self): + adapter = _DeleteStubKolibri(self.db, succeed=False) + result = adapter.delete(VALID_ID) + self.assertFalse(result["ok"]) + + def test_delete_missing_channel_404_shaped(self): + adapter = _DeleteStubKolibri(self.db) + result = adapter.delete("f" * 32) # valid shape, not installed + self.assertFalse(result["ok"]) + self.assertEqual(result["reason"], "item not found") + + def test_delete_invalid_channel_id_rejected(self): + adapter = _DeleteStubKolibri(self.db) + self.assertFalse(adapter.delete("not-a-channel-id")["ok"]) + + if __name__ == "__main__": unittest.main() diff --git a/static/cx-core/tests/test_router.py b/static/cx-core/tests/test_router.py index 16ddc7588..e67c21fa0 100644 --- a/static/cx-core/tests/test_router.py +++ b/static/cx-core/tests/test_router.py @@ -22,13 +22,15 @@ def _item(app: str, local_ref: str) -> ManifestItem: class FakeAdapter(ContentAdapter): - def __init__(self, app, items, export=None, verdict="ABSENT", id_kind="authoritative", import_result=None): + def __init__(self, app, items, export=None, verdict="ABSENT", id_kind="authoritative", + import_result=None, delete_result=None): self.app = app self.id_kind = id_kind self._items = items self._export = export self._verdict = verdict self._import_result = import_result or {"ok": True, "app": app} + self._delete_result = delete_result or {"ok": True, "app": app, "freedBytes": 10} def is_installed(self): return True @@ -46,6 +48,10 @@ def import_item(self, entry, payload_path): self.imported = (entry, payload_path) return self._import_result + def delete(self, local_ref): + self.deleted = local_ref + return self._delete_result + def _registry(): return Registry([ @@ -198,5 +204,58 @@ def test_import_item_adapter_failure_422(self): self.assertFalse(out["ok"]) +class DeleteRouteTest(unittest.TestCase): + def setUp(self): + self.reg = _registry() + + def test_delete_item_delegates_and_returns_freed(self): + status, out = dispatch(self.reg, "DELETE", "/v1/content/kiwix/a.zim", {}) + self.assertEqual(status, 200) + self.assertTrue(out["ok"]) + self.assertEqual(out["freedBytes"], 10) + self.assertEqual(self.reg.get("kiwix").deleted, "a.zim") + + def test_delete_missing_item_404(self): + status, _ = dispatch(self.reg, "DELETE", "/v1/content/kiwix/gone.zim", {}) + self.assertEqual(status, 404) + + def test_delete_unknown_app_404(self): + status, _ = dispatch(self.reg, "DELETE", "/v1/content/nope/x", {}) + self.assertEqual(status, 404) + + def test_delete_adapter_failure_422(self): + reg = Registry([FakeAdapter( + "kiwix", [_item("kiwix", "a.zim")], + delete_result={"ok": False, "reason": "kolibri delete failed"})]) + status, out = dispatch(reg, "DELETE", "/v1/content/kiwix/a.zim", {}) + self.assertEqual(status, 422) + self.assertFalse(out["ok"]) + + def test_delete_non_item_path_405(self): + status, _ = dispatch(self.reg, "DELETE", "/v1/content", {}) + self.assertEqual(status, 405) + + +class StorageRouteTest(unittest.TestCase): + def test_storage_aggregates_disk_and_per_app(self): + reg = Registry( + [FakeAdapter("kiwix", [_item("kiwix", "a.zim"), _item("kiwix", "b.zim")]), + FakeAdapter("calibre", [_item("calibre", "book-1")])], + content_volume="/library") + import cx_core.router as r + orig = r.disk_total_free + r.disk_total_free = lambda p: (1000, 400) + try: + status, out = dispatch(reg, "GET", "/v1/storage", {}) + finally: + r.disk_total_free = orig + self.assertEqual(status, 200) + self.assertEqual(out["volume"], "/library") + self.assertEqual(out["totalBytes"], 1000) + self.assertEqual(out["freeBytes"], 400) + self.assertEqual(out["usedByContentBytes"], 30) # kiwix 20 + calibre 10 + self.assertEqual(out["perApp"], [{"app": "calibre", "bytes": 10}, {"app": "kiwix", "bytes": 20}]) + + if __name__ == "__main__": unittest.main() diff --git a/static/cx-core/tests/test_server.py b/static/cx-core/tests/test_server.py index a55207741..fb2f32ba0 100644 --- a/static/cx-core/tests/test_server.py +++ b/static/cx-core/tests/test_server.py @@ -70,6 +70,28 @@ def test_apps_json_over_http(self): c.close() self.assertEqual(out, {"apps": ["kiwix"]}) + def test_delete_item_over_http(self): + c = self._conn() + c.request("DELETE", f"/v1/content/kiwix/{self.zim_name}") + resp = c.getresponse() + out = json.loads(resp.read()) + c.close() + self.assertEqual(resp.status, 200) + self.assertTrue(out["ok"]) + self.assertEqual(out["freedBytes"], len(self.zim_bytes)) + self.assertFalse(os.path.exists(os.path.join(self._dir.name, self.zim_name))) + + def test_storage_over_http(self): + c = self._conn() + c.request("GET", "/v1/storage") + resp = c.getresponse() + out = json.loads(resp.read()) + c.close() + self.assertEqual(resp.status, 200) + # All content lives in the one ZIM, so the per-app total accounts for it. + self.assertEqual(out["usedByContentBytes"], len(self.zim_bytes)) + self.assertEqual(out["perApp"], [{"app": "kiwix", "bytes": len(self.zim_bytes)}]) + if __name__ == "__main__": unittest.main()