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
40 changes: 40 additions & 0 deletions static/cx-core/cx_core/adapters/calibre.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
20 changes: 20 additions & 0 deletions static/cx-core/cx_core/adapters/calibreweb.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
20 changes: 20 additions & 0 deletions static/cx-core/cx_core/adapters/kiwix.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 +
Expand Down
48 changes: 47 additions & 1 deletion static/cx-core/cx_core/adapters/kolibri.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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
4 changes: 4 additions & 0 deletions static/cx-core/cx_core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"),
Expand Down
20 changes: 20 additions & 0 deletions static/cx-core/cx_core/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
21 changes: 15 additions & 6 deletions static/cx-core/cx_core/ports.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"}
10 changes: 8 additions & 2 deletions static/cx-core/cx_core/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand All @@ -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())
Expand Down
47 changes: 46 additions & 1 deletion static/cx-core/cx_core/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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."""
Expand All @@ -135,13 +170,23 @@ 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"}

# GET /v1/apps : installed apps that have a loaded adapter.
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"))
Expand Down
6 changes: 6 additions & 0 deletions static/cx-core/cx_core/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Loading
Loading