🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Fix Paperless-ngx 3.x task polling and release the DB connection during uploads (#298)
Omega (QA)3e79ed1af106
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ff03331..9883e3c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,9 @@- **Product photo fetch pins the connection to the validated address (GHSA-7rwc-pg49-r48w):** the photo-by-URL fetch used to validate a hostname and then let the HTTP client resolve it again at connect time, so a DNS answer that changed between the two lookups could steer the connection to a private address the guard never saw. The fetch now resolves each hop hostname exactly once, validates every returned address, and connects to the first public one, with no second lookup and no failover. For https the connection still presents the original hostname as SNI and verifies the certificate against it, and the Host header still carries the original hostname. The fetch also no longer follows environment proxy settings, since a proxy would resolve the hostname itself.- _Files: `backend/warranties_routes.py`, `tests/test_photo_url.py`_+- **Paperless-ngx 3.x uploads resolve again (#298):** the task poll only understood the Paperless API v9 shapes, so against Paperless-ngx 3.x (API v10) it never recognized a finished task: the detail lookup 404s, the list reply is a paginated page object, the status is lower case, and the document arrives in `related_document_ids`. The poll now unwraps paginated pages, compares the status case-insensitively, and reads `related_document_ids[0]` (with the `result_data` text as a fallback), so uploads resolve in seconds again instead of timing out after 10 minutes and saving with no document link. The v9 shapes keep working unchanged. The upload route also releases its database connection before the poll starts instead of holding it idle in transaction for the whole wait, and takes a fresh one only for the ownership claim afterwards.+ - _Files: `backend/paperless_handler.py`, `backend/file_routes.py`, `tests/mock_paperless.py`, `tests/test_paperless_api_v10.py`_+- **Warranty expiration change history (#209):** editing a warranty's expiration date, duration, or lifetime status now records the transition (previous value, new value, timestamp, editor, and an optional reason up to 255 characters) in a new `warranty_expiry_history` table without automatically mutating dates from claims. Warranties with recorded changes show a subtle clickable history badge next to the expiration date across the dashboard and Status page, opening an Expiry History modal; the Status page detail row and the Edit Warranty modal also display the change history, and the Edit Warranty modal dynamically reveals the optional reason field only when expiration inputs are modified.- _Files: `backend/migrations/057_create_warranty_expiry_history.sql`, `backend/warranties_routes.py`, `backend/statistics_routes.py`, `frontend/js/components/expiryHistory.js`, `frontend/js/components/editModal.js`, `frontend/js/components/warrantyRenderer.js`, `frontend/js/components/ui.js`, `frontend/js/controllers/warrantyListController.js`, `frontend/js/index.js`, `frontend/index.html`, `frontend/status.html`, `frontend/script.js`, `frontend/status.js`, `frontend/style.css`, `frontend/sw.js`, `locales/*/translation.json`, `tests/test_warranty_expiry_history.py`_diff --git a/backend/file_routes.py b/backend/file_routes.pyindex f9931dd..b9fb7e8 100644--- a/backend/file_routes.py+++ b/backend/file_routes.py@@ -393,13 +393,19 @@ def paperless_upload():try:logger.info("Paperless upload endpoint called")- # Get Paperless handler+ # Get Paperless handler. The handler only reads site settings from+ # the connection, so release it right away: the upload below polls+ # Paperless for up to 10 minutes, and holding a pooled connection+ # idle in transaction for the whole wait starves the pool (#298).+ # A fresh connection is taken again below for the ownership claim.conn = get_db_connection()logger.info("Database connection acquired")-+paperless_handler = get_paperless_handler(conn)logger.info(f"Paperless handler: {paperless_handler is not None}")-+ release_db_connection(conn)+ conn = None+if not paperless_handler:logger.warning("Paperless handler is None - integration not configured")return jsonify({"error": "Paperless-ngx integration is not enabled or configured"}), 400@@ -464,12 +470,18 @@ def paperless_upload():# Record the uploader as the document's owner in Warracker, so# search/linking/serving can be scoped to them. Paperless may# return a non-numeric (task) id instead of a document id; only- # numeric ids can be tracked.+ # numeric ids can be tracked. The connection was released+ # before the upload, so take a fresh one for the claim.try:numeric_document_id = int(document_id)- with conn.cursor() as cur:- claim_upload_ownership(cur, numeric_document_id, request.user['id'], upload_started_at)- conn.commit()+ conn = get_db_connection()+ try:+ with conn.cursor() as cur:+ claim_upload_ownership(cur, numeric_document_id, request.user['id'], upload_started_at)+ conn.commit()+ finally:+ release_db_connection(conn)+ conn = Noneexcept (TypeError, ValueError):logger.info(f"Upload returned non-document id {document_id!r}; ownership not recorded")return jsonify({@@ -484,12 +496,17 @@ def paperless_upload():# Reveal it only when the requester could link it anyway.revealed_id = document_idif document_id is not None:- with conn.cursor() as cur:- if not user_can_link_paperless_document(- cur, request.user['id'],- request.user.get('is_admin', False), document_id- ):- revealed_id = None+ conn = get_db_connection()+ try:+ with conn.cursor() as cur:+ if not user_can_link_paperless_document(+ cur, request.user['id'],+ request.user.get('is_admin', False), document_id+ ):+ revealed_id = None+ finally:+ release_db_connection(conn)+ conn = Nonereturn jsonify({"success": False,"document_id": revealed_id,diff --git a/backend/paperless_handler.py b/backend/paperless_handler.pyindex fdf2685..22fb8b7 100644--- a/backend/paperless_handler.py+++ b/backend/paperless_handler.py@@ -7,6 +7,7 @@ for uploading, retrieving, and managing documents.import requestsimport logging+import refrom typing import Optional, Dict, Any, Tupleimport osfrom io import BytesIO@@ -15,6 +16,25 @@ import hashliblogger = logging.getLogger(__name__)+def _task_payload(body):+ """Normalize a /api/tasks response to a single task dict.++ Paperless API v9 returns the task as a plain object from the detail+ endpoint and as a bare list from the filtered list endpoint. API v10+ (Paperless-ngx 3.x) paginates the list endpoint, so it arrives as a+ page object with the tasks under "results". Unwrap both shapes; an+ empty list or page means the task is not visible yet.+ """+ if isinstance(body, list):+ return body[0] if body else {}+ if isinstance(body, dict):+ results = body.get("results")+ if isinstance(results, list):+ return results[0] if results else {}+ return body+ return {}++class PaperlessHandler:"""Handle interactions with Paperless-ngx API"""@@ -698,25 +718,36 @@ class PaperlessHandler:resp.raise_for_status()- # Legacy endpoint returns a list- if isinstance(resp.json(), list):- task_info = resp.json()[0] if resp.json() else {}- else:- task_info = resp.json()+ # v9 returns the task as a plain object (detail endpoint)+ # or a bare list (filtered list endpoint); v10 paginates+ # the list endpoint, so unwrap the page object first.+ task_info = _task_payload(resp.json())- # In newer Paperless versions the field is called "state"; fall back to- # "status" for backwards-compatibility.+ # Paperless 3.x (API v10) reports the task status in lower+ # case under "status"; v9 uses upper-case "state". Compare+ # case-insensitively so both keep working.state = task_info.get("state") or task_info.get("status")+ if isinstance(state, str):+ state = state.upper()+ # v10 drops related_document in favour of a list of ids.related_doc = task_info.get("related_document")+ if not related_doc:+ related_ids = task_info.get("related_document_ids")+ if isinstance(related_ids, list) and related_ids:+ related_doc = related_ids[0]- # Some Paperless versions don't fill related_document but embed the- # newly-created ID in the free-text "result" string, e.g.+ # Some Paperless versions don't fill the related-document+ # field but embed the newly-created ID in free text, e.g.# "Success. New document id 416 created" – see GH#3064.- if not related_doc and isinstance(task_info.get("result"), str):- import re- m = re.search(r"document id (\d+)", task_info["result"])- if m:- related_doc = m.group(1)+ # v10 carries that text in result_data instead of result.+ if not related_doc:+ for text_field in ("result", "result_data"):+ text = task_info.get(text_field)+ if isinstance(text, str):+ m = re.search(r"document id (\d+)", text)+ if m:+ related_doc = m.group(1)+ breakif state == "SUCCESS" and related_doc:try:diff --git a/tests/mock_paperless.py b/tests/mock_paperless.pyindex 7158395..33e0b72 100644--- a/tests/mock_paperless.py+++ b/tests/mock_paperless.py@@ -26,7 +26,14 @@ DOCS = ["tags": [2]},]TASKS = {} # task_id -> doc_id+TASK_NUMERIC = {} # task_id -> numeric task id (v10 looks tasks up by it)+NEXT_TASK_ID = [1]NEXT_ID = [3]+# Flip to serve API v10 shapes (Paperless-ngx 3.x): the detail endpoint+# 404s for UUIDs, the list endpoint paginates, status is lower case,+# and the document arrives in related_document_ids. Tests flip this+# and reset it; the default stays v9.+TASKS_V10 = FalseLAST_DOCUMENT_QUERIES = [] # parsed query dicts of /api/documents/ GETs@@ -86,6 +93,9 @@ class Handler(BaseHTTPRequestHandler):m = re.match(r"^/api/tasks/([0-9a-f-]+)/$", path)if m:tid = m.group(1)+ # v10 looks tasks up by numeric id, so a UUID never matches.+ if TASKS_V10:+ return self._json({"detail": "Not found"}, status=404)if tid in TASKS:return self._json({"id": tid, "state": "SUCCESS","result": f"document id {TASKS[tid]}"})@@ -94,8 +104,19 @@ class Handler(BaseHTTPRequestHandler):if path == "/api/tasks/":tid = qs.get("task_id", [""])[0]if tid in TASKS:+ if TASKS_V10:+ return self._json({+ "count": 1, "next": None, "previous": None,+ "results": [{"id": TASK_NUMERIC[tid],+ "task_id": tid,+ "status": "success",+ "related_document_ids": [TASKS[tid]],+ "result_data": f"Success. New document id {TASKS[tid]} created"}]})return self._json([{"id": tid, "state": "SUCCESS","result": f"document id {TASKS[tid]}"}])+ if TASKS_V10:+ return self._json({"count": 0, "next": None,+ "previous": None, "results": []})return self._json([])if path == "/api/tags/":@@ -127,6 +148,8 @@ class Handler(BaseHTTPRequestHandler):"archived_file_name": fname})task_id = str(uuid.uuid4())TASKS[task_id] = doc_id+ TASK_NUMERIC[task_id] = NEXT_TASK_ID[0]+ NEXT_TASK_ID[0] += 1# Return task UUID as plain text (like real Paperless-ngx),# toggleable to JSON string via ?json=1 for branch testingif parse_qs(urlparse(self.path).query).get("json"):diff --git a/tests/test_paperless_api_v10.py b/tests/test_paperless_api_v10.pynew file mode 100644index 0000000..bda9b6d--- /dev/null+++ b/tests/test_paperless_api_v10.py@@ -0,0 +1,268 @@+"""Paperless-ngx API v10 (Paperless-ngx 3.x) task polling (#298).++The v9 poll shapes (plain task object, bare list, upper-case state,+related_document, result text) must keep working, and the v10 shapes+(paginated list page, lower-case status, related_document_ids,+result_data) must resolve the document id instead of looping to the+10-minute deadline and returning None.+"""+import io+import types++import mock_paperless+import pytest++import backend.file_routes as file_routes+from backend.paperless_handler import PaperlessHandler, _task_payload+from backend.paperless_access import get_paperless_document_owner++TASK_ID = "123e4567-e89b-12d3-a456-426614174000"+++class _FakeResponse:+ def __init__(self, status_code, payload):+ self.status_code = status_code+ self._payload = payload+ self.url = ""++ def json(self):+ return self._payload++ def raise_for_status(self):+ return None+++def _stub_get(handler, primary, task_list):+ """Point handler.get at canned task responses.++ primary is (status, body) for GET /api/tasks/<uuid>/, task_list is+ the body for GET /api/tasks/?task_id=<uuid>. Either may be a list+ of bodies served in order, to model a task that finishes later.+ """+ calls = {"primary": 0, "list": 0}++ def _pick(spec, count):+ if isinstance(spec, list):+ return spec[min(count, len(spec) - 1)]+ return spec++ def _get(url_or_path, **kwargs):+ if url_or_path.rstrip("/").endswith("/api/tasks"):+ body = _pick(task_list, calls["list"])+ calls["list"] += 1+ return _FakeResponse(200, body)+ status, body = _pick(primary, calls["primary"])+ calls["primary"] += 1+ return _FakeResponse(status, body)++ handler.get = _get+ return calls+++def _handler():+ return PaperlessHandler("http://127.0.0.1:9", "test-token")+++# --- _task_payload: response shape normalization ---++def test_task_payload_unwraps_v10_page():+ page = {"count": 1, "next": None, "previous": None,+ "results": [{"id": 7, "status": "success"}]}+ assert _task_payload(page) == {"id": 7, "status": "success"}+ assert _task_payload({"count": 0, "results": []}) == {}+ assert _task_payload([{"id": 7, "state": "SUCCESS"}]) == {"id": 7, "state": "SUCCESS"}+ assert _task_payload([]) == {}+ assert _task_payload({"id": 7, "state": "SUCCESS"}) == {"id": 7, "state": "SUCCESS"}+ assert _task_payload(None) == {}+++# --- _get_document_id_from_task: v10 and v9 shapes ---++def test_v10_poll_resolves_document_id():+ handler = _handler()+ calls = _stub_get(handler,+ primary=(404, {"detail": "Not found"}),+ task_list={"count": 1, "next": None, "previous": None,+ "results": [{"id": 7, "task_id": TASK_ID,+ "status": "success",+ "related_document_ids": [416],+ "result_data": ""}]})+ assert handler._get_document_id_from_task(+ TASK_ID, timeout_secs=5, poll_interval=0.01) == 416+ assert calls["primary"] == 1+ assert calls["list"] == 1+++def test_v10_poll_reads_result_data_fallback():+ handler = _handler()+ _stub_get(handler,+ primary=(404, {"detail": "Not found"}),+ task_list={"count": 1, "next": None, "previous": None,+ "results": [{"id": 7, "task_id": TASK_ID,+ "status": "success",+ "related_document_ids": [],+ "result_data": "Success. New document id 417 created"}]})+ assert handler._get_document_id_from_task(+ TASK_ID, timeout_secs=5, poll_interval=0.01) == 417+++def test_v10_poll_takes_first_related_document_id():+ handler = _handler()+ _stub_get(handler,+ primary=(404, {"detail": "Not found"}),+ task_list={"count": 1, "next": None, "previous": None,+ "results": [{"id": 7, "task_id": TASK_ID,+ "status": "SUCCESS",+ "related_document_ids": [418, 419]}]})+ assert handler._get_document_id_from_task(+ TASK_ID, timeout_secs=5, poll_interval=0.01) == 418+++def test_v10_poll_failure_state_returns_none_quickly():+ handler = _handler()+ _stub_get(handler,+ primary=(404, {"detail": "Not found"}),+ task_list={"count": 1, "next": None, "previous": None,+ "results": [{"id": 7, "task_id": TASK_ID,+ "status": "failure",+ "related_document_ids": []}]})+ assert handler._get_document_id_from_task(+ TASK_ID, timeout_secs=5, poll_interval=0.01) is None+++def test_v10_empty_page_keeps_polling_then_times_out():+ handler = _handler()+ calls = _stub_get(handler,+ primary=(404, {"detail": "Not found"}),+ task_list={"count": 0, "next": None,+ "previous": None, "results": []})+ assert handler._get_document_id_from_task(+ TASK_ID, timeout_secs=0.05, poll_interval=0.01) is None+ assert calls["list"] > 1+++def test_v10_running_then_success():+ handler = _handler()+ running = {"count": 1, "next": None, "previous": None,+ "results": [{"id": 7, "task_id": TASK_ID,+ "status": "running", "related_document_ids": []}]}+ done = {"count": 1, "next": None, "previous": None,+ "results": [{"id": 7, "task_id": TASK_ID,+ "status": "success", "related_document_ids": [420]}]}+ _stub_get(handler,+ primary=(404, {"detail": "Not found"}),+ task_list=[running, done])+ assert handler._get_document_id_from_task(+ TASK_ID, timeout_secs=5, poll_interval=0.01) == 420+++def test_v9_detail_poll_still_works():+ handler = _handler()+ _stub_get(handler,+ primary=(200, {"id": TASK_ID, "state": "SUCCESS",+ "related_document": 421,+ "result": f"document id 421"}),+ task_list=[])+ assert handler._get_document_id_from_task(+ TASK_ID, timeout_secs=5, poll_interval=0.01) == 421+++def test_v9_list_poll_still_works():+ handler = _handler()+ _stub_get(handler,+ primary=(404, {"detail": "Not found"}),+ task_list=[{"id": TASK_ID, "state": "SUCCESS",+ "related_document": 422}])+ assert handler._get_document_id_from_task(+ TASK_ID, timeout_secs=5, poll_interval=0.01) == 422+++def test_v9_result_text_fallback_still_works():+ handler = _handler()+ _stub_get(handler,+ primary=(200, {"id": TASK_ID, "state": "SUCCESS",+ "result": "Success. New document id 423 created"}),+ task_list=[])+ assert handler._get_document_id_from_task(+ TASK_ID, timeout_secs=5, poll_interval=0.01) == 423+++# --- End to end against the mock server in v10 mode ---++def v10_mock(monkeypatch):+ """Serve v10 task shapes from the mock, then restore v9."""+ monkeypatch.setattr(mock_paperless, "TASKS_V10", True)+ yield+ monkeypatch.setattr(mock_paperless, "TASKS_V10", False)+++def test_upload_resolves_document_id_against_v10_mock(paperless_url, v10_mock):+ handler = PaperlessHandler(paperless_url, "test-token")+ success, document_id, _message = handler.upload_document(+ file_content=b"%PDF-1.4 v10 test",+ filename="v10.pdf",+ title="v10 upload",+ )+ assert success is True+ assert isinstance(document_id, int) and document_id > 0+++def test_upload_resolves_document_id_against_v9_mock(paperless_url):+ handler = PaperlessHandler(paperless_url, "test-token")+ success, document_id, _message = handler.upload_document(+ file_content=b"%PDF-1.4 v9 test",+ filename="v9.pdf",+ title="v9 upload",+ )+ assert success is True+ assert isinstance(document_id, int) and document_id > 0+++# --- The upload route must not hold a DB connection across the poll ---++def test_paperless_upload_releases_connection_before_poll(+ client, user_factory, db_connection, monkeypatch):+ user = user_factory()+ checked_out = {"count": 0}++ from backend.db_handler import get_db_connection as real_get+ from backend.db_handler import release_db_connection as real_release++ def counting_get():+ conn = real_get()+ checked_out["count"] += 1+ return conn++ def counting_release(conn):+ real_release(conn)+ checked_out["count"] -= 1++ monkeypatch.setattr(file_routes, "get_db_connection", counting_get)+ monkeypatch.setattr(file_routes, "release_db_connection", counting_release)++ def _fake_upload_document(**kwargs):+ assert checked_out["count"] == 0, (+ "paperless upload polled while a DB connection was held")+ return True, 9401, "ok"++ def _fake_get_paperless_handler(conn):+ assert checked_out["count"] == 1+ return types.SimpleNamespace(upload_document=_fake_upload_document)++ monkeypatch.setattr(+ file_routes, "get_paperless_handler", _fake_get_paperless_handler)++ r = client.post(+ "/api/paperless/upload", headers=user["headers"],+ data={"title": "conn.pdf",+ "file": (io.BytesIO(b"%PDF-1.4 test"), "conn.pdf")},+ content_type="multipart/form-data")+ assert r.status_code == 200+ body = r.get_json()+ assert body["success"] is True+ assert body["document_id"] == 9401+ assert checked_out["count"] == 0++ with db_connection.cursor() as cur:+ assert get_paperless_document_owner(cur, 9401) is not None