Merge pull request #2239 from rudycelekli/fix/library-restore-content-conflict-20261031

fix(library): report restore content conflicts without a server error
This commit is contained in:
Bingxi Zhao
2026-10-31 16:41:10 +08:00
committed by GitHub
5 changed files with 75 additions and 6 deletions

View File

@@ -1,5 +1,5 @@
{
"fingerprint": "89ccb148b2f2be2f26231881c20cd6c77da096d6b16a24103a2670e8db3db538",
"fingerprint": "76ebae9398b63d68f6f7ba99e420989fcd17a4edaad0b4bb3dfb6aa24484242c",
"routers": {
"deeptutor.api.routers.auth:router": [
{

View File

@@ -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}

View File

@@ -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

View File

@@ -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"

View File

@@ -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