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:
amirhosein mazaheri
2026-10-07 16:20:41 +03:30
parent 0a998ac94a
commit b036912293
16 changed files with 1714 additions and 0 deletions
+70
View File
@@ -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()}
+117
View File
@@ -0,0 +1,117 @@
"""Intake-specific transactional PostgreSQL boundary. No file or provider I/O."""
import json
from uuid import uuid4
from sqlalchemy import text
from app.infrastructure.database import check_compatibility
from app.modules.documents.errors import IntakeError
def administrator(connection, user_id):
row = connection.execute(text("""
SELECT organization_id FROM users
WHERE id=:id AND role='admin' AND is_enabled FOR SHARE
"""), {"id": user_id}).mappings().one_or_none()
if row is None:
raise IntakeError("ADMINISTRATOR_REQUIRED", "Enabled administrator required")
return row["organization_id"]
def document_status(connection, organization_id, document_id):
row = connection.execute(text("""
SELECT d.*, row_to_json(j) AS job FROM documents d
JOIN ingestion_jobs j ON j.document_id=d.id AND j.organization_id=d.organization_id
WHERE d.organization_id=:org AND d.id=:id
"""), {"org": organization_id, "id": document_id}).mappings().one_or_none()
if row is None:
raise IntakeError("DOCUMENT_NOT_FOUND", "Document not found")
result = dict(row)
result["searchable"] = (result["status"] == "ready" and result["is_active"]
and result["deleted_at"] is None
and result["content_purged_at"] is None)
return result
class SqlIntakeRepository:
def __init__(self, engine):
self.engine = engine
def lookup(self, settings, administrator_id, request_id):
with self.engine.begin() as connection:
check_compatibility(connection, settings.embedding_profile)
org = administrator(connection, administrator_id)
previous = connection.execute(text("""
SELECT id,size_bytes,upload_payload_hash FROM documents
WHERE organization_id=:org AND upload_request_id=:request
"""), {"org": org, "request": request_id}).mappings().one_or_none()
return org, previous
def replay(self, org, administrator_id, previous, submitted_hash):
with self.engine.begin() as connection:
if administrator(connection, administrator_id) != org:
raise IntakeError("DOCUMENT_NOT_FOUND", "Document not found")
if submitted_hash != previous["upload_payload_hash"]:
raise IntakeError("IDEMPOTENCY_CONFLICT", "Key already used with a different payload")
result = document_status(connection, org, previous["id"])
return result
def create(self, settings, prepared, key, administrator_id, request_id, expected_org):
document_id, job_id = uuid4(), uuid4()
# Any exception (including ambiguous commit) retains the candidate as an orphan.
# Never risk deleting bytes referenced by a possibly committed document.
with self.engine.begin() as connection:
org = administrator(connection, administrator_id)
if org != expected_org:
raise IntakeError("DOCUMENT_NOT_FOUND", "Document not found")
inserted = connection.execute(text("""
INSERT INTO documents
(id,organization_id,uploaded_by,title,original_filename,upload_request_id,
upload_payload_hash,storage_key,file_sha256,mime_type,size_bytes,processing_profile)
VALUES (:id,:org,:actor,:title,:filename,:request,:hash,:key,:sha,:mime,:size,
CAST(:profile AS jsonb))
ON CONFLICT (organization_id,upload_request_id) DO NOTHING RETURNING id
"""), {"id": document_id, "org": org, "actor": administrator_id,
"title": prepared["title"], "filename": prepared["filename"],
"request": request_id, "hash": prepared["payload_hash"], "key": key,
"sha": prepared["sha"], "mime": prepared["mime"],
"size": len(prepared["content"]),
"profile": json.dumps(settings.processing_profile())}).scalar_one_or_none()
replayed = inserted is None
if replayed:
previous = connection.execute(text("""
SELECT id,upload_payload_hash FROM documents
WHERE organization_id=:org AND upload_request_id=:request
"""), {"org": org, "request": request_id}).mappings().one()
if previous["upload_payload_hash"] != prepared["payload_hash"]:
conflict = True
result = None
else:
conflict = False
result = document_status(connection, org, previous["id"])
else:
conflict = False
connection.execute(text("""
INSERT INTO ingestion_jobs(id,organization_id,document_id)
VALUES (:id,:org,:document)
"""), {"id": job_id, "org": org, "document": document_id})
connection.execute(text("""
INSERT INTO audit_events
(id,organization_id,actor_user_id,action,target_id,idempotency_key,
request_hash,response_json)
VALUES (:id,:org,:actor,'upload',:document,:request,:hash,CAST(:response AS jsonb))
"""), {"id": uuid4(), "org": org, "actor": administrator_id,
"document": document_id, "request": request_id,
"hash": prepared["payload_hash"],
"response": json.dumps({"document_id": str(document_id), "job_id": str(job_id)})})
result = document_status(connection, org, document_id)
return replayed, conflict, result
def status(self, administrator_id, document_id):
with self.engine.begin() as connection:
org = administrator(connection, administrator_id)
return document_status(connection, org, document_id)
def original_references(self):
with self.engine.connect() as connection:
rows = connection.execute(text("""
SELECT id,storage_key FROM documents WHERE content_purged_at IS NULL
""")).mappings().all()
return rows