resource-engine 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. resource_engine/__init__.py +96 -0
  2. resource_engine/application/__init__.py +1 -0
  3. resource_engine/application/actions.py +48 -0
  4. resource_engine/application/context.py +111 -0
  5. resource_engine/application/events.py +54 -0
  6. resource_engine/application/hooks.py +272 -0
  7. resource_engine/application/idempotency.py +277 -0
  8. resource_engine/application/manager.py +1987 -0
  9. resource_engine/application/query.py +47 -0
  10. resource_engine/application/registry.py +137 -0
  11. resource_engine/application/relations.py +470 -0
  12. resource_engine/application/resource.py +984 -0
  13. resource_engine/application/searching.py +162 -0
  14. resource_engine/application/settings.py +169 -0
  15. resource_engine/application/slots.py +67 -0
  16. resource_engine/application/state_machines.py +177 -0
  17. resource_engine/application/timers.py +347 -0
  18. resource_engine/application/transaction.py +100 -0
  19. resource_engine/application/views.py +239 -0
  20. resource_engine/audit/__init__.py +40 -0
  21. resource_engine/audit/export.py +280 -0
  22. resource_engine/audit/history.py +165 -0
  23. resource_engine/audit/janitor.py +257 -0
  24. resource_engine/audit/model.py +98 -0
  25. resource_engine/audit/recorder.py +145 -0
  26. resource_engine/audit/resource.py +68 -0
  27. resource_engine/audit/seal.py +327 -0
  28. resource_engine/audit/sink.py +69 -0
  29. resource_engine/authz/__init__.py +72 -0
  30. resource_engine/authz/apikeys.py +300 -0
  31. resource_engine/authz/base.py +143 -0
  32. resource_engine/authz/catalog.py +291 -0
  33. resource_engine/authz/conditions.py +416 -0
  34. resource_engine/authz/config.py +77 -0
  35. resource_engine/authz/evaluator.py +382 -0
  36. resource_engine/authz/external.py +249 -0
  37. resource_engine/authz/fields.py +44 -0
  38. resource_engine/authz/model.py +145 -0
  39. resource_engine/authz/resources.py +289 -0
  40. resource_engine/authz/roles.py +101 -0
  41. resource_engine/cache.py +144 -0
  42. resource_engine/calls.py +100 -0
  43. resource_engine/capabilities.py +145 -0
  44. resource_engine/composite.py +295 -0
  45. resource_engine/documents/__init__.py +69 -0
  46. resource_engine/documents/content.py +57 -0
  47. resource_engine/documents/events.py +49 -0
  48. resource_engine/documents/janitor.py +93 -0
  49. resource_engine/documents/machine.py +38 -0
  50. resource_engine/documents/manager.py +704 -0
  51. resource_engine/documents/model.py +91 -0
  52. resource_engine/documents/pipeline.py +98 -0
  53. resource_engine/documents/processors.py +320 -0
  54. resource_engine/documents/resource.py +39 -0
  55. resource_engine/domain/__init__.py +10 -0
  56. resource_engine/domain/events.py +50 -0
  57. resource_engine/domain/exceptions.py +23 -0
  58. resource_engine/email.py +417 -0
  59. resource_engine/errors.py +562 -0
  60. resource_engine/explorer.py +133 -0
  61. resource_engine/exports.py +687 -0
  62. resource_engine/generation.py +233 -0
  63. resource_engine/i18n.py +251 -0
  64. resource_engine/identity.py +46 -0
  65. resource_engine/integration.py +80 -0
  66. resource_engine/jobs.py +390 -0
  67. resource_engine/locale/ca/LC_MESSAGES/resource_engine.mo +0 -0
  68. resource_engine/locale/ca/LC_MESSAGES/resource_engine.po +206 -0
  69. resource_engine/locale/es/LC_MESSAGES/resource_engine.mo +0 -0
  70. resource_engine/locale/es/LC_MESSAGES/resource_engine.po +206 -0
  71. resource_engine/logs.py +201 -0
  72. resource_engine/messaging/__init__.py +73 -0
  73. resource_engine/messaging/asyncapi.py +529 -0
  74. resource_engine/messaging/cloudevents.py +98 -0
  75. resource_engine/messaging/consumer.py +165 -0
  76. resource_engine/messaging/delivery.py +115 -0
  77. resource_engine/messaging/envelope.py +193 -0
  78. resource_engine/messaging/hub.py +148 -0
  79. resource_engine/messaging/inbound.py +76 -0
  80. resource_engine/messaging/inspection.py +113 -0
  81. resource_engine/messaging/janitor.py +136 -0
  82. resource_engine/messaging/live.py +179 -0
  83. resource_engine/messaging/processing.py +357 -0
  84. resource_engine/messaging/publishing.py +318 -0
  85. resource_engine/messaging/relay.py +84 -0
  86. resource_engine/messaging/worker.py +166 -0
  87. resource_engine/nosql.py +394 -0
  88. resource_engine/ports/__init__.py +13 -0
  89. resource_engine/ports/activity.py +171 -0
  90. resource_engine/ports/audit.py +42 -0
  91. resource_engine/ports/authz.py +132 -0
  92. resource_engine/ports/cache.py +41 -0
  93. resource_engine/ports/email.py +118 -0
  94. resource_engine/ports/event_publisher.py +34 -0
  95. resource_engine/ports/idempotency.py +69 -0
  96. resource_engine/ports/identity.py +112 -0
  97. resource_engine/ports/locks.py +28 -0
  98. resource_engine/ports/messaging.py +197 -0
  99. resource_engine/ports/observability.py +60 -0
  100. resource_engine/ports/ratelimit.py +59 -0
  101. resource_engine/ports/repository.py +56 -0
  102. resource_engine/ports/storage.py +93 -0
  103. resource_engine/ports/templates.py +54 -0
  104. resource_engine/ports/tracing.py +61 -0
  105. resource_engine/ports/unit_of_work.py +46 -0
  106. resource_engine/processes.py +408 -0
  107. resource_engine/py.typed +0 -0
  108. resource_engine/querying.py +319 -0
  109. resource_engine/ratelimit.py +217 -0
  110. resource_engine/reporting.py +230 -0
  111. resource_engine/schema_examples.py +51 -0
  112. resource_engine/templates.py +143 -0
  113. resource_engine/tenancy.py +68 -0
  114. resource_engine/testing/__init__.py +34 -0
  115. resource_engine/testing/activity.py +123 -0
  116. resource_engine/testing/contracts.py +1416 -0
  117. resource_engine/testing/email.py +36 -0
  118. resource_engine/testing/engine.py +40 -0
  119. resource_engine/testing/memory.py +603 -0
  120. resource_engine/testing/storage.py +110 -0
  121. resource_engine/testing/tracing.py +100 -0
  122. resource_engine/tracing.py +156 -0
  123. resource_engine/translatable.py +80 -0
  124. resource_engine/versions.py +189 -0
  125. resource_engine-0.1.0.dist-info/METADATA +36 -0
  126. resource_engine-0.1.0.dist-info/RECORD +128 -0
  127. resource_engine-0.1.0.dist-info/WHEEL +4 -0
  128. resource_engine-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,704 @@
