diff --git a/deeptutor/api/router_index.json b/deeptutor/api/router_index.json index a035ff0eb..1bcf9bf18 100644 --- a/deeptutor/api/router_index.json +++ b/deeptutor/api/router_index.json @@ -1,5 +1,5 @@ { - "fingerprint": "89ccb148b2f2be2f26231881c20cd6c77da096d6b16a24103a2670e8db3db538", + "fingerprint": "76ebae9398b63d68f6f7ba99e420989fcd17a4edaad0b4bb3dfb6aa24484242c", "routers": { "deeptutor.api.routers.auth:router": [ { diff --git a/deeptutor/api/routers/file_library.py b/deeptutor/api/routers/file_library.py index bcd935f45..83bcaa54c 100644 --- a/deeptutor/api/routers/file_library.py +++ b/deeptutor/api/routers/file_library.py @@ -163,7 +163,10 @@ async def restore_library_file( _auth: TokenPayload = Depends(require_auth), ) -> dict: """Restore a soft-deleted library file.""" - restored = await _get_store().restore_file(file_id) + try: + restored = await _get_store().restore_file(file_id) + except _fl.FileLibraryContentConflict as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc if not restored: raise HTTPException(status_code=404, detail="File not found") return {"id": file_id, "restored": True} diff --git a/deeptutor/services/storage/file_library.py b/deeptutor/services/storage/file_library.py index 51f0f3b01..94a1b2bc5 100644 --- a/deeptutor/services/storage/file_library.py +++ b/deeptutor/services/storage/file_library.py @@ -80,6 +80,10 @@ def _run_migrations(conn) -> None: # --------------------------------------------------------------------------- +class FileLibraryContentConflict(ValueError): + """Restoring an entry would duplicate another active content hash.""" + + class FileLibraryStore: """Persistent file library store. @@ -357,10 +361,23 @@ class FileLibraryStore: exists = conn.execute("SELECT 1 FROM library_files WHERE id = ?", (file_id,)).fetchone() if exists is None: return False - conn.execute( - "UPDATE library_files SET is_deleted = 0, deleted_at = NULL, updated_at = ? WHERE id = ? AND is_deleted = 1", - (now, file_id), - ) + try: + conn.execute( + "UPDATE library_files SET is_deleted = 0, deleted_at = NULL, updated_at = ? WHERE id = ? AND is_deleted = 1", + (now, file_id), + ) + except sqlite3.IntegrityError as exc: + if exc.sqlite_errorcode == sqlite3.SQLITE_CONSTRAINT_UNIQUE: + duplicate = conn.execute( + "SELECT 1 FROM library_files WHERE is_deleted = 0 AND id != ? " + "AND sha256 = (SELECT sha256 FROM library_files WHERE id = ?)", + (file_id, file_id), + ).fetchone() + if duplicate is not None: + raise FileLibraryContentConflict( + "A file with the same content is already active in your library." + ) from exc + raise conn.commit() return True diff --git a/tests/api/test_file_library_router.py b/tests/api/test_file_library_router.py index c0fb4c945..a9e3af698 100644 --- a/tests/api/test_file_library_router.py +++ b/tests/api/test_file_library_router.py @@ -334,3 +334,32 @@ def test_upload_and_list_are_isolated_between_users(library_app: LibraryAppFacto assert bob_list.json() == [] assert bob_get.status_code == 404 assert bob_download.status_code == 404 + + +def test_restore_duplicate_content_reports_conflict_and_can_be_retried( + library_app: LibraryAppFactory, +) -> None: + client, _ = library_app() + first = client.post( + "/files/library/", + data={"filename": "first.txt"}, + files={"file": ("first.txt", b"preserve both records", "text/plain")}, + ).json()["id"] + assert client.delete(f"/files/library/{first}").status_code == 200 + second = client.post( + "/files/library/", + data={"filename": "second.txt"}, + files={"file": ("second.txt", b"preserve both records", "text/plain")}, + ).json()["id"] + assert second != first + + response = client.post(f"/files/library/{first}/restore") + assert response.status_code == 409 + assert "same content" in response.json()["detail"] + assert client.get(f"/files/library/{first}").json()["is_deleted"] is True + assert client.get(f"/files/library/{second}").json()["is_deleted"] is False + assert client.get(f"/files/library/{second}/download").content == b"preserve both records" + + assert client.delete(f"/files/library/{second}").status_code == 200 + assert client.post(f"/files/library/{first}/restore").status_code == 200 + assert client.get(f"/files/library/{first}/download").content == b"preserve both records" diff --git a/tests/services/storage/test_file_library.py b/tests/services/storage/test_file_library.py index d702acb7a..38ad28dc9 100644 --- a/tests/services/storage/test_file_library.py +++ b/tests/services/storage/test_file_library.py @@ -539,3 +539,23 @@ def test_reset_clears_singleton() -> None: reset_file_library_store() s2 = get_file_library_store() assert s1 is not s2 + + +def test_restore_does_not_hide_unrelated_database_failure( + rooted_store: FileLibraryStore, + tmp_db_path: Path, +) -> None: + import sqlite3 + + first = asyncio.run(rooted_store.add_file(data=b"same", filename="first.txt")) + asyncio.run(rooted_store.delete_file(first["id"])) + second = asyncio.run(rooted_store.add_file(data=b"same", filename="second.txt")) + with sqlite3.connect(tmp_db_path) as connection: + connection.execute( + "CREATE TRIGGER fail_restore BEFORE UPDATE OF is_deleted ON library_files " + "WHEN NEW.is_deleted = 0 BEGIN SELECT RAISE(ABORT, 'unrelated failure'); END" + ) + with pytest.raises(sqlite3.IntegrityError, match="unrelated failure"): + asyncio.run(rooted_store.restore_file(first["id"])) + assert asyncio.run(rooted_store.get_file(first["id"]))["is_deleted"] is True + assert asyncio.run(rooted_store.get_file(second["id"]))["is_deleted"] is False