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,417 @@
1
+ """Email from templates, sent after the commit.
2
+
3
+ Inside an operation, record an ``EmailRequested`` event: it is stored with the
4
+ change (the outbox) and sent only if the transaction commits::
5
+
6
+ ctx.record_event(
7
+ EmailRequested(template="invoice_approved", to=[customer.email],
8
+ context={"number": invoice.id}, locale="ca")
9
+ )
10
+
11
+ The worker sends it: ``Mailer.router()`` handles the requests, through a
12
+ ``MessageProcessor`` with the inbox, fed from the outbox (``ProcessFeed``) or
13
+ from a broker. Outside a transaction (a job, a script) call ``Mailer.send``.
14
+
15
+ Stored documents go along as attachments: name them in ``documents`` (their
16
+ ids) and give the Mailer the document manager (``Mailer(...,
17
+ documents=manager.documents)``). A document generated in the same operation
18
+ works too::
19
+
20
+ pdf = await generator.attach(ctx, "printed", "invoice", format="pdf")
21
+ ctx.record_event(EmailRequested(template="invoice_sent", to=[email], documents=[pdf.id]))
22
+
23
+ A template set ``invoice_approved`` is three files under ``email/``:
24
+ ``invoice_approved.subject.txt``, ``invoice_approved.txt`` and
25
+ ``invoice_approved.html`` (text or html may be missing, not both).
26
+ See docs/email.md.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import dataclasses
32
+ import logging
33
+ import mimetypes
34
+ from collections.abc import Callable, Mapping, Sequence
35
+ from dataclasses import dataclass, field
36
+ from email.message import EmailMessage as MimeMessage
37
+ from email.utils import formatdate, parseaddr
38
+ from typing import Any, override
39
+
40
+ from resource_engine.domain.events import DomainEvent
41
+ from resource_engine.errors import ConfigurationError, TemplateNotFound
42
+ from resource_engine.messaging.consumer import EventRouter
43
+ from resource_engine.messaging.envelope import EventEnvelope, to_jsonable
44
+ from resource_engine.ports.email import (
45
+ Attachment,
46
+ EmailEvent,
47
+ EmailMessage,
48
+ EmailSender,
49
+ SuppressionList,
50
+ )
51
+ from resource_engine.ports.templates import TemplateRenderer
52
+
53
+ log = logging.getLogger("resource_engine.email")
54
+
55
+
56
+ @dataclass(frozen=True, kw_only=True)
57
+ class EmailRequested(DomainEvent):
58
+ """An email to send once the change that asked for it is committed.
59
+
60
+ ``context`` travels as JSON (decimals and dates become strings). It is
61
+ stored in the outbox and, with a broker, published like other events:
62
+ keep it to what the template needs.
63
+ """
64
+
65
+ template: str
66
+ to: Sequence[str]
67
+ context: Mapping[str, Any] = field(default_factory=dict)
68
+ locale: str | None = None
69
+ cc: Sequence[str] = ()
70
+ bcc: Sequence[str] = ()
71
+ reply_to: Sequence[str] = ()
72
+ resource: str | None = None
73
+ entity_id: Any = None
74
+ #: Ids of stored documents to attach. They are read when the email is
75
+ #: sent, without a permission check: the operation that asked chose them.
76
+ documents: Sequence[str] = ()
77
+
78
+
79
+ type ContextFactory = Callable[[], Mapping[str, Any]] | Mapping[str, Any]
80
+
81
+
82
+ class Mailer:
83
+ """Composes messages from a template set and sends them.
84
+
85
+ Args:
86
+ sender: The ``EmailSender`` (``SmtpEmailSender``, ``SesEmailSender``,
87
+ ``RecordingEmailSender`` in tests).
88
+ templates: The ``TemplateRenderer``.
89
+ from_address: ``From`` of every message.
90
+ reply_to: Default ``Reply-To``.
91
+ default_locale: Used when a request names none.
92
+ prefix: Folder of the email templates (``email/``).
93
+ globals: Values every template gets (app name, URLs), or a function
94
+ returning them; the request's context wins on a clash.
95
+ suppressions: A ``SuppressionList``: suppressed recipients are left
96
+ out of every message, and a message with nobody left isn't sent.
97
+ documents: The ``DocumentManager`` that requested ``documents`` are
98
+ read from (``manager.documents``).
99
+ max_attachment_bytes: The most the attachments of one message may
100
+ weigh together; above it the request is refused (dead-lettered).
101
+ """
102
+
103
+ def __init__(
104
+ self,
105
+ sender: EmailSender,
106
+ templates: TemplateRenderer,
107
+ *,
108
+ from_address: str,
109
+ reply_to: Sequence[str] = (),
110
+ default_locale: str | None = None,
111
+ prefix: str = "email/",
112
+ globals: ContextFactory | None = None,
113
+ suppressions: SuppressionList | None = None,
114
+ documents: Any = None,
115
+ max_attachment_bytes: int = 10 * 1024 * 1024,
116
+ ) -> None:
117
+ if "@" not in parseaddr(from_address)[1]:
118
+ raise ConfigurationError(f"Invalid from_address {from_address!r}")
119
+ self.sender = sender
120
+ self.templates = templates
121
+ self.from_address = from_address
122
+ self.reply_to = tuple(reply_to)
123
+ self.default_locale = default_locale
124
+ self.prefix = prefix
125
+ self.globals = globals
126
+ self.suppressions = suppressions
127
+ self.documents = documents
128
+ self.max_attachment_bytes = max_attachment_bytes
129
+
130
+ @property
131
+ def domain(self) -> str:
132
+ """The domain of the sender address."""
133
+ return parseaddr(self.from_address)[1].rpartition("@")[2]
134
+
135
+ def template_names(self, template: str) -> tuple[str, str, str]:
136
+ """The subject, text and html template names of a set."""
137
+ base = f"{self.prefix}{template}"
138
+ return f"{base}.subject.txt", f"{base}.txt", f"{base}.html"
139
+
140
+ def compose(
141
+ self,
142
+ template: str,
143
+ to: Sequence[str] | str,
144
+ context: Mapping[str, Any] | None = None,
145
+ *,
146
+ locale: str | None = None,
147
+ cc: Sequence[str] = (),
148
+ bcc: Sequence[str] = (),
149
+ reply_to: Sequence[str] = (),
150
+ attachments: Sequence[Attachment] = (),
151
+ message_id: str | None = None,
152
+ headers: Mapping[str, str] | None = None,
153
+ ) -> EmailMessage:
154
+ """Render a template set into a message (nothing is sent)."""
155
+ recipients = [to] if isinstance(to, str) else list(to)
156
+ if not recipients:
157
+ raise ConfigurationError(f"Email {template!r} has no recipient")
158
+ values = dict(self.globals() if callable(self.globals) else self.globals or {})
159
+ values.update(context or {})
160
+ locale = locale or self.default_locale
161
+ subject_name, text_name, html_name = self.template_names(template)
162
+ subject = self.templates.render(subject_name, values, locale=locale)
163
+ text = self._optional(text_name, values, locale)
164
+ html = self._optional(html_name, values, locale)
165
+ if text is None and html is None:
166
+ raise TemplateNotFound(
167
+ f"Email {template!r} has no body: add {text_name} or {html_name}",
168
+ details={"name": text_name, "locale": locale, "tried": [text_name, html_name]},
169
+ doc="docs/email.md#templates",
170
+ )
171
+ return EmailMessage(
172
+ sender=self.from_address,
173
+ to=recipients,
174
+ subject=" ".join(subject.split()),
175
+ text=text,
176
+ html=html,
177
+ cc=tuple(cc),
178
+ bcc=tuple(bcc),
179
+ reply_to=tuple(reply_to) or self.reply_to,
180
+ message_id=message_id,
181
+ headers=dict(headers or {}),
182
+ attachments=tuple(attachments),
183
+ tags={"template": template},
184
+ )
185
+
186
+ def _optional(self, name: str, values: Mapping[str, Any], locale: str | None) -> str | None:
187
+ if not self.templates.exists(name, locale=locale):
188
+ return None
189
+ return self.templates.render(name, values, locale=locale)
190
+
191
+ async def send(
192
+ self,
193
+ template: str,
194
+ to: Sequence[str] | str,
195
+ context: Mapping[str, Any] | None = None,
196
+ **kw: Any,
197
+ ) -> str | None:
198
+ """Compose and send now (outside a transaction: a job, a script)."""
199
+ composed = self.compose(template, to, context, **kw)
200
+ message = await self._without_suppressed(composed)
201
+ if message is None:
202
+ log.info("email skipped: every recipient is suppressed", extra={"template": template})
203
+ return None
204
+ provider_id = await self.sender.send(message)
205
+ log.info(
206
+ "email sent",
207
+ extra={"template": template, "recipients": len(message.recipients),
208
+ "message_id": message.message_id, "provider_id": provider_id},
209
+ ) # fmt: skip
210
+ return provider_id
211
+
212
+ async def _without_suppressed(self, message: EmailMessage) -> EmailMessage | None:
213
+ if self.suppressions is None:
214
+ return message
215
+ blocked = {a.lower() for a in await self.suppressions.suppressed(message.recipients)}
216
+ if not blocked:
217
+ return message
218
+
219
+ def keep(addresses: Sequence[str]) -> tuple[str, ...]:
220
+ return tuple(a for a in addresses if parseaddr(a)[1].lower() not in blocked)
221
+
222
+ to, cc, bcc = keep(message.to), keep(message.cc), keep(message.bcc)
223
+ if not (to or cc or bcc):
224
+ return None
225
+ return dataclasses.replace(message, to=to, cc=cc, bcc=bcc)
226
+
227
+ # ---------------------------------------------------- requested emails
228
+
229
+ async def handle(self, envelope: EventEnvelope) -> None:
230
+ """Send the email an ``EmailRequested`` envelope asks for. Its
231
+ ``Message-ID`` comes from the envelope id, so a retry is the same message."""
232
+ data = dict(envelope.payload)
233
+ attachments = await self.document_attachments(list(data.get("documents") or ()))
234
+ await self.send(
235
+ str(data["template"]),
236
+ list(data.get("to") or ()),
237
+ dict(data.get("context") or {}),
238
+ locale=data.get("locale"),
239
+ cc=list(data.get("cc") or ()),
240
+ bcc=list(data.get("bcc") or ()),
241
+ reply_to=list(data.get("reply_to") or ()),
242
+ attachments=attachments,
243
+ message_id=f"<{envelope.id}@{self.domain}>",
244
+ )
245
+
246
+ async def document_attachments(self, document_ids: Sequence[str]) -> list[Attachment]:
247
+ """Stored documents as attachments. A document still being processed
248
+ raises ``DocumentNotAvailable`` (the request is retried later); a
249
+ missing, rejected or too large one refuses the request."""
250
+ from resource_engine.errors import (
251
+ DocumentNotAvailable,
252
+ DocumentTooLarge,
253
+ EntityNotFound,
254
+ MessageRejected,
255
+ )
256
+
257
+ if not document_ids:
258
+ return []
259
+ if self.documents is None:
260
+ raise ConfigurationError(
261
+ "An email asks for documents but the Mailer has no document manager",
262
+ hint="Mailer(..., documents=manager.documents).",
263
+ doc="docs/email.md#attachments",
264
+ )
265
+ attachments: list[Attachment] = []
266
+ left = self.max_attachment_bytes
267
+ for document_id in document_ids:
268
+ try:
269
+ document, content = await self.documents.read_trusted(
270
+ str(document_id), max_bytes=left
271
+ )
272
+ except DocumentNotAvailable as exc:
273
+ status = (exc.details or {}).get("status")
274
+ if status in ("pending", "processing"):
275
+ raise
276
+ raise MessageRejected(
277
+ f"Document {document_id!r} can't be attached: it is {status}"
278
+ ) from exc
279
+ except (EntityNotFound, DocumentTooLarge) as exc:
280
+ raise MessageRejected(
281
+ f"Document {document_id!r} can't be attached: {exc.message}",
282
+ details={"max_attachment_bytes": self.max_attachment_bytes},
283
+ ) from exc
284
+ left -= len(content)
285
+ attachments.append(Attachment(document.filename, document.content_type, content))
286
+ return attachments
287
+
288
+ def router(self, *, name: str = "emails") -> EventRouter:
289
+ """An ``EventRouter`` that sends ``EmailRequested`` and ignores the rest.
290
+
291
+ Run it through ``MessageProcessor(..., manager=)`` (the inbox keeps a
292
+ request from being sent twice) and combine it with other routers with
293
+ ``EventRouter.include``. Delivery is at least once: a crash between the
294
+ provider's answer and the inbox mark sends the message again, with the
295
+ same ``Message-ID``.
296
+ """
297
+ router = EventRouter(ignore_unknown=True, name=name, description="Sends requested emails")
298
+ router.register(EmailRequested, lambda envelope: self.handle(envelope))
299
+ return router
300
+
301
+
302
+ class InMemorySuppressionList(SuppressionList):
303
+ """A ``SuppressionList`` in this process (tests, single instances); use the
304
+ SQL one (``SqlAlchemySuppressionList``) with several."""
305
+
306
+ def __init__(self) -> None:
307
+ self.reasons: dict[str, str] = {}
308
+
309
+ @override
310
+ async def suppressed(self, addresses: Sequence[str]) -> set[str]:
311
+ wanted = {parseaddr(a)[1].lower() or a.lower() for a in addresses}
312
+ return wanted & set(self.reasons)
313
+
314
+ @override
315
+ async def suppress(self, address: str, reason: str) -> None:
316
+ self.reasons[address.lower()] = reason
317
+
318
+ @override
319
+ async def release(self, address: str) -> None:
320
+ self.reasons.pop(address.lower(), None)
321
+
322
+
323
+ class EmailEventHandler:
324
+ """Acts on what mail services report: hard bounces, complaints and
325
+ unsubscribes suppress the address; soft bounces and deliveries are logged.
326
+
327
+ Args:
328
+ suppressions: Where suppressed addresses go.
329
+ on_event: Also called for every event (metrics, a record's status).
330
+ """
331
+
332
+ SUPPRESS = {"complaint", "unsubscribe"}
333
+
334
+ def __init__(
335
+ self, suppressions: SuppressionList, *, on_event: Callable[[EmailEvent], Any] | None = None
336
+ ) -> None:
337
+ self.suppressions = suppressions
338
+ self.on_event = on_event
339
+
340
+ async def handle(self, events: Sequence[EmailEvent]) -> int:
341
+ """Returns how many addresses were suppressed."""
342
+ suppressed = 0
343
+ for event in events:
344
+ if event.kind in self.SUPPRESS or (event.kind == "bounce" and event.permanent):
345
+ await self.suppressions.suppress(
346
+ event.address, f"{event.provider} {event.kind}: {event.reason}".strip()
347
+ )
348
+ suppressed += 1
349
+ log.info(
350
+ "email %s",
351
+ event.kind,
352
+ extra={"provider": event.provider, "permanent": event.permanent},
353
+ )
354
+ if self.on_event is not None:
355
+ result = self.on_event(event)
356
+ if hasattr(result, "__await__"):
357
+ await result
358
+ return suppressed
359
+
360
+
361
+ def to_mime(message: EmailMessage) -> MimeMessage:
362
+ """The message as a MIME document (SMTP, SES raw). ``Bcc`` is not a header:
363
+ pass ``message.recipients`` as the envelope recipients."""
364
+ mime = MimeMessage()
365
+ mime["From"] = message.sender
366
+ mime["To"] = ", ".join(message.to)
367
+ if message.cc:
368
+ mime["Cc"] = ", ".join(message.cc)
369
+ if message.reply_to:
370
+ mime["Reply-To"] = ", ".join(message.reply_to)
371
+ mime["Subject"] = message.subject
372
+ mime["Date"] = formatdate(localtime=False, usegmt=True)
373
+ if message.message_id:
374
+ mime["Message-ID"] = message.message_id
375
+ for name, value in message.headers.items():
376
+ mime[name] = value
377
+ if message.text is not None:
378
+ mime.set_content(message.text)
379
+ if message.html is not None:
380
+ mime.add_alternative(message.html, subtype="html")
381
+ else:
382
+ mime.set_content(message.html or "", subtype="html")
383
+ for attachment in message.attachments:
384
+ maintype, _, subtype = attachment.content_type.partition("/")
385
+ mime.add_attachment(
386
+ attachment.content,
387
+ maintype=maintype or "application",
388
+ subtype=subtype or "octet-stream",
389
+ filename=attachment.filename,
390
+ )
391
+ return mime
392
+
393
+
394
+ def attachment(filename: str, content: bytes, content_type: str | None = None) -> Attachment:
395
+ """An attachment, its type guessed from the file name when not given."""
396
+ guessed = content_type or mimetypes.guess_type(filename)[0] or "application/octet-stream"
397
+ return Attachment(filename, guessed, content)
398
+
399
+
400
+ def jsonable_context(context: Mapping[str, Any]) -> dict[str, Any]:
401
+ """``context`` as it reaches the template from an ``EmailRequested``."""
402
+ jsonable: dict[str, Any] = to_jsonable(dict(context))
403
+ return jsonable
404
+
405
+
406
+ __all__ = [
407
+ "Attachment",
408
+ "EmailEvent",
409
+ "EmailEventHandler",
410
+ "EmailMessage",
411
+ "EmailRequested",
412
+ "InMemorySuppressionList",
413
+ "Mailer",
414
+ "attachment",
415
+ "jsonable_context",
416
+ "to_mime",
417
+ ]