1
+ """Document operations: attach, presigned uploads, detach, download.
2
+
3
+ They run the owner resource's lifecycle (see docs/lifecycle.md) with the
4
+ operations ``attach`` and ``detach``:
5
+
6
+ 3. validation: slot, content type, declared size (``before/after_validate``)
7
+ 4-5. open the unit of work, load the owner entity
8
+ 6. ``before_attach[:slot]`` / ``before_detach[:slot]``
9
+ 7. store the blob (a *staged effect*, deleted again on rollback) and write the
10
+ ``Document`` row in the same unit of work; replaced documents are discarded
11
+ 8. ``after_attach[:slot]`` / ``after_detach[:slot]``
12
+ 9. commit (the document becomes visible)
13
+ 10. purge discarded blobs (``on_commit``), ``after_commit`` hooks, events
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import dataclasses
19
+ import uuid
20
+ from collections.abc import AsyncIterator, Sequence
21
+ from dataclasses import dataclass
22
+ from datetime import UTC, datetime, timedelta
23
+ from typing import TYPE_CHECKING, Any, cast
24
+ from urllib.parse import quote
25
+
26
+ from pydantic import BaseModel, Field
27
+
28
+ from resource_engine.application.hooks import HookPoint
29
+ from resource_engine.application.query import ListQuery
30
+ from resource_engine.application.slots import DocumentSlot
31
+ from resource_engine.documents.events import (
32
+ DocumentAttached,
33
+ DocumentDetached,
34
+ DocumentProcessed,
35
+ DocumentRejected,
36
+ )
37
+ from resource_engine.documents.model import Document, DocumentRead, NewDocument, safe_filename
38
+ from resource_engine.errors import (
39
+ ConfigurationError,
40
+ ContentTypeNotAllowed,
41
+ DocumentNotAvailable,
42
+ DocumentSlotNotFound,
43
+ DocumentTooLarge,
44
+ EntityNotFound,
45
+ OperationNotEnabled,
46
+ RequiredDocumentMissing,
47
+ UploadNotVerified,
48
+ )
49
+ from resource_engine.ports.storage import (
50
+ BlobStore,
51
+ Content,
52
+ PresignedRequest,
53
+ SupportsPresignedUrls,
54
+ )
55
+ from resource_engine.tracing import traced
56
+
57
+ if TYPE_CHECKING:
58
+ from resource_engine.application.context import OperationContext
59
+ from resource_engine.application.manager import ResourceManager
60
+ from resource_engine.application.resource import ResourceDefinition
61
+
62
+ LIVE = ("pending", "processing", "available", "rejected")
63
+
64
+
65
+ class AttachInput(BaseModel):
66
+ """What the client sends to start an upload: the file's name, type and size."""
67
+
68
+ filename: str = Field(min_length=1, max_length=1000)
69
+ content_type: str = Field(min_length=3, max_length=255)
70
+ size: int | None = Field(default=None, ge=0)
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class UploadTicket:
75
+ """A pending document and the request the client must make to upload it."""
76
+
77
+ document: DocumentRead
78
+ upload: PresignedRequest
79
+
80
+
81
+ def _now() -> datetime:
82
+ return datetime.now(UTC)
83
+
84
+
85
+ def aware(value: datetime | None) -> datetime | None:
86
+ """Some databases (SQLite) return naive datetimes; they are stored as UTC."""
87
+ if value is not None and value.tzinfo is None:
88
+ return value.replace(tzinfo=UTC)
89
+ return value
90
+
91
+
92
+ def _actor_label(actor: Any) -> str | None:
93
+ if actor is None or isinstance(actor, str):
94
+ return actor
95
+ for attr in ("id", "sub", "username"):
96
+ value = getattr(actor, attr, None)
97
+ if value is not None:
98
+ return str(value)
99
+ return str(actor)
100
+
101
+
102
+ class DocumentManager:
103
+ """Available as ``ResourceManager.documents`` when a blob store is configured.
104
+
105
+ Args:
106
+ manager: The owning ``ResourceManager``.
107
+ store: Where contents go.
108
+ resource: Name of the registered ``DocumentResource``.
109
+ upload_ttl: Validity of presigned upload URLs and of pending documents.
110
+ download_ttl: Validity of presigned download URLs.
111
+ """
112
+
113
+ def __init__(
114
+ self,
115
+ manager: ResourceManager,
116
+ store: BlobStore,
117
+ *,
118
+ resource: str = "documents",
119
+ upload_ttl: timedelta = timedelta(minutes=15),
120
+ download_ttl: timedelta = timedelta(minutes=5),
121
+ ) -> None:
122
+ if resource not in manager.registry:
123
+ raise ConfigurationError(
124
+ f"A blob store is configured but the documents resource {resource!r} "
125
+ "is not registered",
126
+ hint="Call registry.register_documents() at bootstrap.",
127
+ doc="docs/documents.md#setup",
128
+ )
129
+ self.manager = manager
130
+ self.store = store
131
+ self.resource = resource
132
+ self.definition = manager.registry.get(resource)
133
+ assert self.definition.machine is not None
134
+ self.machine = self.definition.machine
135
+ self.upload_ttl = upload_ttl
136
+ self.download_ttl = download_ttl
137
+
138
+ # ----------------------------------------------------------------- helpers
139
+
140
+ @staticmethod
141
+ def slot(definition: ResourceDefinition, name: str) -> DocumentSlot:
142
+ """The slot ``name`` of a resource. Raises ``DocumentSlotNotFound``."""
143
+ try:
144
+ return definition.document_slots[name]
145
+ except KeyError:
146
+ raise DocumentSlotNotFound(
147
+ f"Resource {definition.name!r} has no document slot {name!r}",
148
+ hint=f"Slots: {', '.join(definition.document_slots) or '(none)'}",
149
+ ) from None
150
+
151
+ @staticmethod
152
+ def _check(slot: DocumentSlot, content_type: str, size: int | None) -> None:
153
+ if not slot.accepts(content_type):
154
+ raise ContentTypeNotAllowed(
155
+ f"Slot {slot.name!r} does not accept {content_type!r}",
156
+ hint=f"Accepted: {', '.join(slot.content_types)}",
157
+ details={"accepted": list(slot.content_types)},
158
+ )
159
+ if size is not None and size > slot.max_bytes:
160
+ raise DocumentTooLarge(
161
+ f"{size} bytes exceed the {slot.max_bytes}-byte limit of slot {slot.name!r}",
162
+ details={"max_bytes": slot.max_bytes},
163
+ )
164
+
165
+ def _repo(self, ctx: OperationContext) -> Any:
166
+ return ctx.repository(self.resource)
167
+
168
+ @staticmethod
169
+ def key(owner_resource: str, owner_id: Any, document_id: str) -> str:
170
+ """The blob key of a document: owner resource, owner id, document id."""
171
+ return f"{owner_resource}/{quote(str(owner_id), safe='')}/{document_id}"
172
+
173
+ async def _owned(
174
+ self, ctx: OperationContext, slot: str | None, statuses: Sequence[str] = LIVE
175
+ ) -> list[Document]:
176
+ filters: dict[str, Any] = {
177
+ "owner_resource": ctx.resource.name,
178
+ "owner_id": str(ctx.entity_id),
179
+ }
180
+ if slot is not None:
181
+ filters["slot"] = slot
182
+ page = await self._repo(ctx).list(ListQuery(filters=filters, limit=10_000))
183
+ return [d for d in page.items if d.status in statuses]
184
+
185
+ def _owner_context(self, doc: Document, operation: str, actor: Any) -> OperationContext:
186
+ owner = self.manager.registry.get(doc.owner_resource)
187
+ try:
188
+ owner_id = owner.id_type(doc.owner_id)
189
+ except (TypeError, ValueError):
190
+ owner_id = doc.owner_id
191
+ return self.manager._context(
192
+ owner, operation, actor=actor, entity_id=owner_id, slot=doc.slot
193
+ )
194
+
195
+ async def _get_document(self, document_id: str) -> Document:
196
+ async with self.manager._reading() as uow:
197
+ doc: Document | None = await uow.repository(self.resource).get(document_id)
198
+ # a detached copy: ORMs expire instances when the unit of work closes
199
+ doc = dataclasses.replace(doc) if doc is not None else None
200
+ if doc is None:
201
+ raise EntityNotFound(
202
+ f"Document {document_id!r} does not exist",
203
+ details={"resource": self.resource, "id": document_id},
204
+ )
205
+ return doc
206
+
207
+ # ------------------------------------------- in-transaction building blocks
208
+
209
+ async def store_in(
210
+ self,
211
+ ctx: OperationContext,
212
+ slot: DocumentSlot,
213
+ content: Content,
214
+ *,
215
+ filename: str,
216
+ content_type: str,
217
+ metadata: dict[str, Any] | None = None,
218
+ ) -> Document:
219
+ """Store content and add the row inside ``ctx``'s unit of work (steps 7)."""
220
+ doc_id = uuid.uuid4().hex
221
+ key = self.key(ctx.resource.name, ctx.entity_id, doc_id)
222
+ info = await self.store.put(
223
+ key, content, content_type=content_type, max_bytes=slot.max_bytes
224
+ )
225
+ store = self.store
226
+ ctx.on_rollback(lambda: store.delete([key]))
227
+ doc = Document(
228
+ id=doc_id,
229
+ owner_resource=ctx.resource.name,
230
+ owner_id=str(ctx.entity_id),
231
+ slot=slot.name,
232
+ filename=safe_filename(filename),
233
+ content_type=content_type,
234
+ storage_key=key,
235
+ size=info.size,
236
+ sha256=info.sha256,
237
+ created_at=_now(),
238
+ created_by=_actor_label(ctx.actor),
239
+ metadata=dict(metadata or {}),
240
+ )
241
+ await self.machine.initialize(doc)
242
+ await self._activate(ctx, slot, doc)
243
+ await self._repo(ctx).add(doc)
244
+ return doc
245
+
246
+ async def _activate(self, ctx: OperationContext, slot: DocumentSlot, doc: Document) -> None:
247
+ """pending → available/processing, replacing the slot's previous document."""
248
+ if not slot.multiple:
249
+ for old in await self._owned(ctx, slot.name):
250
+ if old.id != doc.id and old.status != "pending":
251
+ await self.discard_in(ctx, old)
252
+ await self.machine.fire(doc, "start_processing" if slot.processing else "confirm", {})
253
+ ctx.record_event(
254
+ DocumentAttached(
255
+ resource=ctx.resource.name,
256
+ entity_id=ctx.entity_id,
257
+ document_id=doc.id,
258
+ slot=slot.name,
259
+ content_type=doc.content_type,
260
+ size=doc.size,
261
+ processing=slot.processing,
262
+ )
263
+ )
264
+ ctx.extras["document"] = doc
265
+
266
+ async def discard_in(self, ctx: OperationContext, doc: Document) -> None:
267
+ """Mark ``doc`` deleted in ``ctx``'s unit of work; purge its blob after commit."""
268
+ await self.machine.fire(doc, "discard", {})
269
+ await self._repo(ctx).update(doc)
270
+ ctx.record_event(
271
+ DocumentDetached(
272
+ resource=doc.owner_resource,
273
+ entity_id=ctx.entity_id,
274
+ document_id=doc.id,
275
+ slot=doc.slot,
276
+ )
277
+ )
278
+ ctx.on_commit(lambda: self.purge([doc.id]))
279
+
280
+ async def purge(self, document_ids: Sequence[str]) -> int:
281
+ """Delete the blobs of deleted documents and record ``purged_at``."""
282
+ purged = 0
283
+ async with self.manager.uow_factory() as uow:
284
+ repo = uow.repository(self.resource)
285
+ for document_id in document_ids:
286
+ doc = await repo.get(document_id)
287
+ if doc is None or doc.status != "deleted" or doc.purged_at is not None:
288
+ continue
289
+ await self.store.delete([doc.storage_key])
290
+ doc.purged_at = _now()
291
+ await repo.update(doc)
292
+ purged += 1
293
+ await uow.commit()
294
+ return purged
295
+
296
+ async def check_required(self, ctx: OperationContext, event: str) -> None:
297
+ """Before a transition: every slot that lists it needs an available document."""
298
+ for slot in ctx.resource.document_slots.values():
299
+ if event in slot.required_for and not await self._owned(ctx, slot.name, ("available",)):
300
+ raise RequiredDocumentMissing(
301
+ f"Transition {event!r} of {ctx.resource.name} {ctx.entity_id!r} needs a "
302
+ f"document in slot {slot.name!r}",
303
+ hint=f"Attach one first (POST .../documents/{slot.name}).",
304
+ details={"slot": slot.name, "transition": event},
305
+ )
306
+
307
+ async def cascade(self, ctx: OperationContext) -> None:
308
+ """The owner is being deleted: discard all its documents."""
309
+ for doc in await self._owned(ctx, None):
310
+ await self.discard_in(ctx, doc)
311
+
312
+ # ------------------------------------------------------------- operations
313
+
314
+ @traced("attach")
315
+ async def attach(
316
+ self,
317
+ resource: Any,
318
+ entity_id: Any,
319
+ slot: str,
320
+ content: Content,
321
+ *,
322
+ filename: str,
323
+ content_type: str,
324
+ size: int | None = None,
325
+ actor: Any = None,
326
+ ) -> DocumentRead:
327
+ """Store a file through the API (streamed) and attach it to an entity."""
328
+ m = self.manager
329
+ definition = m.registry.get(resource)
330
+ slot_def = self.slot(definition, slot)
331
+ if not slot_def.allows("api"):
332
+ raise OperationNotEnabled(
333
+ f"Slot {slot!r} only accepts presigned uploads",
334
+ hint="Use request_upload() and upload directly to the store.",
335
+ )
336
+ ctx = m._context(
337
+ definition,
338
+ "attach",
339
+ actor=actor,
340
+ entity_id=entity_id,
341
+ slot=slot,
342
+ raw_input={"filename": filename, "content_type": content_type, "size": size},
343
+ )
344
+ await m._gate(ctx, f"attach:{slot}")
345
+ await m._validate(ctx, AttachInput, slot)
346
+ self._check(slot_def, ctx.data.content_type, ctx.data.size)
347
+ hooks = definition.dispatcher
348
+ async with m._transaction(ctx) as uow:
349
+ await m._load(ctx)
350
+ await m._gate_record(ctx, f"attach:{slot}", ctx.entity, input=ctx.data)
351
+ await hooks.run(HookPoint.BEFORE_ATTACH, ctx, slot)
352
+ doc = await self.store_in(
353
+ ctx,
354
+ slot_def,
355
+ content,
356
+ filename=ctx.data.filename,
357
+ content_type=ctx.data.content_type,
358
+ )
359
+ await hooks.run(HookPoint.AFTER_ATTACH, ctx, slot)
360
+ ctx.result = DocumentRead.model_validate(doc)
361
+ await m._before_commit(ctx, uow)
362
+ await uow.commit()
363
+ await m._after_commit(ctx, slot)
364
+ return cast(DocumentRead, ctx.result)
365
+
366
+ @traced("request_upload")
367
+ async def request_upload(
368
+ self,
369
+ resource: Any,
370
+ entity_id: Any,
371
+ slot: str,
372
+ *,
373
+ filename: str,
374
+ content_type: str,
375
+ size: int | None = None,
376
+ actor: Any = None,
377
+ ) -> UploadTicket:
378
+ """Create a pending document and a presigned PUT for the client.
379
+
380
+ ``before_attach`` hooks run now; ``after_attach`` hooks run on
381
+ ``confirm_upload``, when the content exists.
382
+ """
383
+ m = self.manager
384
+ if not isinstance(self.store, SupportsPresignedUrls):
385
+ raise ConfigurationError(
386
+ f"{type(self.store).__name__} cannot presign uploads",
387
+ hint="Use a store with presigned URLs (S3BlobStore) or attach through the API.",
388
+ )
389
+ definition = m.registry.get(resource)
390
+ slot_def = self.slot(definition, slot)
391
+ if not slot_def.allows("presigned"):
392
+ raise OperationNotEnabled(
393
+ f"Slot {slot!r} only accepts uploads through the API",
394
+ hint="Use attach().",
395
+ )
396
+ ctx = m._context(
397
+ definition,
398
+ "attach",
399
+ actor=actor,
400
+ entity_id=entity_id,
401
+ slot=slot,
402
+ raw_input={"filename": filename, "content_type": content_type, "size": size},
403
+ )
404
+ await m._gate(ctx, f"attach:{slot}")
405
+ await m._validate(ctx, AttachInput, slot)
406
+ self._check(slot_def, ctx.data.content_type, ctx.data.size)
407
+ async with m._transaction(ctx) as uow:
408
+ await m._load(ctx)
409
+ await m._gate_record(ctx, f"attach:{slot}", ctx.entity, input=ctx.data)
410
+ await definition.dispatcher.run(HookPoint.BEFORE_ATTACH, ctx, slot)
411
+ doc_id = uuid.uuid4().hex
412
+ doc = Document(
413
+ id=doc_id,
414
+ owner_resource=definition.name,
415
+ owner_id=str(entity_id),
416
+ slot=slot,
417
+ filename=safe_filename(ctx.data.filename),
418
+ content_type=ctx.data.content_type,
419
+ storage_key=self.key(definition.name, entity_id, doc_id),
420
+ size=ctx.data.size,
421
+ created_at=_now(),
422
+ created_by=_actor_label(actor),
423
+ expires_at=_now() + self.upload_ttl,
424
+ )
425
+ await self.machine.initialize(doc)
426
+ await self._repo(ctx).add(doc)
427
+ upload = await self.store.presign_put(
428
+ doc.storage_key, content_type=doc.content_type, expires=self.upload_ttl
429
+ )
430
+ await uow.commit()
431
+ return UploadTicket(DocumentRead.model_validate(doc), upload)
432
+
433
+ @traced("confirm_upload", resource="documents")
434
+ async def confirm_upload(self, document_id: str, *, actor: Any = None) -> DocumentRead:
435
+ """Verify a presigned upload and make the document available (or processing)."""
436
+ m = self.manager
437
+ pending = await self._get_document(document_id)
438
+ ctx = self._owner_context(pending, "attach", actor)
439
+ slot_def = self.slot(ctx.resource, pending.slot)
440
+ async with m._transaction(ctx) as uow:
441
+ await m._load(ctx)
442
+ await m._gate_record(ctx, f"attach:{slot_def.name}", ctx.entity)
443
+ doc = await self._repo(ctx).get(document_id)
444
+ if doc.status != "pending":
445
+ ctx.result = DocumentRead.model_validate(doc) # already confirmed
446
+ return cast(DocumentRead, ctx.result)
447
+ if (expires := aware(doc.expires_at)) is not None and expires < _now():
448
+ raise UploadNotVerified(f"The upload of document {document_id!r} has expired")
449
+ head = await self.store.head(doc.storage_key)
450
+ if head is None:
451
+ raise UploadNotVerified(
452
+ f"No content was uploaded for document {document_id!r}",
453
+ hint="PUT the file to the presigned URL before confirming.",
454
+ )
455
+ if head.size > slot_def.max_bytes:
456
+ await self.store.delete([doc.storage_key])
457
+ raise UploadNotVerified(
458
+ f"The uploaded file has {head.size} bytes; slot {slot_def.name!r} "
459
+ f"allows {slot_def.max_bytes}",
460
+ details={"size": head.size, "max_bytes": slot_def.max_bytes},
461
+ )
462
+ doc.size, doc.sha256, doc.expires_at = head.size, head.sha256, None
463
+ await self._activate(ctx, slot_def, doc)
464
+ await self._repo(ctx).update(doc)
465
+ await ctx.resource.dispatcher.run(HookPoint.AFTER_ATTACH, ctx, slot_def.name)
466
+ ctx.result = DocumentRead.model_validate(doc)
467
+ await m._before_commit(ctx, uow)
468
+ await uow.commit()
469
+ await m._after_commit(ctx, slot_def.name)
470
+ return cast(DocumentRead, ctx.result)
471
+
472
+ @traced("detach")
473
+ async def detach(
474
+ self, resource: Any, entity_id: Any, document_id: str, *, actor: Any = None
475
+ ) -> None:
476
+ """Detach a document from its record; its content is purged later."""
477
+ m = self.manager
478
+ definition = m.registry.get(resource)
479
+ ctx = m._context(definition, "detach", actor=actor, entity_id=entity_id)
480
+ async with m._transaction(ctx) as uow:
481
+ await m._load(ctx)
482
+ doc = await self._repo(ctx).get(document_id)
483
+ if (
484
+ doc is None
485
+ or doc.owner_resource != definition.name
486
+ or doc.owner_id != str(entity_id)
487
+ or doc.status == "deleted"
488
+ ):
489
+ raise EntityNotFound(
490
+ f"{definition.name} {entity_id!r} has no document {document_id!r}",
491
+ details={"resource": self.resource, "id": document_id},
492
+ )
493
+ ctx.slot = doc.slot
494
+ await m._gate_record(ctx, f"detach:{doc.slot}", ctx.entity)
495
+ await definition.dispatcher.run(HookPoint.BEFORE_DETACH, ctx, doc.slot)
496
+ await self.discard_in(ctx, doc)
497
+ await definition.dispatcher.run(HookPoint.AFTER_DETACH, ctx, doc.slot)
498
+ await m._before_commit(ctx, uow)
499
+ await uow.commit()
500
+ await m._after_commit(ctx, doc.slot)
501
+
502
+ @traced("list_documents")
503
+ async def list(
504
+ self, resource: Any, entity_id: Any, slot: str | None = None, *, actor: Any = None
505
+ ) -> list[DocumentRead]:
506
+ """Documents of an entity; needs ``get`` on the owner."""
507
+ definition = self.manager.registry.get(resource)
508
+ if slot is not None:
509
+ self.slot(definition, slot)
510
+ ctx = self.manager._context(definition, "get", entity_id=entity_id, actor=actor)
511
+ await self.manager._gate(ctx, "get")
512
+ async with self.manager._reading(ctx):
513
+ await self.manager._load(ctx)
514
+ await self.manager._gate_record(ctx, "get", ctx.entity)
515
+ docs = await self._owned(ctx, slot)
516
+ docs.sort(key=lambda d: (aware(d.created_at) or _now(), d.id))
517
+ return [DocumentRead.model_validate(d) for d in docs]
518
+
519
+ async def _gate_owner(self, doc: Document, action: str, actor: Any) -> None:
520
+ """Documents inherit visibility from their owner: ``get`` on it for metadata,
521
+ ``download:<slot>`` for content."""
522
+ m = self.manager
523
+ ctx = self._owner_context(doc, "get", actor)
524
+ if m.authorizer is None and ctx.resource.tenant_field is None:
525
+ return
526
+ async with m._reading(ctx) as uow:
527
+ owner = await uow.repository(ctx.resource.name).get(ctx.entity_id)
528
+ if owner is None:
529
+ raise EntityNotFound(f"Document {doc.id!r} does not exist")
530
+ try:
531
+ await m._check_tenant(ctx, owner)
532
+ except EntityNotFound:
533
+ raise EntityNotFound(f"Document {doc.id!r} does not exist") from None
534
+ await m._gate_record(ctx, action, owner)
535
+
536
+ async def get(self, document_id: str, *, actor: Any = None) -> DocumentRead:
537
+ """A document's metadata, if ``actor`` may read its record."""
538
+ doc = await self._get_document(document_id)
539
+ await self._gate_owner(doc, "get", actor)
540
+ return DocumentRead.model_validate(doc)
541
+
542
+ async def _available(self, document_id: str, actor: Any = None) -> Document:
543
+ doc = await self._get_document(document_id)
544
+ await self._gate_owner(doc, f"download:{doc.slot}", actor)
545
+ if doc.status != "available":
546
+ raise DocumentNotAvailable(
547
+ f"Document {document_id!r} is {doc.status}",
548
+ hint="Only available documents can be downloaded.",
549
+ details={"status": doc.status},
550
+ )
551
+ return doc
552
+
553
+ async def open(
554
+ self, document_id: str, *, actor: Any = None
555
+ ) -> tuple[DocumentRead, AsyncIterator[bytes]]:
556
+ """Metadata and a stream of the content of an available document."""
557
+ doc = await self._available(document_id, actor)
558
+ return DocumentRead.model_validate(doc), self.store.open(doc.storage_key)
559
+
560
+ async def read_trusted(
561
+ self, document_id: str, *, max_bytes: int | None = None
562
+ ) -> tuple[DocumentRead, bytes]:
563
+ """An available document and its content, with **no permission check**:
564
+ for engine code acting on a decision already made (an email attaching
565
+ documents its operation named). ``DocumentNotAvailable`` while it is
566
+ still being processed."""
567
+ doc = await self._get_document(document_id)
568
+ if doc.status != "available":
569
+ raise DocumentNotAvailable(
570
+ f"Document {document_id!r} is {doc.status}",
571
+ hint="Only available documents can be read.",
572
+ details={"status": doc.status},
573
+ )
574
+ if max_bytes is not None and (doc.size or 0) > max_bytes:
575
+ raise DocumentTooLarge(
576
+ f"Document {document_id!r} has {doc.size} bytes, more than {max_bytes}",
577
+ details={"size": doc.size, "max_bytes": max_bytes},
578
+ )
579
+ data = b"".join([chunk async for chunk in self.store.open(doc.storage_key)])
580
+ return DocumentRead.model_validate(doc), data
581
+
582
+ async def download_url(
583
+ self, document_id: str, *, expires: timedelta | None = None, actor: Any = None
584
+ ) -> PresignedRequest:
585
+ """A presigned URL that downloads an available document."""
586
+ if not isinstance(self.store, SupportsPresignedUrls):
587
+ raise ConfigurationError(f"{type(self.store).__name__} cannot presign downloads")
588
+ doc = await self._available(document_id, actor)
589
+ return await self.store.presign_get(
590
+ doc.storage_key, expires=expires or self.download_ttl, download_name=doc.filename
591
+ )
592
+
593
+ # -------------------------------------------------------------- processing
594
+
595
+ async def finish_processing(
596
+ self,
597
+ document_id: str,
598
+ *,
599
+ metadata: dict[str, Any] | None = None,
600
+ derived: Sequence[NewDocument] = (),
601
+ error: str | None = None,
602
+ ) -> DocumentRead | None:
603
+ """Close processing: ``complete`` (with metadata and derived documents) or
604
+ ``reject``. Idempotent: documents no longer processing are left alone."""
605
+ m = self.manager
606
+ current = await self._get_document(document_id)
607
+ ctx = self._owner_context(current, "process", None)
608
+ async with m._transaction(ctx) as uow:
609
+ repo = self._repo(ctx)
610
+ doc = await repo.get(document_id)
611
+ if doc.status != "processing":
612
+ return None
613
+ owner = await uow.repository(ctx.resource.name).get(ctx.entity_id)
614
+ if owner is None: # the owner disappeared meanwhile
615
+ await self.discard_in(ctx, doc)
616
+ elif error:
617
+ await self.machine.fire(doc, "reject", {})
618
+ doc.error = error
619
+ await repo.update(doc)
620
+ ctx.record_event(
621
+ DocumentRejected(
622
+ resource=ctx.resource.name,
623
+ entity_id=ctx.entity_id,
624
+ document_id=doc.id,
625
+ slot=doc.slot,
626
+ error=error,
627
+ )
628
+ )
629
+ else:
630
+ ctx.entity = owner
631
+ doc.metadata = {**(doc.metadata or {}), **(metadata or {})}
632
+ await self.machine.fire(doc, "complete", {})
633
+ await repo.update(doc)
634
+ for new in derived:
635
+ slot_def = self.slot(ctx.resource, new.slot)
636
+ self._check(slot_def, new.content_type, None)
637
+ await self.store_in(
638
+ ctx,
639
+ slot_def,
640
+ new.content,
641
+ filename=new.filename,
642
+ content_type=new.content_type,
643
+ metadata={**new.metadata, "derived_from": doc.id},
644
+ )
645
+ ctx.record_event(
646
+ DocumentProcessed(
647
+ resource=ctx.resource.name,
648
+ entity_id=ctx.entity_id,
649
+ document_id=doc.id,
650
+ slot=doc.slot,
651
+ )
652
+ )
653
+ await m._before_commit(ctx, uow)
654
+ await uow.commit()
655
+ await m._after_commit(ctx)
656
+ return DocumentRead.model_validate(doc)
657
+
658
+
659
+ class ContextDocuments:
660
+ """``ctx.documents``: document operations inside the current transaction.
661
+
662
+ For actions and hooks that produce files (a rendered PDF) or remove them.
663
+ Owner hooks (``before_attach`` ...) are not run: the caller is engine code.
664
+ """
665
+
666
+ def __init__(self, documents: DocumentManager, ctx: OperationContext) -> None:
667
+ self._documents = documents
668
+ self._ctx = ctx
669
+
670
+ def _require_tx(self) -> None:
671
+ if self._ctx.uow is None or self._ctx.entity_id is None:
672
+ raise RuntimeError(
673
+ "ctx.documents needs an active transaction on an entity "
674
+ "(an instance action or a hook between before_* and after_*)"
675
+ )
676
+
677
+ async def attach(self, new: NewDocument) -> DocumentRead:
678
+ """Attach a new document to the current record, in its transaction."""
679
+ self._require_tx()
680
+ slot = DocumentManager.slot(self._ctx.resource, new.slot)
681
+ DocumentManager._check(slot, new.content_type, None)
682
+ doc = await self._documents.store_in(
683
+ self._ctx,
684
+ slot,
685
+ new.content,
686
+ filename=new.filename,
687
+ content_type=new.content_type,
688
+ metadata=new.metadata,
689
+ )
690
+ return DocumentRead.model_validate(doc)
691
+
692
+ async def detach(self, document_id: str) -> None:
693
+ """Detach one of the current record's documents, in its transaction."""
694
+ self._require_tx()
695
+ doc = await self._documents._repo(self._ctx).get(document_id)
696
+ if doc is None or doc.owner_id != str(self._ctx.entity_id) or doc.status == "deleted":
697
+ raise EntityNotFound(f"No document {document_id!r} on this entity")
698
+ await self._documents.discard_in(self._ctx, doc)
699
+
700
+ async def list(self, slot: str | None = None) -> list[DocumentRead]:
701
+ """The current record's documents (in ``slot``, when given)."""
702
+ self._require_tx()
703
+ docs = await self._documents._owned(self._ctx, slot)
704
+ return [DocumentRead.model_validate(d) for d in docs]