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,562 @@
1
+ """Engine errors with stable codes.
2
+
3
+ Every error raised by the engine carries:
4
+
5
+ - ``code``: a stable identifier (``RE-Exxx``) that tools and agents can match on.
6
+ - ``message``: what went wrong.
7
+ - ``hint``: how to fix it.
8
+ - ``doc``: where to read more.
9
+
10
+ The catalogue lives in ``docs/errors.md``. Codes are never reused once published.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import Any, ClassVar
16
+
17
+ DOCS_BASE = "docs/errors.md"
18
+
19
+
20
+ class ResourceEngineError(Exception):
21
+ """Base class for every error raised by the engine."""
22
+
23
+ code: ClassVar[str] = "RE-E000"
24
+
25
+ def __init__(
26
+ self,
27
+ message: str,
28
+ *,
29
+ hint: str | None = None,
30
+ doc: str | None = None,
31
+ details: Any = None,
32
+ ) -> None:
33
+ super().__init__(message)
34
+ self.message = message
35
+ self.hint = hint
36
+ self.doc = doc or f"{DOCS_BASE}#{self.code.lower()}"
37
+ self.details = details
38
+
39
+ def __str__(self) -> str:
40
+ parts = [f"{self.code}: {self.message}"]
41
+ if self.hint:
42
+ parts.append(self.hint)
43
+ if self.doc:
44
+ parts.append(f"See {self.doc}")
45
+ return "\n".join(parts)
46
+
47
+ @property
48
+ def title(self) -> str:
49
+ """A short sentence for people (not developers), in the current locale:
50
+ what a user interface can show. ``message`` stays technical and English."""
51
+ from resource_engine.i18n import pgettext
52
+
53
+ return pgettext(self.code, TITLES.get(self.code, TITLES["RE-E000"]))
54
+
55
+ def to_dict(self) -> dict[str, Any]:
56
+ """The error as JSON-ready data: code, title, message and hint."""
57
+ data: dict[str, Any] = {"code": self.code, "title": self.title, "message": self.message}
58
+ if self.hint:
59
+ data["hint"] = self.hint
60
+ if self.doc:
61
+ data["doc"] = self.doc
62
+ if self.details is not None:
63
+ data["details"] = self.details
64
+ return data
65
+
66
+
67
+ #: What each error means for a person using an application, in English; the
68
+ #: engine's catalogue (``resource_engine/locale``) translates them, keyed by code.
69
+ TITLES: dict[str, str] = {
70
+ "RE-E000": "Something went wrong.",
71
+ "RE-E001": "The application is misconfigured.",
72
+ "RE-E002": "This kind of record does not exist.",
73
+ "RE-E003": "This operation is not available.",
74
+ "RE-E004": "The application is misconfigured.",
75
+ "RE-E005": "The application is misconfigured.",
76
+ "RE-E007": "The changes could not be saved together.",
77
+ "RE-E008": "The application is misconfigured.",
78
+ "RE-E009": "The history is not available.",
79
+ "RE-E010": "A message template is missing.",
80
+ "RE-E011": "A message template could not be filled in.",
81
+ "RE-E012": "There are too many changes to save together.",
82
+ "RE-E101": "Some fields are not valid.",
83
+ "RE-E102": "The record does not exist.",
84
+ "RE-E103": "The search cannot be done this way.",
85
+ "RE-E104": "The application is misconfigured.",
86
+ "RE-E105": "Someone else changed this record. Reload it and try again.",
87
+ "RE-E106": "Reload the record before changing it.",
88
+ "RE-E107": "This request was already made with other data.",
89
+ "RE-E108": "A related record does not exist.",
90
+ "RE-E109": "Other records still depend on this one.",
91
+ "RE-E201": "This step is not possible now.",
92
+ "RE-E202": "This step does not exist.",
93
+ "RE-E301": "This action does not exist.",
94
+ "RE-E401": "Some messages could not be sent.",
95
+ "RE-E402": "A message could not be handled.",
96
+ "RE-E403": "The application is misconfigured.",
97
+ "RE-E404": "The application is misconfigured.",
98
+ "RE-E405": "A message could not be read.",
99
+ "RE-E406": "A message was refused.",
100
+ "RE-E501": "Another service did not answer. Try again later.",
101
+ "RE-E502": "The email could not be delivered.",
102
+ "RE-E601": "This kind of document does not exist.",
103
+ "RE-E602": "This type of file is not accepted.",
104
+ "RE-E603": "The file is too large.",
105
+ "RE-E604": "The upload did not complete.",
106
+ "RE-E605": "The document is not available yet.",
107
+ "RE-E606": "A required document is missing.",
108
+ "RE-E607": "Files cannot be stored right now. Try again later.",
109
+ "RE-E608": "The file does not exist.",
110
+ "RE-E701": "Sign in to continue.",
111
+ "RE-E702": "You are not allowed to do this.",
112
+ "RE-E703": "The policy is not valid.",
113
+ "RE-E704": "You cannot grant more than you have.",
114
+ "RE-E705": "The policy uses a condition this system cannot apply.",
115
+ "RE-E706": "You are not allowed to change some of these fields.",
116
+ "RE-E707": "You cannot search or sort by this field.",
117
+ "RE-E708": "Choose an organisation first.",
118
+ "RE-E709": "This belongs to another organisation.",
119
+ "RE-E710": "Too many requests. Wait a moment and try again.",
120
+ }
121
+
122
+
123
+ # --- Configuration (RE-E0xx): raised while building definitions, at bootstrap ---
124
+
125
+
126
+ class ConfigurationError(ResourceEngineError):
127
+ """A resource, action or hook is declared incorrectly."""
128
+
129
+ code = "RE-E001"
130
+
131
+
132
+ class ResourceNotRegistered(ResourceEngineError):
133
+ """The resource isn't registered (RE-E002)."""
134
+
135
+ code = "RE-E002"
136
+
137
+
138
+ class OperationNotEnabled(ResourceEngineError):
139
+ """The operation isn't enabled on the resource (RE-E003)."""
140
+
141
+ code = "RE-E003"
142
+
143
+
144
+ class StateFieldExposed(ConfigurationError):
145
+ """The state field appears in a create/update schema."""
146
+
147
+ code = "RE-E004"
148
+
149
+
150
+ class ExternalEffectInTransaction(ConfigurationError):
151
+ """A hook marked as producing external effects is registered before commit."""
152
+
153
+ code = "RE-E104"
154
+
155
+
156
+ # --- Input and lookup (RE-E1xx) ---
157
+
158
+
159
+ class VersioningNotSupported(ConfigurationError):
160
+ """A versioned resource (``version_field``) uses a repository that cannot
161
+ compare and set versions (``supports_versions``)."""
162
+
163
+ code = "RE-E005"
164
+
165
+
166
+ class TransactionDoomed(ResourceEngineError):
167
+ """An operation failed inside ``manager.transaction()``: the transaction can
168
+ only roll back. ``details`` carries the original error's ``code`` and
169
+ ``message``; the exception is chained to it."""
170
+
171
+ code = "RE-E007"
172
+
173
+
174
+ class IdempotencyNotSupported(ConfigurationError):
175
+ """An idempotency key was sent but the unit of work has no idempotency store."""
176
+
177
+ code = "RE-E008"
178
+
179
+
180
+ class HistoryNotAvailable(ConfigurationError):
181
+ """Transition history was asked for a resource without a state machine, or
182
+ without an audit trail stored as a resource."""
183
+
184
+ code = "RE-E009"
185
+
186
+
187
+ class ValidationFailed(ResourceEngineError):
188
+ """The data doesn't match the operation's schema (RE-E101)."""
189
+
190
+ code = "RE-E101"
191
+
192
+
193
+ class EntityNotFound(ResourceEngineError):
194
+ """No record with that id, or none the caller may see (RE-E102)."""
195
+
196
+ code = "RE-E102"
197
+
198
+
199
+ class InvalidQuery(ResourceEngineError):
200
+ """A filter, sort field, search or page the resource doesn't allow (RE-E103)."""
201
+
202
+ code = "RE-E103"
203
+
204
+
205
+ class QueryNotSupported(InvalidQuery):
206
+ """The resource allows the query, but its store can't run it (a filter or
207
+ sort without an index, a deep offset). ``details`` lists the ``filters``,
208
+ ``order_by`` or ``offset`` refused and what the store supports."""
209
+
210
+
211
+ class TransactionTooLarge(ResourceEngineError):
212
+ """One commit holds more writes than the store's transactions take
213
+ (``max_writes``: 100 in DynamoDB and Cosmos DB, 500 in Firestore).
214
+ ``details``: ``writes``, ``max_writes``."""
215
+
216
+ code = "RE-E012"
217
+
218
+
219
+ # --- State machines (RE-E2xx) ---
220
+
221
+
222
+ class VersionConflict(ResourceEngineError):
223
+ """The record changed since the client read it (optimistic concurrency).
224
+
225
+ ``details``: ``resource``, ``id``, ``expected`` (the version the write was
226
+ based on) and ``current`` (when known). Reload the record and retry.
227
+ """
228
+
229
+ code = "RE-E105"
230
+
231
+
232
+ class VersionRequired(ResourceEngineError):
233
+ """The resource requires the version the client read (``If-Match``)."""
234
+
235
+ code = "RE-E106"
236
+
237
+
238
+ class IdempotencyKeyReused(ResourceEngineError):
239
+ """The idempotency key was already used by the same caller for a different
240
+ request (another operation, record or input)."""
241
+
242
+ code = "RE-E107"
243
+
244
+
245
+ class ReferenceNotFound(ResourceEngineError):
246
+ """A reference field points to a record that does not exist or that the
247
+ caller may not read. ``details``: ``field``, ``resource``, ``id``."""
248
+
249
+ code = "RE-E108"
250
+
251
+
252
+ class TemplateNotFound(ResourceEngineError):
253
+ """No template with that name for the locale or any fallback.
254
+ ``details``: ``name``, ``locale``, ``tried``."""
255
+
256
+ code = "RE-E010"
257
+
258
+
259
+ class TemplateFailed(ResourceEngineError):
260
+ """A template failed to render (a missing variable, a syntax error).
261
+ ``details``: ``name`` and the renderer's ``error``."""
262
+
263
+ code = "RE-E011"
264
+
265
+
266
+ class ReferenceInUse(ResourceEngineError):
267
+ """The record cannot be deleted: other records reference it
268
+ (``on_delete="restrict"``). ``details``: ``resource``, ``field``, ``id``."""
269
+
270
+ code = "RE-E109"
271
+
272
+
273
+ class TransitionNotAllowed(ResourceEngineError):
274
+ """The record's state doesn't allow the transition (RE-E201)."""
275
+
276
+ code = "RE-E201"
277
+
278
+
279
+ class UnknownTransition(ResourceEngineError):
280
+ """The state machine has no such transition (RE-E202)."""
281
+
282
+ code = "RE-E202"
283
+
284
+
285
+ # --- Actions (RE-E3xx) ---
286
+
287
+
288
+ class ActionNotFound(ResourceEngineError):
289
+ """The resource has no such action (RE-E301)."""
290
+
291
+ code = "RE-E301"
292
+
293
+
294
+ # --- Messaging (RE-E4xx) ---
295
+
296
+
297
+ class PublishFailed(ResourceEngineError):
298
+ """Some messages could not be handed to the transport.
299
+
300
+ ``failed_ids`` lists the envelope ids that were not accepted; the rest were.
301
+ The outbox relay uses it to mark only the delivered messages as published.
302
+ """
303
+
304
+ code = "RE-E401"
305
+
306
+ def __init__(self, message: str, *, failed_ids: list[str], **kw: object) -> None:
307
+ super().__init__(message, details={"failed_ids": failed_ids}, **kw) # type: ignore[arg-type]
308
+ self.failed_ids = failed_ids
309
+
310
+
311
+ class NoHandler(ResourceEngineError):
312
+ """An inbound message has a type no handler is registered for."""
313
+
314
+ code = "RE-E402"
315
+
316
+
317
+ class OutboxNotSupported(ConfigurationError):
318
+ """OutboxDelivery is used with a unit of work that has no outbox."""
319
+
320
+ code = "RE-E403"
321
+
322
+
323
+ class InboxNotSupported(ConfigurationError):
324
+ """A consumer was given an inbox unit of work factory whose units have no ``inbox()``."""
325
+
326
+ code = "RE-E404"
327
+
328
+
329
+ class UndecodableMessage(ResourceEngineError):
330
+ """An inbound message body is not an envelope or a CloudEvent."""
331
+
332
+ code = "RE-E405"
333
+
334
+
335
+ class MessageRejected(ResourceEngineError):
336
+ """Raise from a message handler to dead-letter the message without retrying it."""
337
+
338
+ code = "RE-E406"
339
+
340
+
341
+ # --- External services (RE-E5xx) ---
342
+
343
+
344
+ class EmailRejected(ResourceEngineError):
345
+ """The mail service refused a message for good (an invalid address, a
346
+ blocked sender); retrying won't help. ``details``: ``recipients``,
347
+ ``reason``."""
348
+
349
+ code = "RE-E502"
350
+
351
+
352
+ class RemoteCallFailed(ResourceEngineError):
353
+ """A call to an external service (REST, SOAP, OData...) failed.
354
+
355
+ ``details`` carries ``service``, ``operation``, the upstream ``status`` (HTTP
356
+ status, or ``None`` for transport errors and SOAP faults) and a short ``body``
357
+ excerpt. HTTP adapters map it to 502 Bad Gateway.
358
+ """
359
+
360
+ code = "RE-E501"
361
+
362
+ def __init__(
363
+ self,
364
+ message: str,
365
+ *,
366
+ service: str,
367
+ operation: str,
368
+ status: int | None = None,
369
+ body: str | None = None,
370
+ **kw: object,
371
+ ) -> None:
372
+ details = {"service": service, "operation": operation, "status": status}
373
+ if body:
374
+ details["body"] = body[:500]
375
+ super().__init__(message, details=details, **kw) # type: ignore[arg-type]
376
+ self.service = service
377
+ self.operation = operation
378
+ self.status = status
379
+
380
+
381
+ # --- Documents and storage (RE-E6xx) ---
382
+
383
+
384
+ class DocumentSlotNotFound(ResourceEngineError):
385
+ """The resource declares no document slot with that name."""
386
+
387
+ code = "RE-E601"
388
+
389
+
390
+ class ContentTypeNotAllowed(ResourceEngineError):
391
+ """The file's content type is not accepted by the slot."""
392
+
393
+ code = "RE-E602"
394
+
395
+
396
+ class DocumentTooLarge(ResourceEngineError):
397
+ """The file exceeds the slot's ``max_bytes``."""
398
+
399
+ code = "RE-E603"
400
+
401
+
402
+ class UploadNotVerified(ResourceEngineError):
403
+ """A presigned upload cannot be confirmed (missing object, too large, expired)."""
404
+
405
+ code = "RE-E604"
406
+
407
+
408
+ class DocumentNotAvailable(ResourceEngineError):
409
+ """The document exists but its content cannot be served in its current state."""
410
+
411
+ code = "RE-E605"
412
+
413
+
414
+ class RequiredDocumentMissing(ResourceEngineError):
415
+ """A transition needs a document the entity does not have yet."""
416
+
417
+ code = "RE-E606"
418
+
419
+
420
+ class StorageFailed(ResourceEngineError):
421
+ """The blob store failed (network, permissions, bucket missing)."""
422
+
423
+ code = "RE-E607"
424
+
425
+
426
+ class BlobNotFound(ResourceEngineError):
427
+ """No blob stored under the key."""
428
+
429
+ code = "RE-E608"
430
+
431
+
432
+ # --- Identity (RE-E7xx) ---
433
+
434
+
435
+ class AuthenticationFailed(ResourceEngineError):
436
+ """The caller's credentials are missing, malformed, expired or not trusted.
437
+
438
+ ``details.reason`` is a short machine-readable reason (``missing``,
439
+ ``expired``, ``invalid_signature``, ``invalid_audience``, ``invalid_issuer``,
440
+ ``invalid_token``...). Messages never echo the token.
441
+ """
442
+
443
+ code = "RE-E701"
444
+
445
+ def __init__(self, message: str, *, reason: str, **kw: object) -> None:
446
+ super().__init__(message, details={"reason": reason}, **kw) # type: ignore[arg-type]
447
+ self.reason = reason
448
+
449
+
450
+ class PermissionDenied(ResourceEngineError):
451
+ """The principal may not perform the action. ``details.action`` names it."""
452
+
453
+ code = "RE-E702"
454
+
455
+
456
+ class InvalidPolicy(ResourceEngineError):
457
+ """A policy does not validate against the catalogue; ``details.problems``
458
+ lists ``{path, message}`` entries for the editor."""
459
+
460
+ code = "RE-E703"
461
+
462
+
463
+ class PrivilegeEscalation(ResourceEngineError):
464
+ """An editor tried to grant actions they do not hold themselves."""
465
+
466
+ code = "RE-E704"
467
+
468
+
469
+ class ConditionNotSupported(ResourceEngineError):
470
+ """A repository cannot apply a row-level filter; the operation fails closed."""
471
+
472
+ code = "RE-E705"
473
+
474
+
475
+ class FieldNotWritable(ResourceEngineError):
476
+ """The input sets fields the principal may not write; ``details.fields``
477
+ lists them. Nothing is saved."""
478
+
479
+ code = "RE-E706"
480
+
481
+
482
+ class FieldNotReadable(ResourceEngineError):
483
+ """A query filters or sorts by fields the principal may not read;
484
+ ``details.fields`` lists them."""
485
+
486
+ code = "RE-E707"
487
+
488
+
489
+ class TenantRequired(ResourceEngineError):
490
+ """A tenant-scoped resource needs a tenant: the caller has none, or a
491
+ cross-tenant caller did not name one where it is required (create)."""
492
+
493
+ code = "RE-E708"
494
+
495
+
496
+ class TenantMismatch(ResourceEngineError):
497
+ """The operation names a tenant other than the caller's."""
498
+
499
+ code = "RE-E709"
500
+
501
+
502
+ class RateLimited(ResourceEngineError):
503
+ """Too many requests from this caller (or address) in the current window.
504
+ ``details.retry_after`` says how many seconds to wait."""
505
+
506
+ code = "RE-E710"
507
+
508
+
509
+ __all__ = [
510
+ "TITLES",
511
+ "ActionNotFound",
512
+ "AuthenticationFailed",
513
+ "BlobNotFound",
514
+ "ConditionNotSupported",
515
+ "ConfigurationError",
516
+ "ContentTypeNotAllowed",
517
+ "DocumentNotAvailable",
518
+ "DocumentSlotNotFound",
519
+ "DocumentTooLarge",
520
+ "EmailRejected",
521
+ "EntityNotFound",
522
+ "ExternalEffectInTransaction",
523
+ "FieldNotReadable",
524
+ "FieldNotWritable",
525
+ "HistoryNotAvailable",
526
+ "IdempotencyKeyReused",
527
+ "IdempotencyNotSupported",
528
+ "InboxNotSupported",
529
+ "InvalidPolicy",
530
+ "InvalidQuery",
531
+ "MessageRejected",
532
+ "NoHandler",
533
+ "OperationNotEnabled",
534
+ "OutboxNotSupported",
535
+ "PermissionDenied",
536
+ "PrivilegeEscalation",
537
+ "PublishFailed",
538
+ "QueryNotSupported",
539
+ "RateLimited",
540
+ "ReferenceInUse",
541
+ "ReferenceNotFound",
542
+ "RemoteCallFailed",
543
+ "RequiredDocumentMissing",
544
+ "ResourceEngineError",
545
+ "ResourceNotRegistered",
546
+ "StateFieldExposed",
547
+ "StorageFailed",
548
+ "TemplateFailed",
549
+ "TemplateNotFound",
550
+ "TenantMismatch",
551
+ "TenantRequired",
552
+ "TransactionDoomed",
553
+ "TransactionTooLarge",
554
+ "TransitionNotAllowed",
555
+ "UndecodableMessage",
556
+ "UnknownTransition",
557
+ "UploadNotVerified",
558
+ "ValidationFailed",
559
+ "VersionConflict",
560
+ "VersionRequired",
561
+ "VersioningNotSupported",
562
+ ]
@@ -0,0 +1,133 @@
1
+ """Permissions and checks of the explorer: the live events, the worker's jobs
2
+ and publishing events by hand (docs/explorer.md).
3
+
4
+ These actions belong to no resource. ``register_explorer`` adds them to the
5
+ authorization catalogue, so the policy editor offers them like any other:
6
+
7
+ - ``events:read``: every committed event, including those about no record
8
+ (others see only events about records they can read), the outbox and the
9
+ dead letters.
10
+ - ``events:redrive``: send an outbox message again.
11
+ - ``jobs:read`` and ``jobs:run``: the worker's jobs, their runs, "run now".
12
+ - ``events:publish:<Event>``: publish that event by hand. It is *exact*: no
13
+ wildcard grants it (``*`` and ``events:*`` don't), only a role or policy
14
+ naming it.
15
+
16
+ The explorer's endpoints check them with ``require``. Without an authorizer
17
+ every one of them is refused, unless the app opens the explorer explicitly
18
+ for local development (``open=True``).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from typing import Any
24
+
25
+ from resource_engine.authz.catalog import ActionInfo
26
+ from resource_engine.errors import AuthenticationFailed, PermissionDenied
27
+
28
+ RESOURCE = "explorer"
29
+
30
+ EVENTS_READ = ActionInfo(
31
+ "events:read",
32
+ resource="events",
33
+ kind="engine",
34
+ description="See every committed event live, including those about no record",
35
+ wildcards=False,
36
+ )
37
+ EVENTS_REDRIVE = ActionInfo(
38
+ "events:redrive",
39
+ resource="events",
40
+ kind="engine",
41
+ description="Send an outbox message again (to the consumers that failed it)",
42
+ wildcards=False,
43
+ )
44
+ JOBS_READ = ActionInfo(
45
+ "jobs:read",
46
+ resource="jobs",
47
+ kind="engine",
48
+ description="See the worker's jobs, their schedules and recent runs",
49
+ wildcards=False,
50
+ )
51
+ JOBS_RUN = ActionInfo(
52
+ "jobs:run",
53
+ resource="jobs",
54
+ kind="engine",
55
+ description="Ask the worker to run a job now",
56
+ wildcards=False,
57
+ )
58
+
59
+
60
+ def publish_action(event_type: str) -> ActionInfo:
61
+ """``events:publish:<event_type>``: granted only by name."""
62
+ return ActionInfo(
63
+ f"events:publish:{event_type}",
64
+ resource="events",
65
+ kind="publish",
66
+ qualifier=event_type,
67
+ description=f"Publish {event_type} by hand from the explorer",
68
+ wildcards=False,
69
+ exact=True,
70
+ )
71
+
72
+
73
+ def register_explorer(
74
+ registry: Any, *, events: bool = True, jobs: bool = True, publish: bool = True
75
+ ) -> None:
76
+ """Add the explorer's actions to the registry's catalogue (before the
77
+ ``ResourceManager`` is built)."""
78
+ actions: list[ActionInfo] = []
79
+ if events:
80
+ actions += [EVENTS_READ, EVENTS_REDRIVE]
81
+ if jobs:
82
+ actions += [JOBS_READ, JOBS_RUN]
83
+ if publish:
84
+ from resource_engine.messaging.publishing import publishable_events
85
+
86
+ actions += [publish_action(event.__name__) for event in publishable_events(registry)]
87
+ registry.register_actions(*actions)
88
+
89
+
90
+ async def allowed(manager: Any, actor: Any, action: str, *, open: bool = False) -> bool:
91
+ """Whether ``actor`` holds ``action``. Without an authorizer only an
92
+ ``open`` explorer allows it."""
93
+ authorizer = manager.authorizer
94
+ if authorizer is None:
95
+ return open
96
+ return (await authorizer.check(actor, action)).allowed is True
97
+
98
+
99
+ async def require(
100
+ manager: Any, actor: Any, action: str, *, open: bool = False, audit: bool = True
101
+ ) -> None:
102
+ """Raise ``PermissionDenied`` (and audit the refusal) unless ``actor`` holds
103
+ ``action``."""
104
+ if await allowed(manager, actor, action, open=open):
105
+ return
106
+ if audit:
107
+ await manager.audit_event(actor, action, "denied")
108
+ if actor is None and manager.authorizer is not None:
109
+ raise AuthenticationFailed(
110
+ f"Sign in to use {action}",
111
+ reason="missing",
112
+ hint="Send the caller's credentials (a bearer token or an API key).",
113
+ )
114
+ raise PermissionDenied(
115
+ f"Not allowed: {action}",
116
+ details={"action": action},
117
+ hint=None
118
+ if manager.authorizer is not None
119
+ else "The explorer has no authorizer: pass open=True only for local development.",
120
+ )
121
+
122
+
123
+ __all__ = [
124
+ "EVENTS_READ",
125
+ "EVENTS_REDRIVE",
126
+ "JOBS_READ",
127
+ "JOBS_RUN",
128
+ "RESOURCE",
129
+ "allowed",
130
+ "publish_action",
131
+ "register_explorer",
132
+ "require",
133
+ ]