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,1031 @@
1
+ """Generate FastAPI routes from registered resources.
2
+
3
+ FastAPI only adapts HTTP to ``ResourceManager`` calls: no business logic lives here.
4
+ Endpoints are built with explicit signatures so that FastAPI validates bodies with
5
+ the resource's Pydantic schemas and documents them in OpenAPI.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import inspect
11
+ from collections.abc import Callable, Mapping, Sequence
12
+ from typing import Any, Literal, Union
13
+
14
+ from fastapi import (
15
+ APIRouter,
16
+ Body,
17
+ Depends,
18
+ FastAPI,
19
+ Header,
20
+ Path,
21
+ Query,
22
+ Request,
23
+ Response,
24
+ status,
25
+ )
26
+ from fastapi.responses import JSONResponse
27
+ from pydantic import BaseModel, create_model
28
+ from resource_engine import ListQuery, ResourceDefinition, ResourceManager, ResourceRegistry
29
+ from resource_engine.errors import InvalidQuery
30
+ from resource_engine.integration import EXPAND_PAGE_SIZE, dump_read, needs_dump
31
+ from resource_engine.versions import ApiVersion, Deprecation
32
+
33
+ from resource_engine_fastapi.documents import (
34
+ add_owner_document_routes,
35
+ build_document_content_router,
36
+ )
37
+ from resource_engine_fastapi.errors import install_exception_handlers
38
+ from resource_engine_fastapi.exports import ExportJobOut, build_export_router, printout_routes
39
+
40
+ type ActorDependency = Callable[..., Any]
41
+
42
+ _KW = inspect.Parameter.KEYWORD_ONLY
43
+
44
+
45
+ def _no_actor() -> None:
46
+ return None
47
+
48
+
49
+ def _param(name: str, annotation: Any, default: Any) -> inspect.Parameter:
50
+ return inspect.Parameter(name, _KW, annotation=annotation, default=default)
51
+
52
+
53
+ def _query_filters(kw: Mapping[str, Any]) -> dict[str, Any]:
54
+ """The manager's filters from a list endpoint's parameters: equalities,
55
+ ``<relation>.<field>`` and ``<field>[<op>]``."""
56
+ filters: dict[str, Any] = {}
57
+ for k, v in kw.items():
58
+ if v is None:
59
+ continue
60
+ if k.startswith("filter__"):
61
+ filters[k.removeprefix("filter__")] = v
62
+ elif k.startswith("related__"):
63
+ relation, _, fld = k.removeprefix("related__").partition("__")
64
+ filters[f"{relation}.{fld}"] = v
65
+ elif k.startswith("op__"):
66
+ fld, _, op = k.removeprefix("op__").rpartition("__")
67
+ filters[f"{fld}[{op}]"] = v
68
+ return filters
69
+
70
+
71
+ def _operator_params(fld: str, annotation: Any) -> list[inspect.Parameter]:
72
+ """``amount[gte]``-style query parameters for one filterable field: the
73
+ comparisons for ordered types, ``ne``, and ``in`` and ``nin`` as
74
+ comma-separated values."""
75
+ from resource_engine.integration import operators_for
76
+
77
+ params = []
78
+ for op in operators_for(annotation):
79
+ listed = op in ("in", "nin")
80
+ params.append(
81
+ _param(
82
+ f"op__{fld}__{op}",
83
+ (str if listed else annotation) | None,
84
+ Query(
85
+ None,
86
+ alias=f"{fld}[{op}]",
87
+ description=f"{fld} {op}" + (" (comma-separated values)" if listed else ""),
88
+ ),
89
+ )
90
+ )
91
+ return params
92
+
93
+
94
+ def _endpoint(
95
+ fn: Callable[..., Any], params: list[inspect.Parameter], name: str
96
+ ) -> Callable[..., Any]:
97
+ fn.__signature__ = inspect.Signature(params) # type: ignore[attr-defined]
98
+ fn.__name__ = name
99
+ return fn
100
+
101
+
102
+ def _summary(text: str | None) -> str | None:
103
+ return text.strip().splitlines()[0] if text and text.strip() else None
104
+
105
+
106
+ def _dump(value: Any) -> Any:
107
+ return dump_read(value)
108
+
109
+
110
+ def _respond(
111
+ value: Any,
112
+ status_code: int = 200,
113
+ *,
114
+ version_field: str | None = None,
115
+ response: Response | None = None,
116
+ ) -> Any:
117
+ """Results with hidden fields (field-level permissions) or expanded related
118
+ records are serialized directly, bypassing response-model validation, which
119
+ would require the hidden fields and drop the expansions. Versioned
120
+ resources answer with ``ETag: "<version>"``."""
121
+ version = getattr(value, version_field, None) if version_field else None
122
+ etag = None if version is None else f'"{version}"'
123
+ if needs_dump(value):
124
+ reply = JSONResponse(_dump(value), status_code=status_code)
125
+ if etag:
126
+ reply.headers["ETag"] = etag
127
+ return reply
128
+ if etag and response is not None:
129
+ response.headers["ETag"] = etag
130
+ return value
131
+
132
+
133
+ def parse_if_match(value: str | None) -> int | None:
134
+ """``If-Match: "3"`` (or ``W/"3"``) → 3; ``*`` or no header → ``None``."""
135
+ if value is None or value.strip() == "*":
136
+ return None
137
+ token = value.split(",")[0].strip().removeprefix("W/").strip('"')
138
+ try:
139
+ return int(token)
140
+ except ValueError:
141
+ raise InvalidQuery(
142
+ f"If-Match {value!r} is not a version ETag",
143
+ hint='Send the ETag the record was read with, e.g. If-Match: "3".',
144
+ ) from None
145
+
146
+
147
+ def _respond_page(page: dict[str, Any]) -> Any:
148
+ items = page["items"]
149
+ if not any(needs_dump(i) for i in items):
150
+ return page
151
+ return JSONResponse({**page, "items": [_dump(i) for i in items]})
152
+
153
+
154
+ def _page_model(read: Any, name: str | None = None) -> type[BaseModel]:
155
+ return create_model(
156
+ f"{name or read.__name__}Page",
157
+ items=(list[read], ...),
158
+ total=(int, ...),
159
+ offset=(int, ...),
160
+ limit=(int, ...),
161
+ )
162
+
163
+
164
+ def registry_of(manager: ResourceManager) -> ResourceRegistry:
165
+ """The registry the manager serves."""
166
+ return manager.registry
167
+
168
+
169
+ def build_resource_router(
170
+ definition: ResourceDefinition,
171
+ manager: ResourceManager,
172
+ *,
173
+ actor_dependency: ActorDependency = _no_actor,
174
+ api_version: ApiVersion | None = None,
175
+ deprecation: Deprecation | None = None,
176
+ ) -> APIRouter:
177
+ """Routes for one resource: CRUD, ``/transitions/<event>`` and ``/actions/<name>``.
178
+
179
+ ``actor_dependency`` is a FastAPI dependency whose result is passed to the
180
+ manager as ``actor``. It is the integration point for authentication; the
181
+ engine does not interpret it yet.
182
+
183
+ ``api_version``: serve an older version of the resource's API (its
184
+ schemas, converting input and output); ``deprecation`` marks the routes
185
+ deprecated in the OpenAPI document (docs/versioning.md).
186
+ """
187
+ name = definition.name
188
+ deprecation = deprecation or definition.resource_cls.deprecation
189
+ router = APIRouter(
190
+ prefix=f"/{name}",
191
+ tags=[name],
192
+ deprecated=True if deprecation is not None else None,
193
+ )
194
+ schemas = (
195
+ {
196
+ role: api_version.schema(role, definition.schemas)
197
+ for role in ("read", "create", "update")
198
+ if api_version.schema(role, definition.schemas) is not None
199
+ }
200
+ if api_version is not None
201
+ else definition.schemas
202
+ )
203
+ id_param = _param("entity_id", definition.id_type, Path(...))
204
+ actor_param = _param("actor", Any, Depends(actor_dependency))
205
+ # tenant-scoped resources: cross-tenant callers may name a tenant
206
+ tenant_params = (
207
+ [
208
+ _param(
209
+ "tenant",
210
+ str | None,
211
+ Query(None, description="Tenant to act on (cross-tenant callers)"),
212
+ )
213
+ ]
214
+ if definition.tenant_field
215
+ else []
216
+ )
217
+ read = schemas.get("read")
218
+ # a base resource answers with each record's subtype schema
219
+ subtypes = (
220
+ [d.schemas["read"] for d in registry_of(manager).subtypes(name).values()]
221
+ if api_version is None
222
+ else []
223
+ )
224
+ out: Any = Union[tuple(subtypes)] if subtypes else read # noqa: UP007
225
+ to_read = api_version.to_read if api_version is not None else None
226
+ docs = definition.operation_docs
227
+ version_field = definition.version_field
228
+ # versioned resources: responses carry ETag, writes accept If-Match
229
+ response_param = _param("response", Response, inspect.Parameter.empty)
230
+ match_params = (
231
+ [
232
+ _param(
233
+ "if_match",
234
+ str | None,
235
+ Header(
236
+ None,
237
+ alias="If-Match",
238
+ description="ETag of the record as read; a stale one is refused (409)",
239
+ ),
240
+ )
241
+ ]
242
+ if version_field
243
+ else []
244
+ )
245
+
246
+ # every write accepts Idempotency-Key: a retry returns the first result
247
+ key_params = [
248
+ _param(
249
+ "idempotency_key",
250
+ str | None,
251
+ Header(
252
+ None,
253
+ alias="Idempotency-Key",
254
+ description="Retry-safe key: the same request with the same key runs once "
255
+ "and later calls return its result; another request with it is refused (422)",
256
+ ),
257
+ )
258
+ ]
259
+
260
+ reverse = manager.reverse.get(name, {})
261
+ relations = [*definition.references, *(f"{r}[:size]" for r in reverse)]
262
+ nested_hint = ". Nest with dots (invoices.customer_record), up to 3 levels"
263
+ expand_params = (
264
+ [
265
+ _param(
266
+ "expand",
267
+ str | None,
268
+ Query(
269
+ None,
270
+ description="Comma-separated relations to include: "
271
+ + ", ".join(relations)
272
+ + (
273
+ f" (reverse relations embed one page, {EXPAND_PAGE_SIZE} by default)"
274
+ if reverse
275
+ else ""
276
+ )
277
+ + nested_hint,
278
+ ),
279
+ )
280
+ ]
281
+ if relations
282
+ else []
283
+ )
284
+
285
+ def expand_of(kw: dict[str, Any]) -> tuple[str, ...]:
286
+ raw = kw.get("expand") or ""
287
+ return tuple(part.strip() for part in raw.split(",") if part.strip())
288
+
289
+ def reply(value: Any, kw: dict[str, Any], status_code: int = 200) -> Any:
290
+ if to_read is not None: # an older version: its shape, from the current one
291
+ converted = JSONResponse(to_read(_dump(value)), status_code=status_code)
292
+ record_version = getattr(value, version_field, None) if version_field else None
293
+ if record_version is not None:
294
+ converted.headers["ETag"] = f'"{record_version}"'
295
+ return converted
296
+ return _respond(
297
+ value, status_code, version_field=version_field, response=kw.get("response")
298
+ )
299
+
300
+ def given(payload: Any, convert: Any) -> Any:
301
+ """An older version's input as the current schema's input."""
302
+ if convert is None or api_version is None:
303
+ return payload
304
+ return convert(payload.model_dump(exclude_unset=True))
305
+
306
+ if definition.exposed("list"):
307
+ filter_params = []
308
+ for fld in definition.filterable:
309
+ annotation = read.model_fields[fld].annotation if read else str
310
+ # internal name, public alias: a field may be called like a parameter (actor)
311
+ filter_params.append(
312
+ _param(f"filter__{fld}", annotation | None, Query(None, alias=fld)) # type: ignore[operator]
313
+ )
314
+ filter_params += _operator_params(fld, annotation)
315
+ if definition.searchable:
316
+ filter_params.append(
317
+ _param(
318
+ "search",
319
+ str | None,
320
+ Query(
321
+ None,
322
+ alias="q",
323
+ max_length=1000,
324
+ description="Words that must all appear, ignoring case, in one of "
325
+ f"{', '.join(definition.searchable)}",
326
+ ),
327
+ )
328
+ )
329
+ for ref in definition.references.values():
330
+ target = registry_of(manager).get(ref.target)
331
+ target_read = target.schemas.get("read")
332
+ for fld in target.filterable:
333
+ annotation = target_read.model_fields[fld].annotation if target_read else str
334
+ filter_params.append(
335
+ _param(
336
+ f"related__{ref.name}__{fld}",
337
+ annotation | None, # type: ignore[operator]
338
+ Query(
339
+ None,
340
+ alias=f"{ref.name}.{fld}",
341
+ description=f"Filter by the related {ref.target} record's {fld}",
342
+ ),
343
+ )
344
+ )
345
+
346
+ async def list_endpoint(**kw: Any) -> Any:
347
+ order = kw.pop("order_by")
348
+ filters = _query_filters(kw)
349
+ query = ListQuery(
350
+ offset=kw.pop("offset"),
351
+ limit=kw.pop("limit"),
352
+ order_by=[o for o in (order or "").split(",") if o],
353
+ filters=filters,
354
+ search=kw.get("search"),
355
+ )
356
+ page = await manager.list(
357
+ name,
358
+ query,
359
+ actor=kw.get("actor"),
360
+ tenant=kw.get("tenant"),
361
+ expand=expand_of(kw),
362
+ )
363
+ if to_read is not None:
364
+ return JSONResponse(
365
+ {
366
+ "items": [to_read(_dump(i)) for i in page.items],
367
+ "total": page.total,
368
+ "offset": page.offset,
369
+ "limit": page.limit,
370
+ }
371
+ )
372
+ return _respond_page(
373
+ {
374
+ "items": page.items,
375
+ "total": page.total,
376
+ "offset": page.offset,
377
+ "limit": page.limit,
378
+ }
379
+ )
380
+
381
+ list_endpoint.cache_control = definition.cache_control # type: ignore[attr-defined]
382
+ router.add_api_route(
383
+ "",
384
+ _endpoint(
385
+ list_endpoint,
386
+ [
387
+ _param("offset", int, Query(0, ge=0)),
388
+ _param("limit", int, Query(50, ge=1, le=definition.max_page_size)),
389
+ _param(
390
+ "order_by",
391
+ str | None,
392
+ Query(
393
+ None, description="Comma-separated fields; prefix '-' for descending"
394
+ ),
395
+ ),
396
+ *filter_params,
397
+ *expand_params,
398
+ *tenant_params,
399
+ actor_param,
400
+ ],
401
+ f"list_{name}",
402
+ ),
403
+ methods=["GET"],
404
+ response_model=_page_model(out, read.__name__) if read else None,
405
+ summary=_summary(docs.get("list")) or f"List {name}",
406
+ description=docs.get("list"),
407
+ )
408
+
409
+ def export_query(kw: Mapping[str, Any]) -> ListQuery:
410
+ return ListQuery(
411
+ order_by=[o for o in (kw.get("order_by") or "").split(",") if o],
412
+ filters=_query_filters(kw),
413
+ search=kw.get("search"),
414
+ )
415
+
416
+ async def export_endpoint(**kw: Any) -> Any:
417
+ from resource_engine.exports import export_table
418
+
419
+ try:
420
+ content, media_type, filename = await export_table(
421
+ manager,
422
+ name,
423
+ export_query(kw),
424
+ format=kw["format"],
425
+ actor=kw.get("actor"),
426
+ tenant=kw.get("tenant"),
427
+ )
428
+ except InvalidQuery as exc:
429
+ if (
430
+ manager.exports is not None
431
+ and isinstance(exc.details, dict)
432
+ and ("max_rows" in exc.details)
433
+ ):
434
+ exc.hint = f"Export it in the background: POST /{name}/exports."
435
+ raise
436
+ return Response(
437
+ content,
438
+ media_type=media_type,
439
+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},
440
+ )
441
+
442
+ router.add_api_route(
443
+ "/export",
444
+ _endpoint(
445
+ export_endpoint,
446
+ [
447
+ _param(
448
+ "format",
449
+ Literal["csv", "xlsx"],
450
+ Query("csv", description="csv (UTF-8, with a BOM for Excel) or xlsx"),
451
+ ),
452
+ _param(
453
+ "order_by",
454
+ str | None,
455
+ Query(
456
+ None, description="Comma-separated fields; prefix '-' for descending"
457
+ ),
458
+ ),
459
+ *filter_params,
460
+ *tenant_params,
461
+ actor_param,
462
+ ],
463
+ f"export_{name}",
464
+ ),
465
+ methods=["GET"],
466
+ response_class=Response,
467
+ responses={
468
+ 200: {
469
+ "content": {
470
+ "text/csv": {},
471
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {},
472
+ },
473
+ "description": "The list as a file, with the caller's permissions",
474
+ }
475
+ },
476
+ summary=f"Export {name} as CSV or XLSX",
477
+ description="The list with the same filters, sorting and permissions, as a file "
478
+ "(at most 10 000 rows).",
479
+ )
480
+
481
+ if manager.exports is not None:
482
+ exports = manager.exports
483
+
484
+ async def export_job_endpoint(**kw: Any) -> Any:
485
+ job = await exports.request(
486
+ name,
487
+ export_query(kw),
488
+ format=kw["format"],
489
+ actor=kw.get("actor"),
490
+ tenant=kw.get("tenant"),
491
+ )
492
+ base = kw["request"].url.path.removesuffix(f"/{name}/exports")
493
+ return JSONResponse(
494
+ job.to_dict(),
495
+ status_code=status.HTTP_202_ACCEPTED,
496
+ headers={"Location": f"{base}/{exports.path}/{job.id}"},
497
+ )
498
+
499
+ router.add_api_route(
500
+ "/exports",
501
+ _endpoint(
502
+ export_job_endpoint,
503
+ [
504
+ _param(
505
+ "format",
506
+ Literal["csv", "xlsx"],
507
+ Query("csv", description="csv or xlsx"),
508
+ ),
509
+ _param(
510
+ "order_by",
511
+ str | None,
512
+ Query(
513
+ None,
514
+ description="Comma-separated fields; prefix '-' for descending",
515
+ ),
516
+ ),
517
+ *filter_params,
518
+ *tenant_params,
519
+ actor_param,
520
+ _param("request", Request, inspect.Parameter.empty),
521
+ ],
522
+ f"start_export_{name}",
523
+ ),
524
+ methods=["POST"],
525
+ status_code=status.HTTP_202_ACCEPTED,
526
+ response_model=ExportJobOut,
527
+ summary=f"Export {name} in the background",
528
+ description="Checks the permission and the filters, then writes the file in "
529
+ f"the background (up to {exports.max_rows} rows). Follow `Location` "
530
+ f"(`/{exports.path}/{{id}}`) until the status is `done`, then download "
531
+ f"`/{exports.path}/{{id}}/content`.",
532
+ )
533
+
534
+ if definition.exposed("get"):
535
+
536
+ async def get_endpoint(**kw: Any) -> Any:
537
+ result = await manager.get(
538
+ name,
539
+ kw["entity_id"],
540
+ actor=kw["actor"],
541
+ tenant=kw.get("tenant"),
542
+ expand=expand_of(kw),
543
+ )
544
+ return reply(result, kw)
545
+
546
+ get_endpoint.cache_control = definition.cache_control # type: ignore[attr-defined]
547
+ router.add_api_route(
548
+ "/{entity_id}",
549
+ _endpoint(
550
+ get_endpoint,
551
+ [id_param, *expand_params, *tenant_params, actor_param, response_param],
552
+ f"get_{name}",
553
+ ),
554
+ methods=["GET"],
555
+ response_model=out,
556
+ summary=_summary(docs.get("get")) or f"Get one of {name}",
557
+ description=docs.get("get"),
558
+ )
559
+ printout_routes(router, definition, manager, id_param, tenant_params, actor_param)
560
+
561
+ if definition.exposed("create"):
562
+
563
+ async def create_endpoint(**kw: Any) -> Any:
564
+ result = await manager.create(
565
+ name,
566
+ given(kw["payload"], api_version.from_create if api_version else None),
567
+ actor=kw["actor"],
568
+ tenant=kw.get("tenant"),
569
+ idempotency_key=kw.get("idempotency_key"),
570
+ )
571
+ return reply(result, kw, 201)
572
+
573
+ router.add_api_route(
574
+ "",
575
+ _endpoint(
576
+ create_endpoint,
577
+ [
578
+ _param("payload", schemas["create"], Body(...)),
579
+ *tenant_params,
580
+ *key_params,
581
+ actor_param,
582
+ response_param,
583
+ ],
584
+ f"create_{name}",
585
+ ),
586
+ methods=["POST"],
587
+ status_code=status.HTTP_201_CREATED,
588
+ response_model=out,
589
+ summary=_summary(docs.get("create")) or f"Create {name}",
590
+ description=docs.get("create"),
591
+ )
592
+
593
+ if definition.exposed("update"):
594
+
595
+ async def update_endpoint(**kw: Any) -> Any:
596
+ result = await manager.update(
597
+ name,
598
+ kw["entity_id"],
599
+ given(kw["payload"], api_version.from_update if api_version else None),
600
+ actor=kw["actor"],
601
+ tenant=kw.get("tenant"),
602
+ expected_version=parse_if_match(kw.get("if_match")),
603
+ idempotency_key=kw.get("idempotency_key"),
604
+ )
605
+ return reply(result, kw)
606
+
607
+ router.add_api_route(
608
+ "/{entity_id}",
609
+ _endpoint(
610
+ update_endpoint,
611
+ [
612
+ id_param,
613
+ _param("payload", schemas["update"], Body(...)),
614
+ *tenant_params,
615
+ *match_params,
616
+ *key_params,
617
+ actor_param,
618
+ response_param,
619
+ ],
620
+ f"update_{name}",
621
+ ),
622
+ methods=["PATCH"],
623
+ response_model=out,
624
+ summary=_summary(docs.get("update")) or f"Update {name}",
625
+ description=docs.get("update"),
626
+ )
627
+
628
+ if definition.exposed("delete"):
629
+
630
+ async def delete_endpoint(**kw: Any) -> Response:
631
+ await manager.delete(
632
+ name,
633
+ kw["entity_id"],
634
+ actor=kw["actor"],
635
+ tenant=kw.get("tenant"),
636
+ expected_version=parse_if_match(kw.get("if_match")),
637
+ idempotency_key=kw.get("idempotency_key"),
638
+ )
639
+ return Response(status_code=status.HTTP_204_NO_CONTENT)
640
+
641
+ router.add_api_route(
642
+ "/{entity_id}",
643
+ _endpoint(
644
+ delete_endpoint,
645
+ [id_param, *tenant_params, *match_params, *key_params, actor_param],
646
+ f"delete_{name}",
647
+ ),
648
+ methods=["DELETE"],
649
+ status_code=status.HTTP_204_NO_CONTENT,
650
+ response_class=Response,
651
+ summary=_summary(docs.get("delete")) or f"Delete {name}",
652
+ description=docs.get("delete"),
653
+ )
654
+
655
+ if definition.machine is not None and definition.expose_transitions:
656
+
657
+ async def allowed_endpoint(entity_id: Any, actor: Any, tenant: Any = None) -> list[str]:
658
+ return await manager.allowed_transitions(name, entity_id, actor=actor, tenant=tenant)
659
+
660
+ router.add_api_route(
661
+ "/{entity_id}/transitions",
662
+ _endpoint(
663
+ allowed_endpoint,
664
+ [id_param, *tenant_params, actor_param],
665
+ f"allowed_transitions_{name}",
666
+ ),
667
+ methods=["GET"],
668
+ response_model=list[str],
669
+ summary="Transitions allowed from the current state",
670
+ )
671
+ if manager.has_history and definition.audited:
672
+ from resource_engine.audit import StateChange
673
+
674
+ several = len(definition.machines) > 1
675
+ machine_params = (
676
+ [
677
+ inspect.Parameter(
678
+ "machine",
679
+ inspect.Parameter.KEYWORD_ONLY,
680
+ default=Query(None, description="Only this state machine"),
681
+ annotation=Literal[tuple(definition.machines)] | None,
682
+ )
683
+ ]
684
+ if several
685
+ else []
686
+ )
687
+
688
+ async def history_endpoint(
689
+ entity_id: Any, actor: Any, tenant: Any = None, machine: Any = None
690
+ ) -> Any:
691
+ return await manager.history(
692
+ name, entity_id, actor=actor, tenant=tenant, machine=machine
693
+ )
694
+
695
+ router.add_api_route(
696
+ "/{entity_id}/history",
697
+ _endpoint(
698
+ history_endpoint,
699
+ [id_param, *tenant_params, *machine_params, actor_param],
700
+ f"history_{name}",
701
+ ),
702
+ methods=["GET"],
703
+ response_model=list[StateChange],
704
+ summary="State history",
705
+ description="The record's creation and committed transitions, oldest "
706
+ "first, with who made them and when (from the audit trail).",
707
+ )
708
+ for event in definition.transitions:
709
+ owner_machine = definition.machine_for(event)
710
+ sm_doc = inspect.getdoc(owner_machine.machine_cls) if owner_machine else ""
711
+ router.add_api_route(
712
+ f"/{{entity_id}}/transitions/{event}",
713
+ _transition_endpoint(
714
+ definition,
715
+ manager,
716
+ event,
717
+ id_param,
718
+ [*tenant_params, *match_params, *key_params, actor_param, response_param],
719
+ reply,
720
+ ),
721
+ methods=["POST"],
722
+ response_model=out,
723
+ summary=f"Transition: {event}",
724
+ description=sm_doc or None,
725
+ )
726
+
727
+ for action in definition.actions.values():
728
+
729
+ def make_action(
730
+ action_name: str = action.name,
731
+ schema: Any = action.input_schema,
732
+ instance: bool = action.instance,
733
+ ) -> Callable[..., Any]:
734
+ async def action_endpoint(**kw: Any) -> Any:
735
+ result = await manager.run_action(
736
+ name,
737
+ kw.get("entity_id"),
738
+ action_name,
739
+ kw.get("payload"),
740
+ actor=kw["actor"],
741
+ tenant=kw.get("tenant"),
742
+ expected_version=parse_if_match(kw.get("if_match")),
743
+ idempotency_key=kw.get("idempotency_key"),
744
+ )
745
+ return reply(result, kw)
746
+
747
+ params = [id_param] if instance else []
748
+ if schema is not None:
749
+ params.append(_param("payload", schema, Body(...)))
750
+ params += [
751
+ *tenant_params,
752
+ *(match_params if instance else []),
753
+ *key_params,
754
+ actor_param,
755
+ ]
756
+ params.append(response_param)
757
+ return _endpoint(action_endpoint, params, f"{name}_{action_name}")
758
+
759
+ path = (
760
+ f"/{{entity_id}}/actions/{action.name}"
761
+ if action.instance
762
+ else f"/actions/{action.name}"
763
+ )
764
+ response_model = action.output_schema or (out if action.instance else None)
765
+ router.add_api_route(
766
+ path,
767
+ make_action(),
768
+ methods=["POST"],
769
+ response_model=response_model,
770
+ summary=_summary(action.description) or f"Action: {action.name}",
771
+ description=action.description,
772
+ )
773
+
774
+ for relation, related in reverse.items(): # a reverse reference or a link
775
+ router.add_api_route(
776
+ f"/{{entity_id}}/{relation}",
777
+ _related_endpoint(manager, definition, relation, related, id_param, actor_param),
778
+ methods=["GET"],
779
+ response_model=_page_model(owner_read)
780
+ if (owner_read := manager.registry.get(related.owner).schemas.get("read"))
781
+ else None,
782
+ summary=f"{related.owner} of one {name} record",
783
+ description=(
784
+ f"The {related.owner} records whose {related.field} is this {name} record"
785
+ if related.field
786
+ else f"The {related.owner} records linked to this {name} record through "
787
+ f"{getattr(related, 'join', '')}"
788
+ )
789
+ + f", paged, with the caller's list permissions on {related.owner}.",
790
+ )
791
+
792
+ add_owner_document_routes(router, definition, manager, actor_dependency)
793
+ if deprecation is not None: # the sunset, for clients and the contract check
794
+ for route in router.routes:
795
+ extra = dict(getattr(route, "openapi_extra", None) or {})
796
+ extra["x-deprecation"] = deprecation.to_dict()
797
+ route.openapi_extra = extra # type: ignore[attr-defined]
798
+ if hasattr(route, "description"):
799
+ text = route.description or ""
800
+ route.description = (
801
+ f"{deprecation.notice()}\n\n{text}" if text else deprecation.notice()
802
+ )
803
+ return router
804
+
805
+
806
+ def _related_endpoint(
807
+ manager: ResourceManager,
808
+ definition: ResourceDefinition,
809
+ relation: str,
810
+ ref: Any,
811
+ id_param: inspect.Parameter,
812
+ actor_param: inspect.Parameter,
813
+ ) -> Callable[..., Any]:
814
+ owner = manager.registry.get(ref.owner)
815
+ owner_read = owner.schemas.get("read")
816
+ params = [
817
+ id_param,
818
+ _param("offset", int, Query(0, ge=0)),
819
+ _param("limit", int, Query(50, ge=1, le=owner.max_page_size)),
820
+ _param(
821
+ "order_by",
822
+ str | None,
823
+ Query(None, description="Comma-separated fields; prefix '-' for descending"),
824
+ ),
825
+ ]
826
+ for fld in owner.filterable:
827
+ if fld == ref.field:
828
+ continue
829
+ annotation = owner_read.model_fields[fld].annotation if owner_read else str
830
+ params.append(_param(f"filter__{fld}", annotation | None, Query(None, alias=fld))) # type: ignore[operator]
831
+ if owner.references:
832
+ params.append(
833
+ _param(
834
+ "expand",
835
+ str | None,
836
+ Query(None, description="Relations of the listed records to include"),
837
+ )
838
+ )
839
+ if definition.tenant_field:
840
+ params.append(_param("tenant", str | None, Query(None)))
841
+ params.append(actor_param)
842
+
843
+ async def related_endpoint(**kw: Any) -> Any:
844
+ order = kw.pop("order_by")
845
+ query = ListQuery(
846
+ offset=kw.pop("offset"),
847
+ limit=kw.pop("limit"),
848
+ order_by=[o for o in (order or "").split(",") if o],
849
+ filters={
850
+ k.removeprefix("filter__"): v
851
+ for k, v in kw.items()
852
+ if k.startswith("filter__") and v is not None
853
+ },
854
+ )
855
+ expand = tuple(p.strip() for p in (kw.get("expand") or "").split(",") if p.strip())
856
+ page = await manager.list_related(
857
+ definition.name,
858
+ kw["entity_id"],
859
+ relation,
860
+ query,
861
+ actor=kw.get("actor"),
862
+ tenant=kw.get("tenant"),
863
+ expand=expand,
864
+ )
865
+ return _respond_page(
866
+ {"items": page.items, "total": page.total, "offset": page.offset, "limit": page.limit}
867
+ )
868
+
869
+ return _endpoint(related_endpoint, params, f"{definition.name}_{relation}")
870
+
871
+
872
+ def _transition_endpoint(
873
+ definition: ResourceDefinition,
874
+ manager: ResourceManager,
875
+ event: str,
876
+ id_param: inspect.Parameter,
877
+ tail: list[inspect.Parameter],
878
+ reply: Callable[[Any, dict[str, Any]], Any] | None = None,
879
+ ) -> Callable[..., Any]:
880
+ schema = definition.transition_schemas.get(event)
881
+
882
+ async def transition_endpoint(**kw: Any) -> Any:
883
+ result = await manager.transition(
884
+ definition.name,
885
+ kw["entity_id"],
886
+ event,
887
+ kw.get("payload"),
888
+ actor=kw["actor"],
889
+ tenant=kw.get("tenant"),
890
+ expected_version=parse_if_match(kw.get("if_match")),
891
+ idempotency_key=kw.get("idempotency_key"),
892
+ )
893
+ if reply is not None:
894
+ return reply(result, kw)
895
+ return _respond(result, version_field=definition.version_field, response=kw.get("response"))
896
+
897
+ params = [id_param]
898
+ if schema is not None:
899
+ params.append(_param("payload", schema, Body(...)))
900
+ params += tail
901
+ return _endpoint(transition_endpoint, params, f"{definition.name}_{event}")
902
+
903
+
904
+ def build_router(
905
+ registry: ResourceRegistry,
906
+ manager: ResourceManager,
907
+ *,
908
+ prefix: str = "",
909
+ actor_dependency: ActorDependency = _no_actor,
910
+ redirect_downloads: bool = False,
911
+ version: str | None = None,
912
+ current: bool = True,
913
+ deprecation: Deprecation | None = None,
914
+ ) -> APIRouter:
915
+ """Routes for every registered resource (and document downloads, if enabled).
916
+
917
+ ``redirect_downloads`` answers downloads with a 307 to a presigned URL instead
918
+ of streaming the content through the API.
919
+
920
+ ``version``: the API version these routes serve. An older one (``current``
921
+ false) uses each resource's ``api_versions[version]`` where it has one;
922
+ ``deprecation`` deprecates the whole version.
923
+ """
924
+ router = APIRouter(prefix=prefix)
925
+ if getattr(manager.authorizer, "catalog", None) is not None:
926
+ from resource_engine_fastapi.authz import build_authz_router
927
+
928
+ router.include_router(build_authz_router(manager, actor_dependency=actor_dependency))
929
+ if manager.exports is not None and current:
930
+ router.include_router(
931
+ build_export_router(
932
+ manager, actor_dependency=actor_dependency, redirect_downloads=redirect_downloads
933
+ )
934
+ )
935
+ if manager.documents is not None:
936
+ router.include_router(
937
+ build_document_content_router(
938
+ manager, actor_dependency=actor_dependency, redirect_downloads=redirect_downloads
939
+ )
940
+ )
941
+ for definition in registry:
942
+ api = (
943
+ definition.resource_cls.api_versions.get(version)
944
+ if version is not None and not current
945
+ else None
946
+ )
947
+ router.include_router(
948
+ build_resource_router(
949
+ definition,
950
+ manager,
951
+ actor_dependency=actor_dependency,
952
+ api_version=api,
953
+ deprecation=(api.deprecation if api else None) or deprecation,
954
+ )
955
+ )
956
+ return router
957
+
958
+
959
+ def mount_resources(
960
+ app: FastAPI,
961
+ registry: ResourceRegistry,
962
+ manager: ResourceManager,
963
+ *,
964
+ prefix: str = "",
965
+ actor_dependency: ActorDependency = _no_actor,
966
+ redirect_downloads: bool = False,
967
+ access_log: bool = False,
968
+ http_cache: bool = True,
969
+ versions: Sequence[str] = (),
970
+ deprecated: Mapping[str, Deprecation] | None = None,
971
+ ) -> None:
972
+ """Include every registered resource in ``app`` and install error handlers.
973
+ ``access_log`` adds the access log and request ids (``install_access_log``);
974
+ ``http_cache`` the ETag / 304 handling of ``GET`` (docs/caching.md).
975
+
976
+ ``versions`` (``["v1", "v2"]``, oldest first) serves each under its own
977
+ prefix (``/v1/...``); the last is the current one, and older ones use the
978
+ resources' ``api_versions``. ``deprecated`` deprecates whole versions.
979
+ Deprecated routes answer with ``Deprecation``, ``Sunset`` and ``Link``
980
+ headers (docs/versioning.md)."""
981
+ deprecated = dict(deprecated or {})
982
+ unknown = sorted(set(deprecated) - set(versions))
983
+ if unknown:
984
+ from resource_engine.errors import ConfigurationError
985
+
986
+ raise ConfigurationError(
987
+ f"Deprecated API versions {unknown} are not served",
988
+ hint=f"Served versions: {list(versions)}",
989
+ doc="docs/versioning.md",
990
+ )
991
+ notices: dict[str, Deprecation] = {}
992
+ for index, version in enumerate(versions or [None]):
993
+ current = index == len(versions) - 1 if versions else True
994
+ version_prefix = f"{prefix}/{version}" if version else prefix
995
+ whole = deprecated.get(version) if version else None
996
+ app.include_router(
997
+ build_router(
998
+ registry,
999
+ manager,
1000
+ prefix=version_prefix,
1001
+ actor_dependency=actor_dependency,
1002
+ redirect_downloads=redirect_downloads,
1003
+ version=version,
1004
+ current=current,
1005
+ deprecation=whole,
1006
+ )
1007
+ )
1008
+ for definition in registry:
1009
+ api = (
1010
+ definition.resource_cls.api_versions.get(version)
1011
+ if not current and version is not None
1012
+ else None
1013
+ )
1014
+ notice = (
1015
+ (api.deprecation if api else None) or whole or definition.resource_cls.deprecation
1016
+ )
1017
+ if notice is not None:
1018
+ notices[f"{version_prefix}/{definition.name}"] = notice
1019
+ if notices:
1020
+ from resource_engine_fastapi.versioning import DeprecationMiddleware
1021
+
1022
+ app.add_middleware(DeprecationMiddleware, notices=notices)
1023
+ install_exception_handlers(app)
1024
+ if http_cache:
1025
+ from resource_engine_fastapi.caching import ConditionalGetMiddleware
1026
+
1027
+ app.add_middleware(ConditionalGetMiddleware)
1028
+ if access_log:
1029
+ from resource_engine_fastapi.access import install_access_log
1030
+
1031
+ install_access_log(app)