Coverage for app / router / app / files / router.py: 98%

116 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2Uploaded documents — `/app/files`. 

3 

4A document belongs to the workspace it was uploaded in, and every chat in 

5that workspace can attach it (``app/services/uploads.py``). Uploading needs a 

6writer of Knowledge in an organisation or project; deleting, its uploader 

7(as a writer) or an editor. Each upload and deletion is an edit-history 

8version naming who did it, readable at ``/files/{id}/history``. 

9 

10An upload answers before its text is read (``status`` ``reading``), and a 

11chat asks ``GET /files/{id}`` until it is ``ready`` or ``failed``. The file 

12as uploaded is kept, and ``GET /files/{id}/content`` serves it. 

13""" 

14 

15import logging 

16from typing import Optional 

17from uuid import UUID 

18 

19from fastapi import ( 

20 APIRouter, 

21 BackgroundTasks, 

22 Depends, 

23 File, 

24 HTTPException, 

25 UploadFile, 

26 status, 

27) 

28from fastapi.responses import StreamingResponse 

29from pydantic import BaseModel 

30from sqlalchemy.orm import Session 

31 

32from app.db.postgres.enums import HistoryEnum, UploadEnum 

33from app.db.postgres.models import UploadedFile, User 

34from app.dependency.base import get_db 

35from app.dependency.resource_access import ( 

36 list_scope, 

37 verify_resource_access, 

38 verify_resource_read, 

39) 

40from app.dependency.user.context import get_current_user 

41from app.dependency.workspace import owner_for, request_workspace, requested_workspace 

42from app.router.app.history.router import register_history_routes 

43from app.services import history as history_service 

44from app.services import uploads 

45from app.services.workspace import home_of 

46from app.util import minio_client 

47from app.util.http_headers import UNTRUSTED_CONTENT_HEADERS, content_disposition 

48from app.util.time import UTCDateTime 

49 

50logger = logging.getLogger(__name__) 

51 

52files_router = APIRouter(prefix="/files", tags=["App - Files"]) 

53 

54 

55# ── Schemas ──────────────────────────────────────────────────────────────────── 

56 

57 

58class Uploader(BaseModel): 

59 id: UUID 

60 name: Optional[str] = None 

61 email: Optional[str] = None 

62 

63 

64class UploadedFileOut(BaseModel): 

65 id: UUID 

66 name: str 

67 mime_type: Optional[str] = None 

68 created_at: UTCDateTime 

69 #: Who uploaded it — the actor on its first edit-history version. None 

70 #: when that account is gone. 

71 uploaded_by: Optional[Uploader] = None 

72 #: Whether the caller may delete it: its uploader (a writer of 

73 #: Knowledge) or an editor, in a shared workspace; always in Personal. 

74 can_delete: bool = False 

75 #: How far reading its text got: a chat can attach it once ``ready``. 

76 status: UploadEnum.Status = UploadEnum.Status.ready 

77 #: Why no text could be read, when ``failed``. 

78 error: Optional[str] = None 

79 #: The original's size; None for one uploaded before originals were kept. 

80 size_bytes: Optional[int] = None 

81 #: Whether ``GET /files/{id}/content`` can serve the file as uploaded. 

82 has_original: bool = False 

83 

84 

85class FileListResponse(BaseModel): 

86 files: list[UploadedFileOut] 

87 

88 

89def _out( 

90 record: UploadedFile, uploader: Optional[User], can_delete: bool 

91) -> UploadedFileOut: 

92 state, error = uploads.status_of(record) 

93 return UploadedFileOut( 

94 id=record.id, 

95 name=record.name, 

96 mime_type=record.mime_type, 

97 created_at=record.created_at, 

98 uploaded_by=Uploader(id=uploader.id, name=uploader.name, email=uploader.email) 

99 if uploader is not None 

100 else None, 

101 can_delete=can_delete, 

102 status=state, 

103 error=error, 

104 size_bytes=record.size_bytes, 

105 has_original=bool(record.object_key), 

106 ) 

107 

108 

109def _visible(db: Session, file_id: UUID, current_user: User) -> UploadedFile: 

110 """The document, or "not found" — never "forbidden": a document in a 

