mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-11-27 15:35:14 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9feb7aaa14 |
No files matched your search
+10
-21
@@ -6,7 +6,6 @@ import zipfile
|
|||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from tempfile import TemporaryDirectory
|
from tempfile import TemporaryDirectory
|
||||||
from tempfile import mkstemp
|
|
||||||
|
|
||||||
from celery import Task
|
from celery import Task
|
||||||
from celery import shared_task
|
from celery import shared_task
|
||||||
@@ -897,26 +896,25 @@ def build_share_link_bundle(bundle_id: int) -> None:
|
|||||||
|
|
||||||
documents = list(bundle.documents.all().order_by("pk"))
|
documents = list(bundle.documents.all().order_by("pk"))
|
||||||
|
|
||||||
_, temp_zip_path_str = mkstemp(suffix=".zip", dir=settings.SCRATCH_DIR)
|
|
||||||
temp_zip_path = Path(temp_zip_path_str)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
strategy_class = (
|
strategy_class = (
|
||||||
ArchiveOnlyStrategy
|
ArchiveOnlyStrategy
|
||||||
if bundle.file_version == ShareLink.FileVersion.ARCHIVE
|
if bundle.file_version == ShareLink.FileVersion.ARCHIVE
|
||||||
else OriginalsOnlyStrategy
|
else OriginalsOnlyStrategy
|
||||||
)
|
)
|
||||||
with zipfile.ZipFile(temp_zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
|
|
||||||
strategy = strategy_class(zipf)
|
|
||||||
for document in documents:
|
|
||||||
strategy.add_document(document)
|
|
||||||
|
|
||||||
output_dir = settings.SHARE_LINK_BUNDLE_DIR
|
output_dir = settings.SHARE_LINK_BUNDLE_DIR
|
||||||
output_dir.mkdir(parents=True, exist_ok=True)
|
output_dir.mkdir(parents=True, exist_ok=True)
|
||||||
final_path = (output_dir / f"{bundle.slug}.zip").resolve()
|
final_path = (output_dir / f"{bundle.slug}.zip").resolve()
|
||||||
if final_path.exists():
|
|
||||||
final_path.unlink()
|
with TemporaryDirectory(dir=settings.SCRATCH_DIR) as tmp_dir:
|
||||||
shutil.move(temp_zip_path, final_path)
|
temp_zip_path = Path(tmp_dir) / "bundle.zip"
|
||||||
|
with zipfile.ZipFile(temp_zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
|
||||||
|
strategy = strategy_class(zipf)
|
||||||
|
for document in documents:
|
||||||
|
strategy.add_document(document)
|
||||||
|
|
||||||
|
final_path.unlink(missing_ok=True)
|
||||||
|
shutil.move(temp_zip_path, final_path)
|
||||||
|
|
||||||
bundle.file_path = f"{bundle.slug}.zip"
|
bundle.file_path = f"{bundle.slug}.zip"
|
||||||
bundle.size_bytes = final_path.stat().st_size
|
bundle.size_bytes = final_path.stat().st_size
|
||||||
@@ -947,16 +945,7 @@ def build_share_link_bundle(bundle_id: int) -> None:
|
|||||||
"timestamp": timezone.now().isoformat(),
|
"timestamp": timezone.now().isoformat(),
|
||||||
}
|
}
|
||||||
bundle.save(update_fields=["status", "last_error"])
|
bundle.save(update_fields=["status", "last_error"])
|
||||||
try:
|
|
||||||
temp_zip_path.unlink()
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
raise
|
raise
|
||||||
finally:
|
|
||||||
try:
|
|
||||||
temp_zip_path.unlink(missing_ok=True)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
@shared_task
|
@shared_task
|
||||||
|
|||||||
@@ -434,13 +434,9 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
|
|||||||
"documents.tasks.OriginalsOnlyStrategy.add_document",
|
"documents.tasks.OriginalsOnlyStrategy.add_document",
|
||||||
side_effect=RuntimeError("zip failure"),
|
side_effect=RuntimeError("zip failure"),
|
||||||
),
|
),
|
||||||
mock.patch("pathlib.Path.unlink") as unlink_mock,
|
self.assertRaises(RuntimeError),
|
||||||
):
|
):
|
||||||
unlink_mock.side_effect = [OSError("unlink"), OSError("unlink-finally")] + [
|
build_share_link_bundle(bundle.pk)
|
||||||
None,
|
|
||||||
] * 5
|
|
||||||
with self.assertRaises(RuntimeError):
|
|
||||||
build_share_link_bundle(bundle.pk)
|
|
||||||
|
|
||||||
bundle.refresh_from_db()
|
bundle.refresh_from_db()
|
||||||
self.assertEqual(bundle.status, ShareLinkBundle.Status.FAILED)
|
self.assertEqual(bundle.status, ShareLinkBundle.Status.FAILED)
|
||||||
@@ -448,10 +444,6 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
|
|||||||
assert isinstance(bundle.last_error, dict)
|
assert isinstance(bundle.last_error, dict)
|
||||||
self.assertEqual(bundle.last_error.get("message"), "zip failure")
|
self.assertEqual(bundle.last_error.get("message"), "zip failure")
|
||||||
self.assertEqual(bundle.last_error.get("exception_type"), "RuntimeError")
|
self.assertEqual(bundle.last_error.get("exception_type"), "RuntimeError")
|
||||||
scratch_zips = list(Path(settings.SCRATCH_DIR).glob("*.zip"))
|
|
||||||
self.assertTrue(scratch_zips)
|
|
||||||
for path in scratch_zips:
|
|
||||||
path.unlink(missing_ok=True)
|
|
||||||
|
|
||||||
def test_build_share_link_bundle_missing_bundle_noop(self) -> None:
|
def test_build_share_link_bundle_missing_bundle_noop(self) -> None:
|
||||||
# Should not raise when bundle does not exist
|
# Should not raise when bundle does not exist
|
||||||
|
|||||||
@@ -1256,36 +1256,3 @@ class TestIndexPageSize:
|
|||||||
|
|
||||||
assert page_size_of(legacy_page_size_db) == DB_PAGE_SIZE
|
assert page_size_of(legacy_page_size_db) == DB_PAGE_SIZE
|
||||||
assert DocumentChunksTable.count(store.client) == 2
|
assert DocumentChunksTable.count(store.client) == 2
|
||||||
|
|
||||||
|
|
||||||
def test_open_connection_closes_connection_when_setup_fails(
|
|
||||||
tmp_path: Path,
|
|
||||||
mocker: MockerFixture,
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
GIVEN a table setup step that fails after the connection was opened
|
|
||||||
WHEN the store is created
|
|
||||||
THEN the setup error propagates
|
|
||||||
AND the connection that was opened is closed, not leaked
|
|
||||||
"""
|
|
||||||
opened: list[sqlite3.Connection] = []
|
|
||||||
real_connect = sqlite3.connect
|
|
||||||
|
|
||||||
def recording_connect(*args, **kwargs) -> sqlite3.Connection:
|
|
||||||
conn = real_connect(*args, **kwargs)
|
|
||||||
opened.append(conn)
|
|
||||||
return conn
|
|
||||||
|
|
||||||
mocker.patch("paperless_ai.vector_store.sqlite3.connect", recording_connect)
|
|
||||||
mocker.patch.object(
|
|
||||||
DocumentMetaTable,
|
|
||||||
"create",
|
|
||||||
side_effect=RuntimeError("setup failed"),
|
|
||||||
)
|
|
||||||
|
|
||||||
with pytest.raises(RuntimeError, match="setup failed"):
|
|
||||||
PaperlessSqliteVecVectorStore(uri=str(tmp_path))
|
|
||||||
|
|
||||||
assert len(opened) == 1
|
|
||||||
with pytest.raises(sqlite3.ProgrammingError):
|
|
||||||
opened[0].execute("SELECT 1")
|
|
||||||
@@ -4,7 +4,6 @@ import sqlite3
|
|||||||
import struct
|
import struct
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
from contextlib import ExitStack
|
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from types import TracebackType
|
from types import TracebackType
|
||||||
@@ -213,38 +212,33 @@ class PaperlessSqliteVecVectorStore(BasePydanticVectorStore):
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _open_connection(db_path: str) -> sqlite3.Connection:
|
def _open_connection(db_path: str) -> sqlite3.Connection:
|
||||||
with ExitStack() as stack:
|
conn = sqlite3.connect(
|
||||||
conn = sqlite3.connect(
|
db_path,
|
||||||
db_path,
|
timeout=30,
|
||||||
timeout=30,
|
isolation_level=None, # autocommit; explicit transactions below
|
||||||
isolation_level=None, # autocommit; explicit transactions below
|
)
|
||||||
)
|
conn.row_factory = sqlite3.Row
|
||||||
# Closes the connection (and its WAL/SHM handles) if any setup step
|
conn.enable_load_extension(True) # noqa: FBT003
|
||||||
# below raises. pop_all() disarms it once setup has succeeded.
|
sqlite_vec.load(conn)
|
||||||
stack.callback(conn.close)
|
conn.enable_load_extension(False) # noqa: FBT003
|
||||||
conn.row_factory = sqlite3.Row
|
conn.execute(f"PRAGMA page_size={DB_PAGE_SIZE}")
|
||||||
conn.enable_load_extension(True) # noqa: FBT003
|
conn.execute("PRAGMA journal_mode=WAL")
|
||||||
sqlite_vec.load(conn)
|
conn.execute("PRAGMA synchronous=NORMAL")
|
||||||
conn.enable_load_extension(False) # noqa: FBT003
|
IndexMetaTable.create(conn)
|
||||||
conn.execute(f"PRAGMA page_size={DB_PAGE_SIZE}")
|
# vec0 metadata columns only get an efficient lookup path inside a
|
||||||
conn.execute("PRAGMA journal_mode=WAL")
|
# KNN (MATCH) query; a plain `WHERE document_id = ?` is a full table
|
||||||
conn.execute("PRAGMA synchronous=NORMAL")
|
# scan regardless of index size. This plain, indexed table is how
|
||||||
IndexMetaTable.create(conn)
|
# delete()/upsert_document() find a document's chunk ids without
|
||||||
# vec0 metadata columns only get an efficient lookup path inside a
|
# that scan.
|
||||||
# KNN (MATCH) query; a plain `WHERE document_id = ?` is a full table
|
DocumentChunksTable.create(conn)
|
||||||
# scan regardless of index size. This plain, indexed table is how
|
# modified used to be a vec0 metadata column, but vec0 only inlines
|
||||||
# delete()/upsert_document() find a document's chunk ids without
|
# TEXT metadata up to 12 bytes -- an ISO timestamp is always longer,
|
||||||
# that scan.
|
# so every read recompiled and stepped a fresh SQL statement per row.
|
||||||
DocumentChunksTable.create(conn)
|
# It was never filtered on inside a KNN query either, so it never
|
||||||
# modified used to be a vec0 metadata column, but vec0 only inlines
|
# needed to be a vec0 column at all. One row per document here (not
|
||||||
# TEXT metadata up to 12 bytes -- an ISO timestamp is always longer,
|
# per chunk, like document_chunks), since every chunk of a document
|
||||||
# so every read recompiled and stepped a fresh SQL statement per row.
|
# shares the same modified value -- see get_modified_times().
|
||||||
# It was never filtered on inside a KNN query either, so it never
|
DocumentMetaTable.create(conn)
|
||||||
# needed to be a vec0 column at all. One row per document here (not
|
|
||||||
# per chunk, like document_chunks), since every chunk of a document
|
|
||||||
# shares the same modified value -- see get_modified_times().
|
|
||||||
DocumentMetaTable.create(conn)
|
|
||||||
stack.pop_all()
|
|
||||||
return conn
|
return conn
|
||||||
|
|
||||||
@property
|
@property
|
||||||
|
|||||||
Reference in new issue
Block a user