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,91 @@
1
+ """The ``Document`` entity and its read schema."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import unicodedata
7
+ from dataclasses import dataclass, field
8
+ from datetime import datetime
9
+ from typing import Any
10
+
11
+ from pydantic import BaseModel, ConfigDict, Field
12
+
13
+
14
+ @dataclass
15
+ class Document:
16
+ """A file attached to an entity of another resource.
17
+
18
+ The content lives in the blob store under ``storage_key``; this row is the
19
+ source of truth: a blob without a row is garbage (see ``DocumentJanitor``).
20
+ """
21
+
22
+ id: str
23
+ owner_resource: str
24
+ owner_id: str
25
+ slot: str
26
+ filename: str
27
+ content_type: str
28
+ storage_key: str
29
+ status: str | None = None
30
+ size: int | None = None
31
+ sha256: str | None = None
32
+ created_at: datetime | None = None
33
+ created_by: str | None = None
34
+ expires_at: datetime | None = None
35
+ metadata: dict[str, Any] = field(default_factory=dict)
36
+ error: str | None = None
37
+ purged_at: datetime | None = None
38
+
39
+
40
+ class DocumentRead(BaseModel):
41
+ """Public representation of a document."""
42
+
43
+ model_config = ConfigDict(from_attributes=True)
44
+
45
+ id: str = Field(description="Document identifier")
46
+ owner_resource: str = Field(description="Resource the document belongs to")
47
+ owner_id: str = Field(description="Identifier of the owning entity")
48
+ slot: str = Field(description="Slot of the owning resource")
49
+ status: str = Field(description="pending, processing, available, rejected or deleted")
50
+ filename: str = Field(description="Original file name (sanitised)")
51
+ content_type: str = Field(description="MIME type")
52
+ size: int | None = Field(default=None, description="Size in bytes")
53
+ sha256: str | None = Field(default=None, description="SHA-256 of the content, hex")
54
+ created_at: datetime | None = Field(default=None, description="When it was attached")
55
+ created_by: str | None = Field(default=None, description="Actor that attached it")
56
+ metadata: dict[str, Any] = Field(default_factory=dict, description="Data from processing")
57
+ error: str | None = Field(default=None, description="Why processing rejected it")
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class NewDocument:
62
+ """A document produced by code (an action, a processor) rather than uploaded."""
63
+
64
+ slot: str
65
+ content: Any # bytes or AsyncIterable[bytes]
66
+ filename: str
67
+ content_type: str
68
+ metadata: dict[str, Any] = field(default_factory=dict)
69
+
70
+
71
+ _UNSAFE = re.compile(r'[\x00-\x1f\x7f/\\:*?"<>|]+')
72
+
73
+
74
+ def safe_filename(name: str, *, fallback: str = "file") -> str:
75
+ """Base name only, no control or path characters, at most 200 characters."""
76
+ name = unicodedata.normalize("NFC", name or "").replace("\\", "/").rsplit("/", 1)[-1]
77
+ name = _UNSAFE.sub("_", name).strip(" .")
78
+ if len(name) > 200:
79
+ stem, dot, ext = name.rpartition(".")
80
+ name = (stem[: 200 - len(ext) - 1] + dot + ext) if dot and len(ext) < 20 else name[:200]
81
+ return name or fallback
82
+
83
+
84
+ def content_disposition(filename: str, *, inline: bool = False) -> str:
85
+ """RFC 6266 header value with an ASCII fallback and the UTF-8 ``filename*``."""
86
+ from urllib.parse import quote
87
+
88
+ name = safe_filename(filename)
89
+ fallback = name.encode("ascii", "replace").decode().replace("?", "_").replace('"', "_")
90
+ kind = "inline" if inline else "attachment"
91
+ return f"{kind}; filename=\"{fallback}\"; filename*=UTF-8''{quote(name, safe='')}"
@@ -0,0 +1,98 @@
1
+ """Processing pipeline: pluggable steps run on documents of slots with
2
+ ``processing=True`` (virus scan, text extraction, thumbnails, classification...).
3
+
4
+ The pipeline is an event handler for ``DocumentAttached``. Run it with the
5
+ consumers (``MessageProcessor`` + ``MessageConsumer``, or the push endpoint), so
6
+ retries, dead-lettering and de-duplication come from the messaging layer::
7
+
8
+ router = EventRouter(ignore_unknown=True)
9
+ DocumentPipeline(manager.documents, [MyScanner()]).register(router)
10
+ consumer = MessageConsumer(source, MessageProcessor(router, name="documents"))
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections.abc import AsyncIterator, Callable, Sequence
16
+ from dataclasses import dataclass, field
17
+ from typing import Any, Protocol
18
+
19
+ from resource_engine.documents.model import DocumentRead, NewDocument
20
+ from resource_engine.messaging.consumer import EventRouter
21
+ from resource_engine.messaging.envelope import EventEnvelope
22
+
23
+ type OpenContent = Callable[[], AsyncIterator[bytes]]
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class ProcessingResult:
28
+ """What a processor found.
29
+
30
+ Attributes:
31
+ metadata: Stored under ``document.metadata[<processor name>]``.
32
+ derived: New documents to attach to the same owner (e.g. a thumbnail).
33
+ reject: Reason to refuse the document; later processors do not run.
34
+ """
35
+
36
+ metadata: dict[str, Any] = field(default_factory=dict)
37
+ derived: list[NewDocument] = field(default_factory=list)
38
+ reject: str | None = None
39
+
40
+
41
+ class DocumentProcessor(Protocol):
42
+ """One pipeline step. Raise to retry later (transient failure); return
43
+ ``ProcessingResult(reject=...)`` to refuse the document for good."""
44
+
45
+ name: str
46
+
47
+ def accepts(self, document: DocumentRead) -> bool:
48
+ """Whether this step runs for ``document``."""
49
+ ...
50
+
51
+ async def process(self, document: DocumentRead, content: OpenContent) -> ProcessingResult:
52
+ """Run the step on ``document`` and its ``content``."""
53
+ ...
54
+
55
+
56
+ class DocumentPipeline:
57
+ """Runs the processors on attached documents, as a consumer of ``DocumentAttached``."""
58
+
59
+ def __init__(self, documents: Any, processors: Sequence[DocumentProcessor]) -> None:
60
+ self.documents = documents
61
+ self.processors = list(processors)
62
+
63
+ def register(self, router: EventRouter) -> EventRouter:
64
+ """Have ``router`` call this pipeline for ``DocumentAttached``; returns the router."""
65
+ router.register("DocumentAttached", self.handle)
66
+ return router
67
+
68
+ async def handle(self, envelope: EventEnvelope) -> None:
69
+ """Run the processors on the document a ``DocumentAttached`` event names."""
70
+ if not envelope.payload.get("processing"):
71
+ return
72
+ document_id = envelope.payload["document_id"]
73
+ doc = await self.documents._get_document(document_id)
74
+ if doc.status != "processing":
75
+ return # already processed (redelivery) or discarded
76
+ read = DocumentRead.model_validate(doc)
77
+ store = self.documents.store
78
+
79
+ def content() -> AsyncIterator[bytes]:
80
+ stream: AsyncIterator[bytes] = store.open(doc.storage_key)
81
+ return stream
82
+
83
+ metadata: dict[str, Any] = {}
84
+ derived: list[NewDocument] = []
85
+ error: str | None = None
86
+ for processor in self.processors:
87
+ if not processor.accepts(read):
88
+ continue
89
+ result = await processor.process(read, content)
90
+ if result.metadata:
91
+ metadata[processor.name] = result.metadata
92
+ derived += result.derived
93
+ if result.reject:
94
+ error = f"{processor.name}: {result.reject}"
95
+ break
96
+ await self.documents.finish_processing(
97
+ document_id, metadata=metadata, derived=[] if error else derived, error=error
98
+ )
@@ -0,0 +1,320 @@
1
+ """Reference document processors for the processing pipeline.
2
+
3
+ ```python
4
+ from resource_engine.documents import ContentTypeCheck, DocumentPipeline, TextExtraction
5
+ from resource_engine_clamav import ClamAvScanner
6
+ from resource_engine_http import TikaTextExtractor
7
+
8
+ DocumentPipeline(manager.documents, [
9
+ ClamAvScanner("clamav", 3310), # first: nothing else reads malware
10
+ ContentTypeCheck(), # the bytes match the declared type
11
+ TextExtraction(TikaTextExtractor(http, "http://tika:9998"), slot="texts"),
12
+ ]).register(router)
13
+ ```
14
+
15
+ - ``ContentTypeCheck`` reads the first bytes and rejects documents whose
16
+ content is not what their declared type says (an executable uploaded as
17
+ ``image/png``). It knows the common signatures (PDF, PNG, JPEG, GIF, WebP,
18
+ TIFF, ZIP and Office files, Windows and Linux executables).
19
+ - ``TextExtraction`` stores the document's text as a derived ``text/plain``
20
+ document (in ``slot``) and its length, page count and language as metadata,
21
+ for search or classification. Text comes from a ``TextExtractor``:
22
+ ``BuiltinTextExtractor`` reads plain text, CSV, JSON, XML and Word
23
+ (``.docx``) files without dependencies; Apache Tika (``resource-engine-http``)
24
+ reads PDF, Office, images (OCR) and hundreds more.
25
+ - Antivirus: ``ClamAvScanner`` (``resource-engine-clamav``).
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import io
31
+ import re
32
+ import zipfile
33
+ from collections.abc import AsyncIterator, Callable, Sequence
34
+ from dataclasses import dataclass
35
+ from typing import Any, Protocol, override
36
+ from xml.etree import ElementTree
37
+
38
+ from resource_engine.documents.model import DocumentRead, NewDocument
39
+ from resource_engine.documents.pipeline import DocumentProcessor, OpenContent, ProcessingResult
40
+
41
+ # ------------------------------------------------------------ content types
42
+
43
+ #: (signature, offset, detected type). ZIP covers Office Open XML and ODF.
44
+ SIGNATURES: tuple[tuple[bytes, int, str], ...] = (
45
+ (b"%PDF-", 0, "application/pdf"),
46
+ (b"\x89PNG\r\n\x1a\n", 0, "image/png"),
47
+ (b"\xff\xd8\xff", 0, "image/jpeg"),
48
+ (b"GIF87a", 0, "image/gif"),
49
+ (b"GIF89a", 0, "image/gif"),
50
+ (b"WEBP", 8, "image/webp"),
51
+ (b"II*\x00", 0, "image/tiff"),
52
+ (b"MM\x00*", 0, "image/tiff"),
53
+ (b"PK\x03\x04", 0, "application/zip"),
54
+ (b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1", 0, "application/x-ole-storage"),
55
+ (b"MZ", 0, "application/x-msdownload"),
56
+ (b"\x7fELF", 0, "application/x-executable"),
57
+ )
58
+
59
+ #: Declared types each detected type may stand for.
60
+ COMPATIBLE: dict[str, tuple[str, ...]] = {
61
+ "application/zip": (
62
+ "application/zip",
63
+ "application/vnd.openxmlformats-officedocument.",
64
+ "application/vnd.oasis.opendocument.",
65
+ "application/epub+zip",
66
+ "application/java-archive",
67
+ ),
68
+ "application/x-ole-storage": (
69
+ "application/msword",
70
+ "application/vnd.ms-excel",
71
+ "application/vnd.ms-powerpoint",
72
+ "application/vnd.ms-outlook",
73
+ ),
74
+ }
75
+
76
+ EXECUTABLES = frozenset({"application/x-msdownload", "application/x-executable"})
77
+
78
+
79
+ def detect(head: bytes) -> str | None:
80
+ """The type the first bytes show (``None``: no known signature, e.g. text)."""
81
+ for signature, offset, kind in SIGNATURES:
82
+ if head[offset : offset + len(signature)] == signature:
83
+ return kind
84
+ return None
85
+
86
+
87
+ async def read_head(content: OpenContent, size: int = 64) -> bytes:
88
+ """The first ``size`` bytes of a document, to sniff its type."""
89
+ head = b""
90
+ stream = content()
91
+ try:
92
+ async for chunk in stream:
93
+ head += chunk
94
+ if len(head) >= size:
95
+ break
96
+ finally:
97
+ closing = getattr(stream, "aclose", None)
98
+ if closing is not None:
99
+ await closing()
100
+ return head[:size]
101
+
102
+
103
+ class ContentTypeCheck(DocumentProcessor):
104
+ """Rejects documents whose bytes don't match their declared type.
105
+
106
+ Args:
107
+ allow_unknown: Accept content with no known signature (text, CSV,
108
+ JSON...) whatever its declared type, unless that type is one with
109
+ a signature (a "PDF" that doesn't start with ``%PDF-``).
110
+ """
111
+
112
+ name = "content_type"
113
+
114
+ def __init__(self, *, allow_unknown: bool = True) -> None:
115
+ self.allow_unknown = allow_unknown
116
+
117
+ @override
118
+ def accepts(self, document: DocumentRead) -> bool:
119
+ return True
120
+
121
+ @override
122
+ async def process(self, document: DocumentRead, content: OpenContent) -> ProcessingResult:
123
+ declared = document.content_type.split(";")[0].strip().lower()
124
+ detected = detect(await read_head(content))
125
+ if detected in EXECUTABLES:
126
+ return ProcessingResult(reject=f"the content is an executable ({detected})")
127
+ if detected is None:
128
+ claimed = {kind for _, _, kind in SIGNATURES}
129
+ if declared in claimed or not self.allow_unknown:
130
+ return ProcessingResult(reject=f"the content is not {declared}")
131
+ return ProcessingResult(metadata={"declared": declared, "detected": None})
132
+ allowed = COMPATIBLE.get(detected, (detected,))
133
+ if not any(declared == a or (a.endswith(".") and declared.startswith(a)) for a in allowed):
134
+ return ProcessingResult(reject=f"declared {declared}, but the content is {detected}")
135
+ return ProcessingResult(metadata={"declared": declared, "detected": detected})
136
+
137
+
138
+ # --------------------------------------------------------------------- text
139
+
140
+
141
+ @dataclass(frozen=True)
142
+ class ExtractedText:
143
+ """Text a processor extracted from a document."""
144
+
145
+ text: str
146
+ pages: int | None = None
147
+ language: str | None = None
148
+
149
+
150
+ class TextExtractor(Protocol):
151
+ """Turns a document's content into text (``None``: not a type it reads)."""
152
+
153
+ def handles(self, content_type: str) -> bool:
154
+ """Whether this extractor reads ``content_type``."""
155
+ ...
156
+
157
+ async def extract(self, content: OpenContent, content_type: str) -> ExtractedText | None:
158
+ """The text of ``content``, or ``None`` when it has none."""
159
+ ...
160
+
161
+
162
+ async def read_all(content: OpenContent, max_bytes: int) -> bytes:
163
+ """A document's content, refused past ``max_bytes``."""
164
+ data = bytearray()
165
+ async for chunk in content():
166
+ data += chunk
167
+ if len(data) > max_bytes:
168
+ raise ValueError(f"more than {max_bytes} bytes")
169
+ return bytes(data)
170
+
171
+
172
+ _TEXT_TYPES = ("text/", "application/json", "application/xml", "application/csv")
173
+ _DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
174
+ _WORD = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
175
+
176
+
177
+ class _Unsafe(ValueError):
178
+ """A .docx built to attack the reader: oversized when unpacked, or with a DTD."""
179
+
180
+
181
+ def _docx_text(data: bytes, max_bytes: int) -> str:
182
+ """The paragraphs of an uploaded (untrusted) .docx. The XML is read only
183
+ when it unpacks to at most ``max_bytes`` (a small zip can unpack to
184
+ gigabytes) and has no DTD: Word never writes one, and entity definitions
185
+ are how XML parsers are attacked."""
186
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
187
+ if archive.getinfo("word/document.xml").file_size > max_bytes:
188
+ raise _Unsafe("word/document.xml unpacks past the limit")
189
+ with archive.open("word/document.xml") as part:
190
+ xml = part.read(max_bytes + 1)
191
+ if len(xml) > max_bytes:
192
+ raise _Unsafe("word/document.xml unpacks past the limit")
193
+ if b"<!DOCTYPE" in xml.upper() or b"<!ENTITY" in xml.upper():
194
+ raise _Unsafe("word/document.xml declares a DTD")
195
+ root = ElementTree.fromstring(xml) # noqa: S314 - size-capped, no DTD: nothing to expand
196
+ paragraphs = []
197
+ for paragraph in root.iter(f"{_WORD}p"):
198
+ paragraphs.append("".join(t.text or "" for t in paragraph.iter(f"{_WORD}t")))
199
+ return "\n".join(paragraphs)
200
+
201
+
202
+ class BuiltinTextExtractor(TextExtractor):
203
+ """Plain text, CSV, JSON, XML and Word (``.docx``), with no dependencies.
204
+
205
+ Args:
206
+ max_bytes: Larger documents are skipped (no text). For ``.docx``, also
207
+ the most its text part may unpack to; one with a DTD is skipped.
208
+ """
209
+
210
+ def __init__(self, *, max_bytes: int = 20 * 1024 * 1024) -> None:
211
+ self.max_bytes = max_bytes
212
+
213
+ @override
214
+ def handles(self, content_type: str) -> bool:
215
+ kind = content_type.split(";")[0].strip().lower()
216
+ return kind.startswith(_TEXT_TYPES) or kind == _DOCX
217
+
218
+ @override
219
+ async def extract(self, content: OpenContent, content_type: str) -> ExtractedText | None:
220
+ try:
221
+ data = await read_all(content, self.max_bytes)
222
+ except ValueError:
223
+ return None
224
+ kind = content_type.split(";")[0].strip().lower()
225
+ if kind == _DOCX:
226
+ try:
227
+ return ExtractedText(_docx_text(data, self.max_bytes))
228
+ except (zipfile.BadZipFile, KeyError, ElementTree.ParseError, _Unsafe):
229
+ return None
230
+ charset = re.search(r"charset=([\w-]+)", content_type)
231
+ for encoding in (charset.group(1) if charset else "utf-8", "utf-8-sig", "latin-1"):
232
+ try:
233
+ return ExtractedText(data.decode(encoding))
234
+ except (UnicodeDecodeError, LookupError):
235
+ continue
236
+ return None # pragma: no cover - latin-1 decodes anything
237
+
238
+
239
+ class TextExtraction(DocumentProcessor):
240
+ """Extracts each document's text: a derived ``text/plain`` document in
241
+ ``slot`` (when given) and ``characters``, ``pages``, ``language`` as metadata.
242
+
243
+ Args:
244
+ extractors: Tried in order; the first that handles the type is used.
245
+ slot: Slot of the owner for the text document (``None``: metadata only).
246
+ preview: Characters of the text kept in the metadata (``0``: none).
247
+ accepts: Which documents to read (default: every type an extractor handles).
248
+ """
249
+
250
+ name = "text"
251
+
252
+ def __init__(
253
+ self,
254
+ *extractors: TextExtractor,
255
+ slot: str | None = None,
256
+ preview: int = 0,
257
+ accepts: Callable[[DocumentRead], bool] | None = None,
258
+ ) -> None:
259
+ self.extractors: Sequence[TextExtractor] = extractors or (BuiltinTextExtractor(),)
260
+ self.slot = slot
261
+ self.preview = preview
262
+ self._accepts = accepts
263
+
264
+ def _extractor(self, content_type: str) -> TextExtractor | None:
265
+ return next((e for e in self.extractors if e.handles(content_type)), None)
266
+
267
+ @override
268
+ def accepts(self, document: DocumentRead) -> bool:
269
+ if self.slot is not None and document.slot == self.slot:
270
+ return False # never extract the extracted text again
271
+ if self._accepts is not None:
272
+ return self._accepts(document)
273
+ return self._extractor(document.content_type) is not None
274
+
275
+ @override
276
+ async def process(self, document: DocumentRead, content: OpenContent) -> ProcessingResult:
277
+ extractor = self._extractor(document.content_type)
278
+ if extractor is None:
279
+ return ProcessingResult()
280
+ found = await extractor.extract(content, document.content_type)
281
+ if found is None:
282
+ return ProcessingResult(metadata={"extracted": False})
283
+ metadata: dict[str, Any] = {"extracted": True, "characters": len(found.text)}
284
+ if found.pages is not None:
285
+ metadata["pages"] = found.pages
286
+ if found.language:
287
+ metadata["language"] = found.language
288
+ if self.preview:
289
+ metadata["preview"] = found.text[: self.preview]
290
+ derived = []
291
+ if self.slot is not None and found.text.strip():
292
+ stem = document.filename.rsplit(".", 1)[0] or "document"
293
+ derived.append(
294
+ NewDocument(
295
+ slot=self.slot,
296
+ content=found.text.encode("utf-8"),
297
+ filename=f"{stem}.txt",
298
+ content_type="text/plain; charset=utf-8",
299
+ )
300
+ )
301
+ return ProcessingResult(metadata=metadata, derived=derived)
302
+
303
+
304
+ async def chunks(data: bytes, size: int = 64 * 1024) -> AsyncIterator[bytes]:
305
+ """``data`` as an async stream (tests, extractors that buffer)."""
306
+ for start in range(0, len(data), size):
307
+ yield data[start : start + size]
308
+
309
+
310
+ __all__ = [
311
+ "BuiltinTextExtractor",
312
+ "ContentTypeCheck",
313
+ "ExtractedText",
314
+ "TextExtraction",
315
+ "TextExtractor",
316
+ "chunks",
317
+ "detect",
318
+ "read_all",
319
+ "read_head",
320
+ ]
@@ -0,0 +1,39 @@
1
+ """The engine's resource for documents attached to records."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from resource_engine.application.resource import Resource
6
+ from resource_engine.application.settings import Access, Internal, Listing
7
+ from resource_engine.documents.machine import DocumentStateMachine
8
+ from resource_engine.documents.model import Document, DocumentRead
9
+
10
+
11
+ class DocumentResource(Resource):
12
+ """Files attached to entities of other resources.
13
+
14
+ Business resources declare slots (``documents = [DocumentSlot(...)]``); the
15
+ engine stores each file's content in the blob store and its metadata here.
16
+ Documents are created, replaced and removed through the owner resource
17
+ (``attach`` / ``detach``), never directly.
18
+
19
+ Business area:
20
+ Documents
21
+ """
22
+
23
+ name = "documents"
24
+ model = Document
25
+ id_type = str
26
+ schemas = {"read": DocumentRead}
27
+ operations = ["list", "get"]
28
+ operation_docs = {
29
+ "list": "Lists documents, filterable by owner, slot and status.",
30
+ "get": "Returns a document's metadata.",
31
+ }
32
+ state_machine = DocumentStateMachine
33
+ internal = Internal(transitions=True)
34
+ # raw document queries: use the owner's routes instead
35
+ access = Access(wildcards=False)
36
+ listing = Listing(
37
+ filterable=["owner_resource", "owner_id", "slot", "status"],
38
+ sortable=["created_at", "filename", "size"],
39
+ )
@@ -0,0 +1,10 @@
1
+ """Domain building blocks.
2
+
3
+ Nothing in this package may import FastAPI, SQLAlchemy, Pydantic or any
4
+ infrastructure library. Modules' ``domain/`` packages should only depend on this.
5
+ """
6
+
7
+ from resource_engine.domain.events import DomainEvent
8
+ from resource_engine.domain.exceptions import DomainError
9
+
10
+ __all__ = ["DomainError", "DomainEvent"]
@@ -0,0 +1,50 @@
1
+ """Domain events: what happened, raised by the domain and published after commit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass, field
7
+ from datetime import UTC, datetime
8
+ from typing import Any, ClassVar
9
+
10
+
11
+ def _now() -> datetime:
12
+ return datetime.now(UTC)
13
+
14
+
15
+ @dataclass(frozen=True, kw_only=True)
16
+ class DomainEvent:
17
+ """Something that happened in the domain.
18
+
19
+ Events are collected during an operation and published only after the
20
+ transaction commits. Subclass it as a frozen dataclass::
21
+
22
+ @dataclass(frozen=True, kw_only=True)
23
+ class InvoiceApproved(DomainEvent):
24
+ invoice_id: int
25
+
26
+ When its payload changes in a way consumers notice, raise
27
+ ``schema_version`` and keep publishing the older shapes in
28
+ ``previous_versions`` (``resource_engine.versions.EventVersion``) until
29
+ their sunset. ``deprecation`` marks the event itself as on its way out.
30
+ """
31
+
32
+ schema_version: ClassVar[int] = 1
33
+ previous_versions: ClassVar[Mapping[int, Any]] = {}
34
+ deprecation: ClassVar[Any] = None
35
+
36
+ occurred_at: datetime = field(default_factory=_now)
37
+
38
+ @property
39
+ def name(self) -> str:
40
+ """The event's type name: its class name."""
41
+ return type(self).__name__
42
+
43
+
44
+ def event_doc(event_cls: type) -> str | None:
45
+ """The event class's own docstring; ``None`` for the signature that
46
+ ``@dataclass`` writes when there is none."""
47
+ doc: str | None = event_cls.__dict__.get("__doc__")
48
+ if not doc or doc.startswith(f"{event_cls.__name__}("):
49
+ return None
50
+ return doc
@@ -0,0 +1,23 @@
1
+ """Errors of business rules, raised by domain code."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class DomainError(Exception):
7
+ """A business rule was violated.
8
+
9
+ Raise it (or a subclass) from domain code, hooks or actions. Adapters map it to
10
+ a client error (HTTP 422 by default). ``code`` is optional and free-form.
11
+ """
12
+
13
+ code: str = "DOMAIN"
14
+
15
+ def __init__(self, message: str, *, code: str | None = None) -> None:
16
+ super().__init__(message)
17
+ self.message = message
18
+ if code is not None:
19
+ self.code = code
20
+
21
+ def to_dict(self) -> dict[str, str]:
22
+ """The error's code and message, as JSON-ready data."""
23
+ return {"code": self.code, "message": self.message}