111 workspace the caller cannot see is that workspace's business.""" 

112 record = db.get(UploadedFile, file_id) 

113 try: 

114 if record is None: 

115 raise HTTPException(status_code=status.HTTP_404_NOT_FOUND) 

116 verify_resource_read(record, current_user, db) 

117 except HTTPException: 

118 raise HTTPException( 

119 status_code=status.HTTP_404_NOT_FOUND, detail="File not found" 

120 ) from None 

121 return record 

122 

123 

124# ── Endpoints ────────────────────────────────────────────────────────────────── 

125 

126 

127@files_router.post( 

128 "/upload", response_model=UploadedFileOut, status_code=status.HTTP_201_CREATED 

129) 

130async def upload_file( 

131 background_tasks: BackgroundTasks, 

132 file: UploadFile = File(...), 

133 db: Session = Depends(get_db), 

134 current_user: User = Depends(get_current_user), 

135): 

136 """ 

137 Upload a single file into the request workspace's library. 

138 

139 The file is kept as it came (``uploads.object_key``) and its text is 

140 read after answering (``uploads.read``). Returns a file_id that a chat 

141 in the workspace passes instead of re-uploading, once 

142 ``GET /files/{id}`` says it is ``ready``. 

143 

144 It was read before answering, and docling takes minutes on a long PDF: 

145 the request outlived svc-bff's 20 s and Cloudflare's 100 s, and a 

146 document that could not be read was stored empty, for a chat to attach 

147 as a blank. 

148 """ 

149 # Before the file is read: who may add to this library is the 

150 # workspace's call (a writer of Knowledge in an organisation or project). 

151 owner = owner_for(db, current_user, model=UploadedFile) 

152 name = file.filename or "file" 

153 content = await file.read() 

154 if not content: 

155 raise HTTPException( 

156 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

157 detail="The file is empty.", 

158 ) 

159 if len(content) > uploads.MAX_UPLOAD_BYTES: 

160 raise HTTPException( 

161 status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, 

162 detail=f"The file is larger than {uploads.MAX_UPLOAD_BYTES // (1024 * 1024)} MB.", 

163 ) 

164 

165 record = UploadedFile( 

166 name=name, 

167 content="", 

168 mime_type=file.content_type, 

169 status=UploadEnum.Status.reading, 

170 size_bytes=len(content), 

171 **owner, 

172 ) 

173 db.add(record) 

174 db.flush() 

175 key = uploads.object_key(record.id) 

176 try: 

177 uploads.store_original(key, content, name) 

178 except Exception: 

179 db.rollback() 

180 logger.exception("Could not store an upload's original") 

181 raise HTTPException( 

182 status_code=status.HTTP_502_BAD_GATEWAY, 

183 detail="The file could not be stored. Nothing was saved; try again.", 

184 ) from None 

185 record.object_key = key 

186 history_service.record_version( 

187 db, 

188 resource_type=HistoryEnum.ResourceType.uploaded_file, 

189 model=UploadedFile, 

190 resource=record, 

191 action=HistoryEnum.Action.created, 

192 actor=current_user, 

193 ) 

194 try: 

195 db.commit() 

196 except Exception: 

197 # Nothing names the stored copy now: it goes too. 

198 db.rollback() 

199 uploads.remove_original(key) 

200 raise 

201 db.refresh(record) 

202 background_tasks.add_task( 

203 uploads.read, 

204 record.id, 

205 current_user.id, 

206 content, 

207 name, 

208 file.content_type or "application/octet-stream", 

209 ) 

210 return _out(record, current_user, can_delete=True) 

211 

212 

213@files_router.get("", response_model=FileListResponse) 

214def list_files( 

215 db: Session = Depends(get_db), 

216 current_user: User = Depends(get_current_user), 

217): 

218 """The request workspace's documents, newest first, each with who 

219 uploaded it and whether the caller may delete it.""" 

