resource-engine-fastapi 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 (39) hide show
  1. resource_engine_fastapi/__init__.py +39 -0
  2. resource_engine_fastapi/access.py +110 -0
  3. resource_engine_fastapi/asyncapi.py +47 -0
  4. resource_engine_fastapi/auth.py +158 -0
  5. resource_engine_fastapi/authz.py +100 -0
  6. resource_engine_fastapi/caching.py +111 -0
  7. resource_engine_fastapi/docs.py +77 -0
  8. resource_engine_fastapi/documents.py +219 -0
  9. resource_engine_fastapi/email_events.py +85 -0
  10. resource_engine_fastapi/errors.py +178 -0
  11. resource_engine_fastapi/events.py +109 -0
  12. resource_engine_fastapi/explorer/__init__.py +441 -0
  13. resource_engine_fastapi/explorer/assets/auth.js +171 -0
  14. resource_engine_fastapi/explorer/assets/console.js +340 -0
  15. resource_engine_fastapi/explorer/assets/events.js +189 -0
  16. resource_engine_fastapi/explorer/assets/explorer.css +156 -0
  17. resource_engine_fastapi/explorer/assets/explorer.js +275 -0
  18. resource_engine_fastapi/explorer/assets/jobs.js +143 -0
  19. resource_engine_fastapi/explorer/assets/messages.js +85 -0
  20. resource_engine_fastapi/explorer/assets/publish.js +117 -0
  21. resource_engine_fastapi/explorer/data.py +84 -0
  22. resource_engine_fastapi/explorer/events.py +182 -0
  23. resource_engine_fastapi/explorer/jobs.py +167 -0
  24. resource_engine_fastapi/explorer/labels.py +198 -0
  25. resource_engine_fastapi/explorer/locale/ca/LC_MESSAGES/explorer.mo +0 -0
  26. resource_engine_fastapi/explorer/locale/ca/LC_MESSAGES/explorer.po +417 -0
  27. resource_engine_fastapi/explorer/locale/es/LC_MESSAGES/explorer.mo +0 -0
  28. resource_engine_fastapi/explorer/locale/es/LC_MESSAGES/explorer.po +417 -0
  29. resource_engine_fastapi/explorer/messages.py +73 -0
  30. resource_engine_fastapi/explorer/publish.py +85 -0
  31. resource_engine_fastapi/exports.py +186 -0
  32. resource_engine_fastapi/i18n.py +76 -0
  33. resource_engine_fastapi/py.typed +0 -0
  34. resource_engine_fastapi/router.py +1031 -0
  35. resource_engine_fastapi/versioning.py +49 -0
  36. resource_engine_fastapi-0.1.0.dist-info/METADATA +32 -0
  37. resource_engine_fastapi-0.1.0.dist-info/RECORD +39 -0
  38. resource_engine_fastapi-0.1.0.dist-info/WHEEL +4 -0
  39. resource_engine_fastapi-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,219 @@
