fix: a paper scan is not left behind when the action fails
The scan was written to Galena or plain files before any of the action's database writes. It is now read and checked before those writes (scan_bytes) but stored only after the run's rows have flushed (keep_scan). A plain-files scan is also deleted if the transaction rolls back. Galena has no delete here, so a scan committed there can still outlive a failed final COMMIT. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -56,6 +56,7 @@ from typing import Any
|
||||
|
||||
from dredd_core import events, workflow_contract
|
||||
from dredd_core.document_ref import DocumentRef, FileRef, check_name, sha256_of, to_dict
|
||||
from sqlalchemy import event as sa_event
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
@@ -326,6 +327,11 @@ def store_scan(document: DocumentRef | None, scan: Any, *, token: str) -> Docume
|
||||
"""Keep the scan of the signed paper: in Galena next to `document` when Galena publishes it,
|
||||
else (no document, Galena refused, a draft) in this module's plain files. Every refusal of the
|
||||
scan itself comes before either write."""
|
||||
return keep_scan(document, *scan_bytes(scan), token=token)
|
||||
|
||||
|
||||
def scan_bytes(scan: Any) -> tuple[bytes, str]:
|
||||
"""The scan's bytes and file name, or the 422 that refuses it. Nothing is written."""
|
||||
if scan is None:
|
||||
raise _bad("scan_required", "The paper ending is approved by uploading the signed scan.")
|
||||
store = subjects.files()
|
||||
@@ -337,6 +343,13 @@ def store_scan(document: DocumentRef | None, scan: Any, *, token: str) -> Docume
|
||||
{"code": "file_too_large", "max": store.max_bytes})
|
||||
name = check_name((scan.filename or "").replace("\\", "/").rsplit("/", 1)[-1].strip()
|
||||
or "skan.pdf")
|
||||
return data, name
|
||||
|
||||
|
||||
def keep_scan(document: DocumentRef | None, data: bytes, name: str, *,
|
||||
token: str) -> DocumentRef | FileRef:
|
||||
"""Write a checked scan: Galena first when the run is on a document, else plain files."""
|
||||
store = subjects.files()
|
||||
if document is not None:
|
||||
path = f"{SCAN_FOLDER}/{name}"
|
||||
commit = galena.get().save_scan(document.document_id, path, data, token=token)
|
||||
@@ -346,6 +359,19 @@ def store_scan(document: DocumentRef | None, scan: Any, *, token: str) -> Docume
|
||||
return store.save(data, name)
|
||||
|
||||
|
||||
def delete_on_rollback(db: DbSession, ref: FileRef) -> None:
|
||||
"""Remove the plain file `ref` if `db`'s transaction rolls back; keep it once it commits."""
|
||||
def rolled_back(_session: Any) -> None:
|
||||
sa_event.remove(db, "after_commit", committed)
|
||||
subjects.files().delete(ref.file_id)
|
||||
|
||||
def committed(_session: Any) -> None:
|
||||
sa_event.remove(db, "after_rollback", rolled_back)
|
||||
|
||||
sa_event.listen(db, "after_rollback", rolled_back, once=True)
|
||||
sa_event.listen(db, "after_commit", committed, once=True)
|
||||
|
||||
|
||||
def next_stamp(now: dt.datetime, last: dt.datetime | None) -> dt.datetime:
|
||||
"""A timeline entry is never older than the run's last one, whatever the clock did."""
|
||||
return now if last is None or now > last else last + _TICK
|
||||
@@ -422,10 +448,8 @@ def act(db: DbSession, actor: AppUser, run_id: uuid.UUID, *, action: str,
|
||||
if entered else t.state.assignees[before.current])
|
||||
managers = notify.owners(db, run, token=token) if "owner" in t.notify else frozenset()
|
||||
|
||||
# Writes outside the database (Galena, the file store) only after every refusal.
|
||||
if action == "paper_scan":
|
||||
kept = store_scan(subject if isinstance(subject, DocumentRef) else None, scan, token=token)
|
||||
run.scan, proof = to_dict(kept), evidence(kept)
|
||||
scanned = scan_bytes(scan) # its refusals before any write
|
||||
else:
|
||||
if action == "edit_request":
|
||||
requests.apply_edit(db, actor, subject, **edit, ip=ip)
|
||||
@@ -447,6 +471,18 @@ def act(db: DbSession, actor: AppUser, run_id: uuid.UUID, *, action: str,
|
||||
run.stages = [dict(s) for s in t.state.stages]
|
||||
run.current, run.state, run.round = t.state.current, t.state.state, t.state.round
|
||||
|
||||
if action == "paper_scan":
|
||||
# The scan is written outside the database, so as late as possible: after the run's own
|
||||
# rows reach Postgres (a refused write leaves no scan behind). A plain-files scan is
|
||||
# deleted again if the transaction rolls back; Galena keeps a scan it already committed
|
||||
# (it has no delete here), which only a failed final COMMIT can still leave.
|
||||
db.flush()
|
||||
kept = keep_scan(subject if isinstance(subject, DocumentRef) else None, *scanned,
|
||||
token=token)
|
||||
if isinstance(kept, FileRef):
|
||||
delete_on_rollback(db, kept)
|
||||
run.scan, proof = to_dict(kept), evidence(kept)
|
||||
|
||||
at = _stamp(db, run.id)
|
||||
db.add(WorkflowEvent(id=uuid.uuid4(), run_id=run.id, kind=t.event_kind,
|
||||
stage_from=t.stage_from, stage_to=t.stage_to, round=before.round,
|
||||
@@ -478,4 +514,5 @@ def act(db: DbSession, actor: AppUser, run_id: uuid.UUID, *, action: str,
|
||||
|
||||
__all__ = ["ACTIONS", "SCAN_FOLDER", "DocumentAt", "Subject", "act", "assert_content", "assert_current",
|
||||
"event_payload", "evidence", "next_stamp", "pinned", "run_state", "start", "store_scan",
|
||||
"scan_bytes", "keep_scan", "delete_on_rollback",
|
||||
"subject_kind"]
|
||||
|
||||
@@ -449,7 +449,7 @@ def test_refresh_is_the_owners(monkeypatch):
|
||||
def test_paper_scan_off_the_paper_stage_stores_nothing(monkeypatch):
|
||||
db = _acting(monkeypatch)
|
||||
saved = []
|
||||
monkeypatch.setattr(runs, "store_scan", lambda *a, **k: saved.append(a))
|
||||
monkeypatch.setattr(runs, "keep_scan", lambda *a, **k: saved.append(a))
|
||||
with pytest.raises(ValidationError) as err:
|
||||
_act(db, OTHER, action="paper_scan", scan=_Upload(b"%PDF scan"))
|
||||
assert err.value.extra["code"] == "not_paper_stage"
|
||||
@@ -475,6 +475,32 @@ def plain(monkeypatch, tmp_path):
|
||||
return store
|
||||
|
||||
|
||||
def _session():
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.orm import Session
|
||||
db = Session(create_engine("sqlite://"))
|
||||
db.execute(text("SELECT 1")) # a transaction for commit / rollback to end
|
||||
return db
|
||||
|
||||
|
||||
def test_a_plain_scan_is_deleted_when_the_transaction_rolls_back(plain):
|
||||
kept = plain.save(b"%PDF signed", "skan.pdf")
|
||||
db = _session()
|
||||
runs.delete_on_rollback(db, kept)
|
||||
db.rollback()
|
||||
assert not plain.delete(kept.file_id) # already gone
|
||||
|
||||
|
||||
def test_a_plain_scan_stays_once_the_transaction_commits(plain):
|
||||
kept = plain.save(b"%PDF signed", "skan.pdf")
|
||||
db = _session()
|
||||
runs.delete_on_rollback(db, kept)
|
||||
db.commit()
|
||||
db.execute(__import__("sqlalchemy").text("SELECT 1"))
|
||||
db.rollback() # a later rollback of the same session must not touch it
|
||||
assert plain.read(kept) == b"%PDF signed"
|
||||
|
||||
|
||||
def test_paper_scan_falls_back_to_plain_files_when_galena_refuses(monkeypatch, plain):
|
||||
fake = FakeGalena(scan_commit=None) # Galena refused, or made a draft of it
|
||||
monkeypatch.setattr(galena, "get", lambda: fake)
|
||||
|
||||
Reference in New Issue
Block a user