220 records = ( 

221 db.query(UploadedFile) 

222 .filter( 

223 list_scope(UploadedFile, current_user, db, workspace=requested_workspace()) 

224 ) 

225 .order_by(UploadedFile.created_at.desc()) 

226 .all() 

227 ) 

228 creators = uploads.uploaders(db, records) 

229 allowed = uploads.deletable( 

230 db, current_user, request_workspace(db, current_user), records, creators 

231 ) 

232 return FileListResponse( 

233 files=[_out(r, creators.get(r.id), r.id in allowed) for r in records] 

234 ) 

235 

236 

237@files_router.get("/{file_id}", response_model=UploadedFileOut) 

238def get_file( 

239 file_id: UUID, 

240 db: Session = Depends(get_db), 

241 current_user: User = Depends(get_current_user), 

242): 

243 """One document, and how far reading its text has got. 

244 

245 A chat asks until it is ``ready``, or says why it ``failed``. One the 

246 caller cannot see is "not found".""" 

247 record = _visible(db, file_id, current_user) 

248 creators = uploads.uploaders(db, [record]) 

249 allowed = uploads.deletable( 

250 db, current_user, home_of(db, record), [record], creators 

251 ) 

252 return _out(record, creators.get(record.id), record.id in allowed) 

253 

254 

255@files_router.get("/{file_id}/content") 

256def download_file( 

257 file_id: UUID, 

258 db: Session = Depends(get_db), 

259 current_user: User = Depends(get_current_user), 

260): 

261 """The document as it was uploaded, to save or open — for anyone who can 

262 attach it. Served as the person's bytes, not the platform's: a download, 

263 sandboxed, its type read from its name.""" 

264 record = _visible(db, file_id, current_user) 

265 if not record.object_key: 

266 raise HTTPException( 

267 status_code=status.HTTP_404_NOT_FOUND, 

268 detail="This document was uploaded before originals were kept; only its text is.", 

269 ) 

270 try: 

271 chunks = minio_client.stream(record.object_key) 

272 except Exception as exc: 

273 if minio_client.is_missing(exc): 

274 raise HTTPException( 

275 status_code=status.HTTP_404_NOT_FOUND, 

276 detail="The stored file is missing.", 

277 ) from None 

278 logger.exception("Could not read an upload's stored original") 

279 raise HTTPException( 

280 status_code=status.HTTP_502_BAD_GATEWAY, 

281 detail="Could not retrieve the file from storage.", 

282 ) from None 

283 return StreamingResponse( 

284 chunks, 

285 media_type=uploads.media_type(record.name), 

286 headers={ 

287 "Content-Disposition": content_disposition(record.name), 

288 **UNTRUSTED_CONTENT_HEADERS, 

289 }, 

290 ) 

291 

292 

293@files_router.delete("/{file_id}", status_code=status.HTTP_204_NO_CONTENT) 

294def delete_file( 

295 file_id: UUID, 

296 db: Session = Depends(get_db), 

297 current_user: User = Depends(get_current_user), 

298): 

299 """Delete a document — its uploader (a writer of Knowledge) or an editor, 

300 in a shared workspace. Its history stays, without the text; its stored 

301 original goes with it. 

302 

303 One the caller cannot see is "not found", never "forbidden": its 

304 existence is another workspace's business. One they can see but may not 

305 delete is a 403 that says why. 

306 """ 

307 record = _visible(db, file_id, current_user) 

308 verify_resource_access(record, current_user, db) 

309 key = record.object_key 

310 history_service.record_version( 

311 db, 

312 resource_type=HistoryEnum.ResourceType.uploaded_file, 

313 model=UploadedFile, 

314 resource=record, 

315 action=HistoryEnum.Action.deleted, 

316 actor=current_user, 

317 ) 

318 db.delete(record) 

319 db.commit() 

320 uploads.remove_original(key) 

321 

322 

323register_history_routes( 

324 files_router, 

325 resource_type=HistoryEnum.ResourceType.uploaded_file, 

326 model=UploadedFile, 

327 not_found_detail="File not found", 

328 # Any member who can attach a document can see who uploaded it. 

329 access_check=verify_resource_read, 

330)