- 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/
118 lines
6.1 KiB
Python
118 lines
6.1 KiB
Python
"""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
|