Coverage for app / services / uploads.py: 95%
134 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Uploaded documents — a workspace's library of files parsed for chat.
4A document belongs to the workspace it was uploaded in
5(``app/services/workspace.py``), like any resource: a person's Personal
6library holds their own, and an organisation's or project's is shared by its
7members, in the Knowledge area (``app/services/access.py``) — a reader
8attaches a document to a chat, a writer uploads and deletes their own, an
9editor deletes any. Who uploaded one is the actor on its ``created``
10edit-history version, which outlives the document and the uploader's
11membership alike.
13A chat reads only its own workspace's documents: an id from anywhere else is
14left out, as if it did not exist.
16Its text is read after the upload has answered (:func:`read`): docling takes
17minutes on a long PDF on a CPU host, past svc-bff's 20 s and Cloudflare's
18100 s for one request. Until it is ``ready`` a chat refuses it
19(:class:`DocumentsNotReady`) rather than leaving it out, or the agent would
20answer as if it had read it.
22The file as uploaded is kept in the object store (:func:`object_key`), so
23it can be opened again from any conversation (``GET /files/{id}/content``).
24"""
26from __future__ import annotations
28import asyncio
29import hashlib
30import logging
31import mimetypes
32from collections.abc import Iterable, Sequence
33from datetime import timedelta
34from typing import Any
35from uuid import UUID
37from sqlalchemy.orm import Session
39from app.db.postgres.engine import SessionLocal
40from app.db.postgres.enums import HistoryEnum, UploadEnum
41from app.db.postgres.models import ResourceVersion, UploadedFile, User
42from app.services.knowledge import file_types
43from app.util import docling_client, minio_client
44from app.util.time import as_utc, aware_utcnow
46logger = logging.getLogger(__name__)
48#: The most one upload may be: a knowledge source's limit per file. nginx
49#: caps a request body lower; this is svc-core's own door.
50MAX_UPLOAD_BYTES = file_types.MAX_FILE_SIZE
53def object_key(file_id: UUID) -> str:
54 """Where an upload's original is stored: by its id, never by the name it
55 came with, so no name can reach another object."""
56 return f"uploads/{file_id}/original"
59def media_type(name: str) -> str:
60 """The type a stored original is served as: read from its name, never
61 from what the uploading client declared."""
62 return mimetypes.guess_type(name)[0] or "application/octet-stream"
65def store_original(key: str, data: bytes, name: str) -> None:
66 """Keep an upload's bytes. Raises when the store refuses them."""
67 minio_client.put_named(key, data, media_type(name))
70def remove_original(key: str | None) -> None:
71 """Remove an upload's stored original, when it has one. Best effort: a
72 copy left behind is logged, never a reason to fail the request."""
73 if not key:
74 return
75 try:
76 minio_client.delete(key)
77 except Exception:
78 logger.exception("Could not remove an upload's stored original")
81#: Why a document has no text; a chat shows it after the file's name. Never
82#: an exception's text.
83UNREADABLE = (
84 "The document reader is unavailable or could not convert it. Try "
85 "uploading it again later."
86)
87NO_TEXT = "It has no text that could be read."
88INTERRUPTED = "It was still being read when the service restarted. Upload it again."
90#: A document still ``reading`` this long after its upload was being read by
91#: a process that has gone, since a restart drops the background task.
92#: docling gives up on one conversion at ``DOCLING_TIMEOUT_S``, so twice that
93#: is past anything it could still be waiting on.
94ABANDONED_AFTER = timedelta(seconds=2 * docling_client.DOCLING_TIMEOUT_S)
97def fingerprint(text: str) -> str:
98 """The SHA-256 of a document's extracted text — what its edit history
99 keeps in place of the text."""
100 return hashlib.sha256(text.encode("utf-8")).hexdigest()
103def status_of(row: Any) -> tuple[UploadEnum.Status, str | None]:
104 """How far reading ``row``'s text got, and why it failed. A read the
105 process lost reads as failed, without a write."""
106 status = UploadEnum.Status(getattr(row, "status", None) or UploadEnum.Status.ready)
107 created = getattr(row, "created_at", None)
108 if (
109 status is UploadEnum.Status.reading
110 and created is not None
111 and as_utc(created) < aware_utcnow() - ABANDONED_AFTER
112 ):
113 return UploadEnum.Status.failed, INTERRUPTED
114 return status, getattr(row, "error", None)
117async def read(
118 file_id: UUID, uploader_id: UUID, content: bytes, name: str, mime_type: str
119) -> None:
120 """Read an upload's text and settle its row: ``ready`` with the text, or
121 ``failed`` with why. Runs after the upload has answered (a FastAPI
122 background task), so it opens its own session."""
123 error: str | None = None
124 try:
125 chunks = await docling_client.parse_document(content, name, mime_type)
126 except docling_client.DocumentUnreadable:
127 # docling_client has logged why, as a warning.
128 chunks, error = [], UNREADABLE
129 except Exception:
130 logger.exception("Reading an uploaded %s failed", mime_type)
131 chunks, error = [], UNREADABLE
132 text = "\n\n".join(chunk.text for chunk in chunks if chunk.text.strip())
133 if not text and error is None:
134 error = NO_TEXT
135 await asyncio.to_thread(_settle, file_id, uploader_id, text, error)
138def _settle(file_id: UUID, uploader_id: UUID, text: str, error: str | None) -> None:
139 """Write what :func:`read` found, as an edit by the uploader. A document
140 deleted meanwhile is left gone; one that cannot be written stays
141 ``reading`` until :func:`status_of` calls it lost."""
142 from app.services import history
144 db = SessionLocal()
145 try:
146 row = db.get(UploadedFile, file_id)
147 if row is None or row.status != UploadEnum.Status.reading:
148 return
149 row.content = text
150 row.content_sha256 = fingerprint(text) if error is None else None
151 row.status = UploadEnum.Status.failed if error else UploadEnum.Status.ready
152 row.error = error
153 history.record_version(
154 db,
155 resource_type=HistoryEnum.ResourceType.uploaded_file,
156 model=UploadedFile,
157 resource=row,
158 action=HistoryEnum.Action.updated,
159 actor=db.get(User, uploader_id),
160 )
161 db.commit()
162 except Exception:
163 db.rollback()
164 logger.exception("Could not record an uploaded document's text")
165 finally:
166 db.close()
169class DocumentsNotReady(Exception):
170 """A chat named documents whose text is not there: still being read, or
171 never will be. ``message`` says which, and what to do."""
173 def __init__(self, reading: list[str], failed: list[str]):
174 self.reading = reading
175 self.failed = failed
176 parts = []
177 if reading:
178 parts.append(
179 f"Still reading {', '.join(reading)}: send again once it's ready."
180 )
181 if failed:
182 parts.append(
183 f"{', '.join(failed)} could not be read: remove it and attach it again."
184 )
185 self.message = " ".join(parts)
186 super().__init__(self.message)
189def _ids(raw: Iterable[Any]) -> list[UUID]:
190 out: list[UUID] = []
191 for value in raw:
192 try:
193 out.append(value if isinstance(value, UUID) else UUID(str(value)))
194 except (TypeError, ValueError):
195 continue
196 return out
199def as_ids(raw: Iterable[Any]) -> list[UUID]:
200 """``raw`` as document ids, each once, in the order given; what is not an
201 id is left out."""
202 return list(dict.fromkeys(_ids(raw)))
205def in_workspace(db: Session, ids: Iterable[UUID], ws: Any) -> dict[UUID, UploadedFile]:
206 """The documents among ``ids`` that workspace ``ws`` holds, by id."""
207 from app.services.workspace import in_scope
209 wanted = list(ids)
210 if not wanted:
211 return {}
212 return {
213 row.id: row
214 for row in db.query(UploadedFile)
215 .filter(UploadedFile.id.in_(wanted), in_scope(UploadedFile, ws, system=False))
216 .all()
217 }
220def ready_rows(db: Session, raw_ids: Iterable[Any], ws: Any) -> list[UploadedFile]:
221 """The documents ``raw_ids`` name that workspace ``ws`` holds, in the
222 order asked. Another workspace's document — or an id that is not one —
223 is left out. One of its own without its text yet, or that could not be
224 read, raises :class:`DocumentsNotReady`."""
225 ids = as_ids(raw_ids)
226 rows = in_workspace(db, ids, ws)
227 found = [rows[i] for i in ids if i in rows]
228 states = [status_of(row)[0] for row in found]
229 reading = [r.name for r, s in zip(found, states) if s is UploadEnum.Status.reading]
230 failed = [r.name for r, s in zip(found, states) if s is UploadEnum.Status.failed]
231 if reading or failed:
232 raise DocumentsNotReady(reading, failed)
233 return found
236def uploaders(db: Session, files: Sequence[UploadedFile]) -> dict[UUID, User | None]:
237 """Who uploaded each of ``files``: the actor on its ``created`` version,
238 in two queries for the whole list."""
239 if not files:
240 return {}
241 created = dict(
242 db.query(ResourceVersion.resource_id, ResourceVersion.actor_user_id)
243 .filter(
244 ResourceVersion.resource_type == HistoryEnum.ResourceType.uploaded_file,
245 ResourceVersion.resource_id.in_([f.id for f in files]),
246 ResourceVersion.action == HistoryEnum.Action.created,
247 )
248 .all()
249 )
250 actor_ids = {a for a in created.values() if a}
251 users = (
252 {u.id: u for u in db.query(User).filter(User.id.in_(actor_ids)).all()}
253 if actor_ids
254 else {}
255 )
256 return {f.id: users.get(created.get(f.id)) for f in files}
259def deletable(
260 db: Session,
261 user: Any,
262 ws: Any,
263 files: Sequence[UploadedFile],
264 creators: dict[UUID, User | None],
265) -> set[UUID]:
266 """The ids among ``files`` (all of workspace ``ws``) that ``user`` may
267 delete — the rule ``verify_resource_access`` applies to each, read once
268 for the list: anything for an editor of Knowledge, their own for a
269 writer, nothing for a reader."""
270 from app.services import access, membership
271 from app.services.workspace import WorkspaceKind
273 ids = {f.id for f in files}
274 if getattr(user, "is_superuser", False) or ws.kind is WorkspaceKind.personal:
275 return ids
276 scope = (
277 membership.ORGANISATION
278 if ws.kind is WorkspaceKind.organisation
279 else membership.PROJECT
280 )
281 m = membership.effective_membership(db, scope, ws.id, user.id)
282 if m is None:
283 return set()
284 kind = access.kind_of(UploadedFile)
285 level = access.effective(m)[kind.area]
286 if level >= access.AccessLevel.editor:
287 return ids
288 if level >= kind.change_own_level:
289 return {
290 f.id
291 for f in files
292 if (creator := creators.get(f.id)) is not None and creator.id == user.id
293 }
294 return set()