1
+ """HTTP routes for documents attached to resources.
2
+
3
+ Owner routes (``/{resource}/{id}/documents...``) are added for resources with
4
+ document slots; download and confirmation live under the documents resource.
5
+ Annotations are evaluated eagerly here (no ``from __future__ import annotations``):
6
+ FastAPI needs the per-resource id and slot types defined inside the builder.
7
+
8
+ With an authorizer, the manager checks ``<resource>:attach|detach|download:<slot>``
9
+ and the owner's visibility.
10
+ """
11
+
12
+ from collections.abc import AsyncIterator
13
+ from datetime import datetime
14
+ from typing import Any, Literal
15
+
16
+ from fastapi import APIRouter, Depends, File, Path, Query, Request, Response, UploadFile, status
17
+ from fastapi.responses import RedirectResponse, StreamingResponse
18
+ from pydantic import BaseModel, Field
19
+ from resource_engine import ResourceDefinition, ResourceManager
20
+ from resource_engine.documents import DocumentRead, content_disposition
21
+ from resource_engine.errors import DocumentTooLarge
22
+ from resource_engine.ports.storage import SupportsPresignedUrls
23
+
24
+ CHUNK = 1024 * 1024
25
+ MULTIPART_OVERHEAD = 16 * 1024
26
+
27
+
28
+ class UploadRequest(BaseModel):
29
+ """Body of an upload request: the file's name, type and size."""
30
+
31
+ filename: str = Field(min_length=1, max_length=1000, description="Original file name")
32
+ content_type: str = Field(min_length=3, max_length=255, description="MIME type")
33
+ size: int | None = Field(default=None, ge=0, description="Size in bytes, if known")
34
+
35
+
36
+ class PresignedUpload(BaseModel):
37
+ """A presigned request the client sends the file with, straight to the store."""
38
+
39
+ url: str
40
+ method: str
41
+ headers: dict[str, str]
42
+ expires_at: datetime
43
+
44
+
45
+ class UploadTicketOut(BaseModel):
46
+ """Answer to an upload request: the pending document and where to upload its content."""
47
+
48
+ document: DocumentRead
49
+ upload: PresignedUpload
50
+
51
+
52
+ async def _chunks(file: UploadFile) -> AsyncIterator[bytes]:
53
+ while chunk := await file.read(CHUNK):
54
+ yield chunk
55
+
56
+
57
+ def add_owner_document_routes(
58
+ router: APIRouter,
59
+ definition: ResourceDefinition,
60
+ manager: ResourceManager,
61
+ actor_dependency: Any,
62
+ ) -> None:
63
+ """``/{id}/documents`` routes on the owner resource's router."""
64
+ if manager.documents is None or not definition.document_slots:
65
+ return
66
+ docs = manager.documents
67
+ name = definition.name
68
+ slots = definition.document_slots
69
+ SlotName = Literal[tuple(slots)] # type: ignore[valid-type] # OpenAPI enum
70
+ IdType = definition.id_type
71
+
72
+ @router.get(
73
+ "/{entity_id}/documents",
74
+ response_model=list[DocumentRead],
75
+ summary=f"Documents of a {name} entity",
76
+ operation_id=f"{name}_documents",
77
+ )
78
+ async def list_documents(
79
+ entity_id: IdType = Path(...), # type: ignore[valid-type]
80
+ slot: SlotName | None = Query(None), # type: ignore[valid-type]
81
+ actor: Any = Depends(actor_dependency),
82
+ ) -> Any:
83
+ return await docs.list(name, entity_id, slot, actor=actor)
84
+
85
+ if any(s.allows("api") for s in slots.values()):
86
+
87
+ @router.post(
88
+ "/{entity_id}/documents/{slot}",
89
+ response_model=DocumentRead,
90
+ status_code=status.HTTP_201_CREATED,
91
+ summary=f"Upload a document to a {name} entity",
92
+ operation_id=f"{name}_attach_document",
93
+ )
94
+ async def attach_document(
95
+ request: Request,
96
+ entity_id: IdType = Path(...), # type: ignore[valid-type]
97
+ slot: SlotName = Path(...), # type: ignore[valid-type]
98
+ file: UploadFile = File(...),
99
+ actor: Any = Depends(actor_dependency),
100
+ ) -> Any:
101
+ declared = request.headers.get("content-length")
102
+ limit = slots[slot].max_bytes
103
+ if declared and declared.isdigit() and int(declared) > limit + MULTIPART_OVERHEAD:
104
+ raise DocumentTooLarge(
105
+ f"The request has {declared} bytes; slot {slot!r} allows {limit}",
106
+ details={"max_bytes": limit},
107
+ )
108
+ return await docs.attach(
109
+ name,
110
+ entity_id,
111
+ slot,
112
+ _chunks(file),
113
+ filename=file.filename or "file",
114
+ content_type=file.content_type or "application/octet-stream",
115
+ actor=actor,
116
+ )
117
+
118
+ if isinstance(docs.store, SupportsPresignedUrls) and any(
119
+ s.allows("presigned") for s in slots.values()
120
+ ):
121
+
122
+ @router.post(
123
+ "/{entity_id}/documents/{slot}/uploads",
124
+ response_model=UploadTicketOut,
125
+ status_code=status.HTTP_201_CREATED,
126
+ summary="Request a direct (presigned) upload",
127
+ description="PUT the file to `upload.url` with `upload.headers`, then POST "
128
+ "`/documents/{id}/confirm`.",
129
+ operation_id=f"{name}_request_upload",
130
+ )
131
+ async def request_upload(
132
+ payload: UploadRequest,
133
+ entity_id: IdType = Path(...), # type: ignore[valid-type]
134
+ slot: SlotName = Path(...), # type: ignore[valid-type]
135
+ actor: Any = Depends(actor_dependency),
136
+ ) -> Any:
137
+ ticket = await docs.request_upload(
138
+ name,
139
+ entity_id,
140
+ slot,
141
+ filename=payload.filename,
142
+ content_type=payload.content_type,
143
+ size=payload.size,
144
+ actor=actor,
145
+ )
146
+ return UploadTicketOut(
147
+ document=ticket.document,
148
+ upload=PresignedUpload(
149
+ url=ticket.upload.url,
150
+ method=ticket.upload.method,
151
+ headers=ticket.upload.headers,
152
+ expires_at=ticket.upload.expires_at,
153
+ ),
154
+ )
155
+
156
+ @router.delete(
157
+ "/{entity_id}/documents/{document_id}",
158
+ status_code=status.HTTP_204_NO_CONTENT,
159
+ response_class=Response,
160
+ summary="Detach a document",
161
+ operation_id=f"{name}_detach_document",
162
+ )
163
+ async def detach_document(
164
+ entity_id: IdType = Path(...), # type: ignore[valid-type]
165
+ document_id: str = Path(...),
166
+ actor: Any = Depends(actor_dependency),
167
+ ) -> Response:
168
+ await docs.detach(name, entity_id, document_id, actor=actor)
169
+ return Response(status_code=204)
170
+
171
+
172
+ def build_document_content_router(
173
+ manager: ResourceManager,
174
+ *,
175
+ actor_dependency: Any,
176
+ redirect_downloads: bool = False,
177
+ ) -> APIRouter:
178
+ """``/documents/{id}/content`` and ``/documents/{id}/confirm``."""
179
+ docs = manager.documents
180
+ assert docs is not None
181
+ router = APIRouter(prefix=f"/{docs.resource}", tags=[docs.resource])
182
+
183
+ @router.get(
184
+ "/{document_id}/content",
185
+ summary="Download a document",
186
+ response_class=StreamingResponse,
187
+ responses={
188
+ 200: {
189
+ "content": {"application/octet-stream": {}},
190
+ "description": "The document's content, with its own content type",
191
+ },
192
+ 307: {"description": "Redirect to a presigned URL"},
193
+ },
194
+ )
195
+ async def download(
196
+ document_id: str = Path(...), actor: Any = Depends(actor_dependency)
197
+ ) -> Response:
198
+ if redirect_downloads and isinstance(docs.store, SupportsPresignedUrls):
199
+ url = await docs.download_url(document_id, actor=actor)
200
+ return RedirectResponse(url.url, status_code=307)
201
+ document, stream = await docs.open(document_id, actor=actor)
202
+ headers = {
203
+ "Content-Disposition": content_disposition(document.filename),
204
+ "X-Content-Type-Options": "nosniff",
205
+ "Cache-Control": "private, no-store",
206
+ }
207
+ if document.size is not None:
208
+ headers["Content-Length"] = str(document.size)
209
+ return StreamingResponse(stream, media_type=document.content_type, headers=headers)
210
+
211
+ @router.post(
212
+ "/{document_id}/confirm",
213
+ response_model=DocumentRead,
214
+ summary="Confirm a presigned upload",
215
+ )
216
+ async def confirm(document_id: str = Path(...), actor: Any = Depends(actor_dependency)) -> Any:
217
+ return await docs.confirm_upload(document_id, actor=actor)
218
+
219
+ return router
@@ -0,0 +1,85 @@
1
+ """An endpoint for mail services' webhooks: bounces, complaints, deliveries.
2
+
3
+ ```python
4
+ from resource_engine.email import EmailEventHandler
5
+ from resource_engine_fastapi import mount_email_events
6
+ from resource_engine_http import parse_postmark
7
+
8
+ mount_email_events(
9
+ app, parse_postmark, EmailEventHandler(suppressions), token=SECRET, path="/webhooks/postmark"
10
+ )
11
+ ```
12
+
13
+ Configure the provider to call ``https://<app>/webhooks/postmark?token=<SECRET>``
14
+ (or with HTTP Basic, password ``<SECRET>``): requests without the token are
15
+ refused (401) before anything is parsed. Answers 204; a payload the parser
16
+ doesn't recognise gives no events and is still acknowledged, so the provider
17
+ doesn't retry it forever.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import base64
23
+ import hmac
24
+ from collections.abc import Callable, Sequence
25
+ from typing import Any
26
+
27
+ from fastapi import FastAPI, Request, Response
28
+ from resource_engine.email import EmailEventHandler
29
+ from resource_engine.ports.email import EmailEvent
30
+
31
+
32
+ def _token_of(request: Request) -> str | None:
33
+ if "token" in request.query_params:
34
+ return request.query_params["token"]
35
+ scheme, _, value = request.headers.get("authorization", "").partition(" ")
36
+ if scheme.lower() == "bearer":
37
+ return value.strip()
38
+ if scheme.lower() == "basic":
39
+ try:
40
+ return base64.b64decode(value).decode().partition(":")[2]
41
+ except (ValueError, UnicodeDecodeError):
42
+ return None
43
+ return None
44
+
45
+
46
+ def mount_email_events(
47
+ app: FastAPI,
48
+ parser: Callable[[Any], Sequence[EmailEvent]],
49
+ handler: EmailEventHandler,
50
+ *,
51
+ token: str | None,
52
+ path: str = "/webhooks/email",
53
+ ) -> None:
54
+ """``POST path``: ``parser(json)`` → ``EmailEvent``s → ``handler.handle``.
55
+
56
+ ``path``: one per provider when several send events
57
+ (``/webhooks/postmark``, ``/webhooks/ses``).
58
+
59
+ ``token``: the shared secret the provider sends (query ``token``, a bearer
60
+ token, or the Basic password). ``None`` accepts anyone: only behind a
61
+ gateway that authenticates the provider.
62
+ """
63
+
64
+ async def receive(request: Request) -> Response:
65
+ if token is not None and not hmac.compare_digest(_token_of(request) or "", token):
66
+ return Response(status_code=401)
67
+ try:
68
+ payload = await request.json()
69
+ except ValueError:
70
+ return Response(status_code=400)
71
+ events = parser(payload)
72
+ if events:
73
+ await handler.handle(events)
74
+ return Response(status_code=204)
75
+
76
+ app.add_api_route(
77
+ path,
78
+ receive,
79
+ methods=["POST"],
80
+ include_in_schema=False,
81
+ name=f"email-events:{path}",
82
+ )
83
+
84
+
85
+ __all__ = ["mount_email_events"]
@@ -0,0 +1,178 @@
1
+ """The engine's errors as HTTP answers: status codes and the error body."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from fastapi import FastAPI, Request
8
+ from fastapi.responses import JSONResponse
9
+ from resource_engine import DomainError, ResourceEngineError
10
+ from resource_engine import errors as e
11
+
12
+ STATUS_BY_ERROR: list[tuple[type[ResourceEngineError], int]] = [
13
+ (e.AuthenticationFailed, 401),
14
+ (e.PermissionDenied, 403),
15
+ (e.PrivilegeEscalation, 403),
16
+ (e.FieldNotWritable, 403),
17
+ (e.FieldNotReadable, 403),
18
+ (e.TenantRequired, 403),
19
+ (e.TenantMismatch, 403),
20
+ (e.InvalidPolicy, 422),
21
+ (e.ValidationFailed, 422),
22
+ (e.InvalidQuery, 400),
23
+ (e.EntityNotFound, 404),
24
+ (e.ResourceNotRegistered, 404),
25
+ (e.UnknownTransition, 404),
26
+ (e.ActionNotFound, 404),
27
+ (e.OperationNotEnabled, 405),
28
+ (e.TransitionNotAllowed, 409),
29
+ (e.VersionConflict, 409),
30
+ (e.VersionRequired, 428),
31
+ (e.IdempotencyKeyReused, 422),
32
+ (e.ReferenceNotFound, 422),
33
+ (e.ReferenceInUse, 409),
34
+ (e.DocumentSlotNotFound, 404),
35
+ (e.BlobNotFound, 404),
36
+ (e.ContentTypeNotAllowed, 415),
37
+ (e.DocumentTooLarge, 413),
38
+ (e.UploadNotVerified, 409),
39
+ (e.DocumentNotAvailable, 409),
40
+ (e.RequiredDocumentMissing, 409),
41
+ (e.StorageFailed, 502),
42
+ (e.ConfigurationError, 500),
43
+ (e.RemoteCallFailed, 502),
44
+ (e.RateLimited, 429),
45
+ ]
46
+
47
+
48
+ def authenticate_challenge(reason: str) -> str:
49
+ """``WWW-Authenticate`` for a refused credential: a ``DPoP`` challenge for
50
+ proof errors (RFC 9449), ``Bearer`` otherwise (RFC 6750)."""
51
+ if reason == "invalid_dpop_proof":
52
+ return f'DPoP error="invalid_dpop_proof", error_description="{reason}"'
53
+ if reason == "missing":
54
+ return "Bearer"
55
+ return f'Bearer error="invalid_token", error_description="{reason}"'
56
+
57
+
58
+ def status_for(exc: ResourceEngineError) -> int:
59
+ """The HTTP status of an engine error (500 for unknown ones)."""
60
+ for cls, status in STATUS_BY_ERROR:
61
+ if isinstance(exc, cls):
62
+ return status
63
+ return 500
64
+
65
+
66
+ def install_exception_handlers(app: FastAPI) -> None:
67
+ """Map engine and domain errors to JSON responses ``{"error": {...}}``.
68
+
69
+ 5xx answers (engine failures, and any other exception as a 500 ``RE-E000``
70
+ "Internal error") are reported (``resource_engine.reporting``)."""
71
+
72
+ @app.exception_handler(ResourceEngineError)
73
+ async def _engine_error(request: Request, exc: ResourceEngineError) -> JSONResponse:
74
+ status = status_for(exc)
75
+ if status >= 500:
76
+ await _report(request, exc, status)
77
+ headers = None
78
+ if isinstance(exc, e.AuthenticationFailed):
79
+ headers = {"WWW-Authenticate": authenticate_challenge(exc.reason)}
80
+ elif isinstance(exc, e.RateLimited):
81
+ details = exc.details if isinstance(exc.details, dict) else {}
82
+ retry = int(details.get("retry_after") or 1)
83
+ headers = {
84
+ "Retry-After": str(retry),
85
+ "RateLimit-Limit": str(details.get("limit")),
86
+ "RateLimit-Remaining": "0",
87
+ "RateLimit-Reset": str(retry),
88
+ }
89
+ return JSONResponse(status_code=status, content={"error": exc.to_dict()}, headers=headers)
90
+
91
+ @app.exception_handler(DomainError)
92
+ async def _domain_error(request: Request, exc: DomainError) -> JSONResponse:
93
+ return JSONResponse(status_code=422, content={"error": exc.to_dict()})
94
+
95
+ app.add_middleware(UnexpectedErrorMiddleware)
96
+ app.add_middleware(RateLimitHeadersMiddleware)
97
+
98
+
99
+ class RateLimitHeadersMiddleware:
100
+ """``RateLimit-Limit``, ``-Remaining`` and ``-Reset`` on responses to callers
101
+ the actor dependency rate-limited (``bearer_actor(..., rate_limiter=)``)."""
102
+
103
+ def __init__(self, app: Any) -> None:
104
+ self.app = app
105
+
106
+ async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
107
+ """Handle one ASGI call: add the rate limit headers to the response."""
108
+ if scope["type"] != "http":
109
+ await self.app(scope, receive, send)
110
+ return
111
+
112
+ async def with_headers(message: Any) -> None:
113
+ if message["type"] == "http.response.start":
114
+ decision = (scope.get("state") or {}).get("rate_limit")
115
+ if decision is not None:
116
+ names = {k.lower() for k, _ in message.get("headers", [])}
117
+ if b"ratelimit-limit" not in names:
118
+ message["headers"] = [
119
+ *message.get("headers", []),
120
+ (b"ratelimit-limit", str(decision.limit).encode()),
121
+ (b"ratelimit-remaining", str(decision.remaining).encode()),
122
+ (b"ratelimit-reset", str(decision.reset).encode()),
123
+ ]
124
+ await send(message)
125
+
126
+ await self.app(scope, receive, with_headers)
127
+
128
+
129
+ class UnexpectedErrorMiddleware:
130
+ """Any other exception: reported, answered with 500 ``RE-E000``.
131
+
132
+ A middleware rather than an ``Exception`` handler (which Starlette runs
133
+ outside every middleware), so the report and the response stay inside the
134
+ request: its request id and access log line."""
135
+
136
+ def __init__(self, app: Any) -> None:
137
+ self.app = app
138
+
139
+ async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
140
+ """Handle one ASGI call: report an unhandled exception and answer 500."""
141
+ if scope["type"] != "http":
142
+ await self.app(scope, receive, send)
143
+ return
144
+ started = False
145
+
146
+ async def tracking(message: dict[str, Any]) -> None:
147
+ nonlocal started
148
+ if message["type"] == "http.response.start":
149
+ started = True
150
+ await send(message)
151
+
152
+ try:
153
+ await self.app(scope, receive, tracking)
154
+ except Exception as exc:
155
+ if started:
156
+ raise
157
+ await _report(Request(scope), exc, 500)
158
+ response = JSONResponse(
159
+ status_code=500,
160
+ content={"error": {"code": "RE-E000", "message": "Internal error"}},
161
+ )
162
+ await response(scope, receive, send)
163
+
164
+
165
+ async def _report(request: Request, exc: BaseException, status: int) -> None:
166
+ """Report a 5xx with the route (not the raw path: ids stay out of grouping)."""
167
+ from resource_engine.reporting import report_error
168
+
169
+ route = getattr(request.scope.get("route"), "path", None) or request.url.path
170
+ await report_error(
171
+ exc,
172
+ where="http",
173
+ force=True,
174
+ actor=getattr(request.state, "principal", None),
175
+ method=request.method,
176
+ route=route,
177
+ status=status,
178
+ )
@@ -0,0 +1,109 @@
1
+ """Push endpoint for inbound events (webhooks).
2
+
3
+ Brokers that push over HTTP POST each message to this route: SAP Event Mesh
4
+ webhook subscriptions, SAP advanced event mesh REST delivery points, Pub/Sub push
5
+ subscriptions (with ``resource_engine_gcp.decode_pubsub_push``), Event Grid, or any
6
+ service sending the envelope JSON or CloudEvents.
7
+
8
+ Responses tell the broker what to do:
9
+
10
+ - ``204``: handled or duplicate; the broker must drop the message.
11
+ - ``503`` with ``Retry-After``: failed; the broker should redeliver.
12
+ - ``dead_letter_status`` (422 by default): it will never succeed (undecodable,
13
+ no handler, ``MessageRejected``...). Brokers differ in what they do with 4xx,
14
+ so set it to what yours dead-letters on.
15
+
16
+ Authenticate the caller with ``dependencies`` (e.g. a shared-secret or JWT check);
17
+ the engine's own inbound authorisation is still to come.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import math
23
+ from collections.abc import Callable, Mapping, Sequence
24
+ from enum import Enum
25
+ from typing import Any
26
+
27
+ from fastapi import APIRouter, Request, Response
28
+ from fastapi.responses import JSONResponse
29
+ from resource_engine.messaging import MessageProcessor, Outcome, decode_http, try_decode
30
+ from resource_engine.ports.messaging import ReceivedMessage
31
+
32
+ type HttpDecoder = Callable[[Mapping[str, str], bytes], ReceivedMessage]
33
+
34
+
35
+ def default_decoder(type_prefix: str = "") -> HttpDecoder:
36
+ """Envelope JSON or CloudEvents (structured or binary mode)."""
37
+ return lambda headers, body: try_decode(
38
+ lambda: decode_http(headers, body, type_prefix=type_prefix)
39
+ )
40
+
41
+
42
+ def build_event_receiver(
43
+ processor: MessageProcessor,
44
+ *,
45
+ path: str = "/events",
46
+ decode: HttpDecoder | None = None,
47
+ allowed_origins: Sequence[str] = (),
48
+ dead_letter_status: int = 422,
49
+ dependencies: Sequence[Any] | None = None,
50
+ tags: list[str] | None = None,
51
+ public: bool = False,
52
+ ) -> APIRouter:
53
+ """Router with ``POST {path}`` feeding ``processor`` and the CloudEvents webhook
54
+ validation handshake (``OPTIONS {path}``).
55
+
56
+ Args:
57
+ processor: Same ``MessageProcessor`` a pull consumer would use.
58
+ decode: Request to ``ReceivedMessage``; defaults to ``default_decoder()``.
59
+ allowed_origins: Origins accepted in the CloudEvents ``WebHook-Request-Origin``
60
+ handshake (``"*"`` for any). Empty: the handshake is refused.
61
+ dead_letter_status: Status for messages that must not be retried.
62
+ dependencies: FastAPI dependencies run before the handler: how callers
63
+ are authenticated (a bearer or Google-signed token, a shared
64
+ secret). Required: whoever can post here makes consumers act.
65
+ public: Accept calls without ``dependencies``, when the network
66
+ already authenticates them (a private network, a signature
67
+ checked by a proxy). Off by default.
68
+ """
69
+ if not dependencies and not public:
70
+ from resource_engine.errors import ConfigurationError
71
+
72
+ raise ConfigurationError(
73
+ f"The event receiver for {processor.name!r} has no authentication",
74
+ hint="Pass dependencies=[Depends(verify_caller)] (for Pub/Sub push, a "
75
+ "google_id_token(...) bearer check), or public=True when the network "
76
+ "already authenticates callers.",
77
+ doc="docs/messaging.md#push-endpoints",
78
+ )
79
+ decoder = decode or default_decoder()
80
+ route_tags: list[str | Enum] = list(tags or ["events"])
81
+ router = APIRouter(tags=route_tags, dependencies=list(dependencies or []))
82
+
83
+ @router.post(path, status_code=204, summary=f"Receive events for {processor.name}")
84
+ async def receive(request: Request) -> Response:
85
+ message = decoder(request.headers, await request.body())
86
+ result = await processor.process(message)
87
+ if result.outcome.settled:
88
+ return Response(status_code=204)
89
+ status = 503 if result.outcome is Outcome.RETRY else dead_letter_status
90
+ headers = {}
91
+ if result.outcome is Outcome.RETRY:
92
+ headers["Retry-After"] = str(max(1, math.ceil(result.delay_seconds)))
93
+ return JSONResponse(
94
+ status_code=status,
95
+ headers=headers,
96
+ content={"error": {"outcome": result.outcome.value, "message": result.error}},
97
+ )
98
+
99
+ @router.options(path, include_in_schema=False)
100
+ async def handshake(request: Request) -> Response:
101
+ origin = request.headers.get("webhook-request-origin")
102
+ if origin and ("*" in allowed_origins or origin in allowed_origins):
103
+ return Response(
104
+ status_code=200,
105
+ headers={"WebHook-Allowed-Origin": origin, "WebHook-Allowed-Rate": "*"},
106
+ )
107
+ return Response(status_code=403 if origin else 405)
108
+
109
+ return router