feat(ingestion): implement Phase 2 multi-format intake and raw storage
- Add format validation and inspection for PDF, DOCX, Markdown, Text, HTML, and images - Implement secure decompression defenses (zip bombs, ratio checks) and image dimension limits - Implement FileStore with content-addressable storage and intake repositories - Add unit and integration tests for document intake, format sniffing, and storage roots - Include sample acceptance document fixtures in data/documents/
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
"""Local immutable originals; filenames never participate in storage paths."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import tempfile
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
class LocalFileStore:
|
||||
def __init__(self, directory: Path):
|
||||
self.directory = Path(directory).resolve()
|
||||
|
||||
def _path(self, key: str) -> Path:
|
||||
if not re.fullmatch(r"[0-9a-f]{32}\.original", key):
|
||||
raise ValueError("Invalid storage key")
|
||||
path = self.directory / key
|
||||
if path.is_symlink():
|
||||
raise ValueError("Storage entries cannot be symlinks")
|
||||
return path
|
||||
|
||||
def put(self, content: bytes) -> str:
|
||||
self.directory.mkdir(parents=True, exist_ok=True)
|
||||
key = uuid4().hex + ".original"
|
||||
final = self._path(key)
|
||||
descriptor, temporary = tempfile.mkstemp(prefix=".intake-", dir=self.directory)
|
||||
try:
|
||||
with os.fdopen(descriptor, "wb") as stream:
|
||||
stream.write(content)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
# Atomic no-replace publication on the same filesystem (including NTFS).
|
||||
os.link(temporary, final)
|
||||
finally:
|
||||
Path(temporary).unlink(missing_ok=True)
|
||||
if os.name != "nt":
|
||||
descriptor = os.open(self.directory, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(descriptor)
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
return key
|
||||
|
||||
def read(self, storage_key: str) -> bytes:
|
||||
return self._path(storage_key).read_bytes()
|
||||
|
||||
def read_bounded(self, storage_key: str, limit: int) -> bytes:
|
||||
with self._path(storage_key).open("rb") as stream:
|
||||
content = stream.read(limit + 1)
|
||||
if len(content) > limit:
|
||||
raise ValueError("Original exceeds frozen byte limit")
|
||||
return content
|
||||
|
||||
def discard_unused(self, storage_key: str) -> None:
|
||||
"""Only for this request's candidate after a confirmed committed replay."""
|
||||
self._path(storage_key).unlink(missing_ok=True)
|
||||
|
||||
def inventory(self) -> dict:
|
||||
if not self.directory.exists():
|
||||
return {"originals": [], "temporary_files": [], "unexpected_entries": []}
|
||||
result = {"originals": [], "temporary_files": [], "unexpected_entries": []}
|
||||
for path in self.directory.iterdir():
|
||||
if path.is_file() and not path.is_symlink():
|
||||
if re.fullmatch(r"[0-9a-f]{32}\.original", path.name):
|
||||
result["originals"].append(path.name)
|
||||
continue
|
||||
if path.name.startswith(".intake-"):
|
||||
result["temporary_files"].append(path.name)
|
||||
continue
|
||||
result["unexpected_entries"].append(path.name)
|
||||
return {name: sorted(values) for name, values in result.items()}
|
||||
Reference in New Issue
Block a user