craftainer-crud 0.2.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.
- craftainer_crud/README.md +100 -0
- craftainer_crud/__init__.py +5 -0
- craftainer_crud/config.py +69 -0
- craftainer_crud/controllers/README.md +303 -0
- craftainer_crud/controllers/__init__.py +1 -0
- craftainer_crud/controllers/crud_actions.py +222 -0
- craftainer_crud/controllers/crud_manifest.py +145 -0
- craftainer_crud/controllers/crud_query.py +364 -0
- craftainer_crud/controllers/crud_router.py +1502 -0
- craftainer_crud/controllers/crud_stats.py +255 -0
- craftainer_crud/interfaces/README.md +150 -0
- craftainer_crud/interfaces/__init__.py +1 -0
- craftainer_crud/interfaces/base.py +825 -0
- craftainer_crud/interfaces/cache.py +34 -0
- craftainer_crud/interfaces/compat.py +121 -0
- craftainer_crud/interfaces/dependency.py +101 -0
- craftainer_crud/manifest/__init__.py +19 -0
- craftainer_crud/manifest/builder.py +204 -0
- craftainer_crud/manifest/models.py +138 -0
- craftainer_crud/manifest/registry.py +94 -0
- craftainer_crud/models/README.md +44 -0
- craftainer_crud/models/__init__.py +1 -0
- craftainer_crud/models/base.py +55 -0
- craftainer_crud/models/mixins.py +94 -0
- craftainer_crud/models/revision.py +34 -0
- craftainer_crud/py.typed +0 -0
- craftainer_crud/repositories/README.md +130 -0
- craftainer_crud/repositories/__init__.py +1 -0
- craftainer_crud/repositories/base.py +135 -0
- craftainer_crud/repositories/filtering.py +42 -0
- craftainer_crud/repositories/memory.py +523 -0
- craftainer_crud/repositories/sqlalchemy.py +543 -0
- craftainer_crud/repositories/stats.py +81 -0
- craftainer_crud/views/README.md +49 -0
- craftainer_crud/views/__init__.py +4 -0
- craftainer_crud/views/base.py +57 -0
- craftainer_crud/views/bulk.py +17 -0
- craftainer_crud/views/revision.py +17 -0
- craftainer_crud/views/stats.py +89 -0
- craftainer_crud/web_components.py +469 -0
- craftainer_crud/xml_codec.py +67 -0
- craftainer_crud-0.2.0.dist-info/METADATA +134 -0
- craftainer_crud-0.2.0.dist-info/RECORD +45 -0
- craftainer_crud-0.2.0.dist-info/WHEEL +4 -0
- craftainer_crud-0.2.0.dist-info/licenses/LICENSE +674 -0
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# craftainer_crud/
|
|
2
|
+
|
|
3
|
+
The generic CRUD framework a host application's resource packages build on —
|
|
4
|
+
router factories, the CRUD interface, storage-agnostic repositories, and
|
|
5
|
+
model/view bases — laid out as an MVC-ish split, each subpackage with its own
|
|
6
|
+
`README.md`:
|
|
7
|
+
|
|
8
|
+
- `models/` — the generic SQLAlchemy declarative base, record-lifecycle
|
|
9
|
+
mixins, and shared revision model.
|
|
10
|
+
- `views/` — the generic Pydantic view base and bulk/revision/stats
|
|
11
|
+
response shapes.
|
|
12
|
+
- `interfaces/` — the generic CRUD interface, built from a view + a
|
|
13
|
+
repository.
|
|
14
|
+
- `repositories/` — storage-agnostic CRUD access, backing `interfaces/`.
|
|
15
|
+
- `controllers/` — the generic CRUD router factories and the manifest routes.
|
|
16
|
+
- `manifest/` — the CRUD manifest: the registry the router factories fill, its
|
|
17
|
+
pydantic models and the builder that renders it from `field_specs` and the
|
|
18
|
+
routers' own limits. Served by `controllers/crud_manifest.py`; contract in
|
|
19
|
+
`docs/manifest.md`.
|
|
20
|
+
|
|
21
|
+
None of these carry resource-specific code — a resource's own model,
|
|
22
|
+
views and router live in the host application and import from here to
|
|
23
|
+
build on this framework. `tests/support/` holds a worked example (a
|
|
24
|
+
`Hero` model and its views).
|
|
25
|
+
|
|
26
|
+
## Layering
|
|
27
|
+
|
|
28
|
+
Import order within `crud/` is strict and one-directional — lower
|
|
29
|
+
layers never import from higher ones (`models` → `views` →
|
|
30
|
+
`repositories` → `interfaces` → `controllers`) — enforced by
|
|
31
|
+
`import-linter`'s `"crud layers"` contract in `../../pyproject.toml`'s
|
|
32
|
+
`[tool.importlinter]`, run via `uv run lint-imports` (wired into
|
|
33
|
+
`../../.pre-commit-config.yaml`'s manual/pre-push stage, same as mypy).
|
|
34
|
+
`manifest/` sits outside that contract: `controllers/crud_router.py` imports its
|
|
35
|
+
registry, and its builder imports `controllers/crud_query.py`, so it is a sibling
|
|
36
|
+
of `controllers`, not a layer below it (`manifest/registry.py` itself imports
|
|
37
|
+
nothing from `controllers`). This contract covers only ordering *within* the package. `interfaces/base.py`
|
|
38
|
+
imports `aiomqtt` lazily (`MQTTEventSink`/`MQTTEventSource`) — a
|
|
39
|
+
third-party dependency, not another module here, so it doesn't change
|
|
40
|
+
this layer order.
|
|
41
|
+
|
|
42
|
+
This package imports nothing from the host application; the
|
|
43
|
+
`"crud never imports app"` import-linter contract enforces it. Its
|
|
44
|
+
generic `xml_codec.py` and `web_components.py` live at the package top
|
|
45
|
+
level (below `controllers`, which uses them), not in `app`.
|
|
46
|
+
|
|
47
|
+
```mermaid
|
|
48
|
+
graph LR
|
|
49
|
+
models --> views --> repositories --> interfaces --> controllers
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
An arrow means "may import from" — each module may depend on anything
|
|
53
|
+
to its left, never anything to its right.
|
|
54
|
+
|
|
55
|
+
## Host integration
|
|
56
|
+
|
|
57
|
+
The host application owns settings, the database engine and rate limiting;
|
|
58
|
+
this package receives them:
|
|
59
|
+
|
|
60
|
+
- `config.py` — `CrudConfig` (`use_memory`, `bulk_action_max_matched`,
|
|
61
|
+
`sse_keepalive_seconds`, `mqtt: MQTTConfig`) and `configure(config,
|
|
62
|
+
session_factory)`. Call it once at startup, before the first request:
|
|
63
|
+
`models.base.get_db`/`DBSession` open sessions from the injected
|
|
64
|
+
`async_sessionmaker` (`get_session_factory()` raises if none was
|
|
65
|
+
supplied), and providers/routes read `get_config()` at call time. No
|
|
66
|
+
module here creates an engine or reads environment settings.
|
|
67
|
+
- Rate limiting: the router factories (`build_resource_router`,
|
|
68
|
+
`build_json_router`, `build_xml_router`) take an optional
|
|
69
|
+
`bulk_rate_limit` route decorator (e.g. `limiter.limit("20/minute")`)
|
|
70
|
+
for the bulk-action routes; `None` means unlimited. This package does
|
|
71
|
+
not depend on `slowapi`.
|
|
72
|
+
- Stats caching: the router factories take an optional `stats_cache`
|
|
73
|
+
(`interfaces/cache.py`'s `StatsCache` protocol) to serve `/stats` and
|
|
74
|
+
`/predict` from a shared cache, and `None` means no caching. The host supplies the
|
|
75
|
+
implementation and drives invalidation from the CRUD event stream; this package
|
|
76
|
+
does not depend on Redis.
|
|
77
|
+
- Migrations stay app-owned: the app's Alembic setup targets
|
|
78
|
+
`models.base.Base.metadata`, so a release of this package that changes
|
|
79
|
+
its models (`revision`, mixins) needs a new app-side migration
|
|
80
|
+
(NFR-0019 in the host repository).
|
|
81
|
+
- Extras: `[mqtt]` (`aiomqtt`, imported only inside
|
|
82
|
+
`MQTTEventSink`/`MQTTEventSource`) and `[xml]` (`defusedxml`, imported only
|
|
83
|
+
inside `xml_codec.from_xml` and the router's XML-body parsing).
|
|
84
|
+
`tests/unit/test_optional_extras.py` proves the core imports without them.
|
|
85
|
+
|
|
86
|
+
## Do
|
|
87
|
+
|
|
88
|
+
- Add a new generic, resource-agnostic CRUD capability here (a new
|
|
89
|
+
router factory option, repository method, or view shape usable by any
|
|
90
|
+
future resource) — see each subpackage's own `README.md` for where it
|
|
91
|
+
belongs.
|
|
92
|
+
|
|
93
|
+
## Don't
|
|
94
|
+
|
|
95
|
+
- Add resource-specific code anywhere in this package — a resource's
|
|
96
|
+
own model/view/router belongs in the host application, built on top of the
|
|
97
|
+
generic pieces here.
|
|
98
|
+
- Import anything from the host application (`app`) — pass what you need in
|
|
99
|
+
through `config.configure(...)` or a factory parameter instead; see "Host
|
|
100
|
+
integration" above.
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Runtime injection point for the host application's engine and settings.
|
|
2
|
+
|
|
3
|
+
`craftainer_crud` never reads application settings or builds a database
|
|
4
|
+
engine itself. The host calls `configure(...)` once at startup, before the first
|
|
5
|
+
request, passing an `async_sessionmaker` (it owns the engine) and a `CrudConfig`.
|
|
6
|
+
Until then `get_config()` returns the defaults below and `get_session_factory()`
|
|
7
|
+
raises, so a missing wiring step fails loudly instead of silently using the wrong
|
|
8
|
+
database.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
|
|
13
|
+
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class MQTTConfig:
|
|
18
|
+
"""Connection details for the MQTT event sink/source (needs the future `[mqtt]` extra)."""
|
|
19
|
+
|
|
20
|
+
host: str = "localhost"
|
|
21
|
+
port: int = 1883
|
|
22
|
+
keepalive_seconds: int = 60
|
|
23
|
+
username: str | None = None
|
|
24
|
+
password: str | None = None
|
|
25
|
+
use_tls: bool = False
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True, slots=True)
|
|
29
|
+
class CrudConfig:
|
|
30
|
+
"""Everything `craftainer_crud` needs from its host, besides the session factory."""
|
|
31
|
+
|
|
32
|
+
use_memory: bool = False
|
|
33
|
+
"""True selects the in-memory repository/event bus instead of SQLAlchemy/MQTT (mock mode)."""
|
|
34
|
+
bulk_action_max_matched: int = 1000
|
|
35
|
+
"""Largest number of records one bulk update/delete/restore may match."""
|
|
36
|
+
sse_keepalive_seconds: float = 15.0
|
|
37
|
+
"""Idle seconds before an SSE stream emits a keep-alive comment."""
|
|
38
|
+
mqtt: MQTTConfig = field(default_factory=MQTTConfig)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
_config = CrudConfig()
|
|
42
|
+
_session_factory: async_sessionmaker[AsyncSession] | None = None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def configure(
|
|
46
|
+
config: CrudConfig, session_factory: async_sessionmaker[AsyncSession] | None = None
|
|
47
|
+
) -> None:
|
|
48
|
+
"""Install the host's config and session factory (call once at startup)."""
|
|
49
|
+
global _config, _session_factory # noqa: PLW0603 -- the module is the injection point
|
|
50
|
+
_config = config
|
|
51
|
+
_session_factory = session_factory
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def get_config() -> CrudConfig:
|
|
55
|
+
"""Return the installed config (defaults until `configure` is called)."""
|
|
56
|
+
return _config
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def get_session_factory() -> async_sessionmaker[AsyncSession]:
|
|
60
|
+
"""Return the installed session factory, or raise if `configure` hasn't supplied one.
|
|
61
|
+
|
|
62
|
+
The raise is `# pragma: no cover` for tests/e2e specifically: its one live process
|
|
63
|
+
is always configured, so the branch can never run there --
|
|
64
|
+
tests/unit/craftainer_crud/test_config.py covers it directly.
|
|
65
|
+
"""
|
|
66
|
+
if _session_factory is None: # pragma: no cover -- see docstring
|
|
67
|
+
msg = "craftainer_crud.config.configure(...) must be called with a session factory"
|
|
68
|
+
raise RuntimeError(msg)
|
|
69
|
+
return _session_factory
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
# crud/controllers/
|
|
2
|
+
|
|
3
|
+
The generic CRUD router factories every resource builds on. A resource's
|
|
4
|
+
own router (e.g. Hero) lives in `app.crud_1` instead — see its
|
|
5
|
+
`README.md`. Highest layer in `crud`'s own import order — may import
|
|
6
|
+
from any other `crud/` subpackage, but nothing else in `crud/` may
|
|
7
|
+
import from here (see `../README.md`'s "Layering" section).
|
|
8
|
+
|
|
9
|
+
- `crud_router.py` — the generic router factories (see "Generic CRUD
|
|
10
|
+
router factories" below).
|
|
11
|
+
- `crud_actions.py` / `crud_query.py` — the shared id/filter/bulk
|
|
12
|
+
decision logic and the `field__op=value`/`sort=` query-string parser
|
|
13
|
+
`crud_router.py`'s factories wrap; see their own module docstrings.
|
|
14
|
+
- `crud_stats.py` — the shared `/stats`/`/predict` query parsing,
|
|
15
|
+
numeric/categorical field classification, and OLS forecast math
|
|
16
|
+
`crud_router.py`'s factories wrap; see "Generic CRUD router factories"
|
|
17
|
+
below and its own module docstring.
|
|
18
|
+
|
|
19
|
+
## RBAC
|
|
20
|
+
|
|
21
|
+
Add a role requirement to a route with `dependencies=[Depends
|
|
22
|
+
(require_roles("editor", "maintainer"))]` from `app.oidc` (see
|
|
23
|
+
`../../app/README.md`'s "RBAC" section for the mechanism), or a
|
|
24
|
+
module-level `Depends(...)` constant reused across a router's routes —
|
|
25
|
+
see `app.crud_1.heroes.heroes_v2`'s `ReadRoles`/`WriteRoles`/`DeleteRoles`.
|
|
26
|
+
|
|
27
|
+
## Generic CRUD router factories
|
|
28
|
+
|
|
29
|
+
`crud_router.py`'s `build_json_router`/`build_xml_router`/`build_web_router`
|
|
30
|
+
build a resource's list/create/get/update/delete routes (or, for
|
|
31
|
+
`build_web_router`, its `/form` + `/components.js` routes) internally, as
|
|
32
|
+
closures over the Pydantic views and CRUD dependency passed to them.
|
|
33
|
+
`build_resource_router` composes all three into one resource-version's
|
|
34
|
+
combined `APIRouter`, mounting each under its own `/json`/`/xml`/`/web`
|
|
35
|
+
sub-prefix — `app.crud_1.heroes`'s `heroes_v2.py`/`heroes_v1.py` are
|
|
36
|
+
one `build_resource_router(...)` call each, not three separate
|
|
37
|
+
per-format router modules; see `../../app/crud_1/README.md`'s "API and
|
|
38
|
+
model versioning" and `docs/adrs/0009-...md` for the full path shape.
|
|
39
|
+
Its own `prefix` argument should always be `""` — the caller's own
|
|
40
|
+
resource package (e.g. `heroes/__init__.py`) is where the real,
|
|
41
|
+
resource-relative prefix gets assigned, explicitly, at the
|
|
42
|
+
`include_router` call that mounts the returned router. Every
|
|
43
|
+
`include_router` call in this repository passes an explicit, non-empty
|
|
44
|
+
`prefix`, so a route's full URL can be read off the chain of mount sites
|
|
45
|
+
alone; see `../../app/crud_1/README.md`'s "Every mount names its own
|
|
46
|
+
segment", and its "Don't" section for why a resource-version router
|
|
47
|
+
baking its own prefix in here is bad design. `api_prefix` is separate
|
|
48
|
+
and still needed as the full absolute path (e.g. `/crud/v1/heroes/v2`)
|
|
49
|
+
— it only feeds `build_web_router`'s `api_base`, which gets baked into
|
|
50
|
+
rendered HTML/JS at build time and can't be derived from a later
|
|
51
|
+
`include_router` call's prefix the way FastAPI's own routing can. Each
|
|
52
|
+
factory takes `crud_dependency` as an
|
|
53
|
+
`Annotated[craftainer_crud.interfaces.base.CRUDLike[...], Depends(...)]`-shaped
|
|
54
|
+
value — `CRUDLike` is a `Protocol` both `CRUDInterface` (current
|
|
55
|
+
version) and `CompatCRUD` (deprecated version, see `../../app/crud_1/
|
|
56
|
+
README.md`'s "API and model versioning") satisfy structurally, so the
|
|
57
|
+
same factories build both.
|
|
58
|
+
|
|
59
|
+
`crud_router.py`'s `ROUTER_VERSION` constant names a version of these
|
|
60
|
+
factories' own route shape/behavior, not any resource's shape — see
|
|
61
|
+
`../../app/crud_1/README.md`'s "API and model versioning" for the full
|
|
62
|
+
three-axis path scheme this feeds into.
|
|
63
|
+
|
|
64
|
+
**Record addressing, filtering/sorting, and bulk actions** (`build_json_router`/
|
|
65
|
+
`build_xml_router`): a single record is addressed by an `id` query
|
|
66
|
+
parameter, not a path segment — `GET/PATCH/DELETE <prefix>?id=5`, 404 if
|
|
67
|
+
missing. `id` names the query key regardless of a resource's own id-field
|
|
68
|
+
name, the same way every generated route used to name its path parameter
|
|
69
|
+
`record_id` before addressing moved off the path. Without `id`, `GET` lists
|
|
70
|
+
(optionally filtered/sorted, see
|
|
71
|
+
`craftainer_crud.controllers.crud_query`'s module docstring for the `field__op=value`/
|
|
72
|
+
`sort=` wire format) and `PATCH`/`DELETE` act in bulk over whatever filters
|
|
73
|
+
are given — a request with **no** filters and no `id` is rejected (422 via
|
|
74
|
+
`RequestValidationError`) rather than silently acting on every record.
|
|
75
|
+
`craftainer_crud.controllers.crud_actions`'s `resolve_list_or_get`/`resolve_update`/
|
|
76
|
+
`resolve_delete` implement this id/filter/bulk decision once, shared by both
|
|
77
|
+
factories; each wraps the same calls in its own response format (JSON body
|
|
78
|
+
vs. an XML-rendered `Response`). Before a bulk update/delete actually runs,
|
|
79
|
+
`crud_actions.py` counts how many records the filters match
|
|
80
|
+
(`CRUDLike.count`) and refuses the action (400) above
|
|
81
|
+
`CrudConfig.bulk_action_max_matched` (default 1000, set by the host from `Settings`) — a
|
|
82
|
+
technically-non-empty but always-true filter (e.g. `id__gte=0`) would
|
|
83
|
+
otherwise still match every row. A bulk action that does run is logged
|
|
84
|
+
(`INFO`, actor/path/filters/ids) for auditing, and is itself rate-limited —
|
|
85
|
+
see `../../app/README.md`'s "Rate limiting". A bulk action's response
|
|
86
|
+
(`craftainer_crud.views.bulk.BulkUpdateResult`/`BulkDeleteResult`) carries the matched
|
|
87
|
+
count and the ids affected, not the full records. `build_json_router` also
|
|
88
|
+
serves `GET <prefix>/filters`, the same per-field-type introspection
|
|
89
|
+
`crud_query.py` uses to parse, as JSON — the `<resource>-list>` web component
|
|
90
|
+
(`craftainer_crud.web_components`) fetches this once to render filter/sort/bulk controls
|
|
91
|
+
generically, without either side hardcoding a resource's fields.
|
|
92
|
+
|
|
93
|
+
**Record-lifecycle routes** (`build_json_router`/`build_xml_router`/
|
|
94
|
+
`build_web_router` alike — `build_resource_router` forwards every opt-in
|
|
95
|
+
param below to all three factories identically, so a resource passing
|
|
96
|
+
`archivable=True`/`draft_schema=`/`revision_repository_dependency=`/
|
|
97
|
+
`event_source_dependency=`/`stats_enabled=True` gets the matching routes in
|
|
98
|
+
JSON, XML, and (client-side, via generated JS) the web UI, not JSON-only):
|
|
99
|
+
`?include_archived=true`/`?include_unpublished=true` on the existing `GET`
|
|
100
|
+
override the default Archivable/Schedulable exclusion (see
|
|
101
|
+
`../repositories/README.md`). `POST <prefix>/clone?id=` is always added
|
|
102
|
+
(fully generic, no mixin needed): it builds `create_schema` from the
|
|
103
|
+
fields it itself declares, read off the existing record, so a
|
|
104
|
+
Draftable/Archivable/Schedulable model's server-assigned fields are never
|
|
105
|
+
copied from the source. `draft_schema` (typically a resource's own
|
|
106
|
+
all-optional `*Update` view), if passed, adds `POST <prefix>/draft`
|
|
107
|
+
(persists with server-assigned lifecycle defaults) and `POST
|
|
108
|
+
<prefix>/publish?id=` (re-validates against `create_schema`, 422 naming
|
|
109
|
+
any field still missing, then flips `is_draft=False`). `archivable=True`
|
|
110
|
+
adds `POST <prefix>/restore`, mirroring delete's own id-or-filters/
|
|
111
|
+
single-or-bulk shape (`craftainer_crud.controllers.crud_actions.resolve_restore`,
|
|
112
|
+
same rate-limit/`exempt_single_record_action` treatment as the bulk
|
|
113
|
+
update/delete routes). `revision_repository_dependency` + `resource`
|
|
114
|
+
together add `GET <prefix>/revisions?id=`, a plain query against the
|
|
115
|
+
shared `Revision` table (`craftainer_crud.models.revision`) — not routed through
|
|
116
|
+
`crud_dependency`/`CRUDLike` at all, since it reads a different model
|
|
117
|
+
entirely. `event_source_dependency` (an
|
|
118
|
+
`Annotated[craftainer_crud.interfaces.base.EventSource, Depends(...)]`-shaped value,
|
|
119
|
+
mirroring `crud_dependency`'s own shape) adds `GET <prefix>/events`: a
|
|
120
|
+
`StreamingResponse` (`media_type="text/event-stream"`) of that resource's
|
|
121
|
+
create/update/update_many/delete/delete_many/restore/restore_many
|
|
122
|
+
activity, gated by the same `read_roles` dependency as the plain `GET`
|
|
123
|
+
list route. The route resolves an optional `subscriber_id` query param
|
|
124
|
+
(falling back to the standard `Last-Event-ID` header on reconnect), calls
|
|
125
|
+
`EventSource.subscribe`, and renders the result via `crud_router.py`'s
|
|
126
|
+
private `_sse_events` — which uses `asyncio.wait` on a persisted
|
|
127
|
+
`__anext__()` task rather than `asyncio.wait_for` around each keep-alive
|
|
128
|
+
tick specifically because `wait_for` would cancel (and tear down) the
|
|
129
|
+
underlying event generator on every single keep-alive interval; see
|
|
130
|
+
`_sse_events`'s own docstring. See `app.crud_1.heroes.heroes_v2` for all
|
|
131
|
+
of the above wired up on Hero, `../../app/README.md`'s "Record-lifecycle
|
|
132
|
+
mixins" section, and `docs/adrs/0015-mqtt-for-crud-events.md` for the
|
|
133
|
+
event stream's transport and delivery-guarantee design.
|
|
134
|
+
|
|
135
|
+
`stats_enabled=True` adds `GET <prefix>/stats` (count, per-numeric-field
|
|
136
|
+
min/max/avg/sum, per-categorical-field (bool/enum) value distribution, an
|
|
137
|
+
optional `?bucket=day|week|month` time-bucketed count series over
|
|
138
|
+
`created_at`, and — for a resource carrying a `../models/mixins.py`
|
|
139
|
+
mixin — a lifecycle breakdown) and `GET <prefix>/predict` (a naive
|
|
140
|
+
ordinary-least-squares linear-regression forecast over that same
|
|
141
|
+
time-bucketed series, projecting `?periods=` future buckets; `?field=`
|
|
142
|
+
targets a specific numeric field's per-bucket sum instead of record
|
|
143
|
+
count). Both are gated by the same `read_roles` dependency as the plain
|
|
144
|
+
`GET` list route. `craftainer_crud.controllers.crud_stats` holds the shared query
|
|
145
|
+
parsing/field-classification/forecast logic both `build_json_router` and
|
|
146
|
+
`build_xml_router` wrap (reusing `crud_query.field_specs`'s own
|
|
147
|
+
`FieldKind` classification, narrowed to plain int/float fields for
|
|
148
|
+
numeric aggregates — see its own module docstring for why date/datetime
|
|
149
|
+
fields, also `FieldKind.NUMBER` for filtering purposes, are excluded).
|
|
150
|
+
Pass `stats_cache=` (a `../interfaces/cache.py` `StatsCache`, with `resource=`) to
|
|
151
|
+
`build_json_router`/`build_xml_router`/`build_resource_router` to serve both routes from
|
|
152
|
+
a shared cache as pre-serialized bodies. The key is built by `crud_stats.cache_key` from
|
|
153
|
+
the route kind, normalized query parameters (so unrelated params and param order don't
|
|
154
|
+
split entries), the response schema (a deprecated version never shares an entry with the
|
|
155
|
+
current one) and `crud_stats.cache_scope(crud)`: one scope per owner when the CRUD object
|
|
156
|
+
carries a read-scoped `OwnerScope` (ADR-0011), otherwise `shared`. Roles aren't in the
|
|
157
|
+
scope because `read_roles` runs first and decides who may read, not what they read.
|
|
158
|
+
Validation errors (422) are raised before the cache is consulted and are never stored.
|
|
159
|
+
Cached responses carry `X-Stats-Cache: hit|miss`; with `stats_cache=None` (the default)
|
|
160
|
+
the routes are byte-identical to before. Invalidation is the host's job (see
|
|
161
|
+
`../interfaces/cache.py` and `app.cache.run_invalidation`).
|
|
162
|
+
|
|
163
|
+
`/predict`'s response always names its method `"linear_regression"`
|
|
164
|
+
explicitly, so a client can't mistake it for a trained model — see
|
|
165
|
+
`craftainer_crud.views.stats.PredictionView`.
|
|
166
|
+
|
|
167
|
+
**XML parity** (`build_xml_router`): every record-lifecycle/stats/predict
|
|
168
|
+
route above has an XML-flavored sibling, following the same rendering
|
|
169
|
+
pattern the original list/create/get/update/delete XML routes already
|
|
170
|
+
use — `POST <prefix>/restore` is body-less (id-or-filters via query
|
|
171
|
+
params only, same as `DELETE`); `POST <prefix>/draft` parses an XML body
|
|
172
|
+
against `draft_schema` the same way `create_record_xml` parses one
|
|
173
|
+
against `create_schema`; `POST <prefix>/publish` takes `id` as a query
|
|
174
|
+
param, no body; `GET <prefix>/revisions?id=` renders `<revisions>`
|
|
175
|
+
wrapping repeated `<revision>` elements, the same pattern
|
|
176
|
+
`list_records_xml` already uses for a list of records. `GET
|
|
177
|
+
<prefix>/stats`/`GET <prefix>/predict` are **hand-assembled** nested XML,
|
|
178
|
+
not a single `to_xml` call — `craftainer_crud.xml_codec.to_xml` only supports a flat
|
|
179
|
+
model (see its own module docstring), and stats/predictions are naturally
|
|
180
|
+
nested (per-field aggregates, a distribution, a time series). The route
|
|
181
|
+
renders each numeric-field/categorical-value/time-bucket/prediction-point
|
|
182
|
+
row as its own flat model via `to_xml`, then concatenates those inside
|
|
183
|
+
hand-written wrapping tags (`<numeric-fields>`, `<time-buckets>`, etc.) —
|
|
184
|
+
`crud_router.py`'s private `_stats_to_xml`/`_prediction_to_xml`. No
|
|
185
|
+
change to `xml_codec.py`'s own flat-model constraint. `GET
|
|
186
|
+
<prefix>/events` stays a **JSON-payload** SSE stream even under the XML
|
|
187
|
+
router — SSE's `data:` line is a transport envelope, not a resource
|
|
188
|
+
representation (see `craftainer_crud.interfaces.base.EventSink`/`EventSource`'s own
|
|
189
|
+
docstrings), so encoding it as XML would be new scope with no existing
|
|
190
|
+
precedent.
|
|
191
|
+
|
|
192
|
+
**Web UI parity** (`build_web_router`): the web router itself gains no
|
|
193
|
+
new FastAPI routes for any of this — its generated JS
|
|
194
|
+
(`craftainer_crud.web_components.render_crud_component_js`) already talks directly to
|
|
195
|
+
the sibling JSON router for every action, so covering the routes above
|
|
196
|
+
here just means the generated `<{resource}-list>`/`<{resource}-form>`
|
|
197
|
+
elements grow more UI, gated by the same opt-in params: an Archive/Restore
|
|
198
|
+
row action (`archivable=True`), a Save-as-draft/Publish pair
|
|
199
|
+
(`draft_schema` given), a per-row expandable History panel fetching `GET
|
|
200
|
+
<prefix>/revisions?id=` (`revision_repository_dependency` given), a live
|
|
201
|
+
`EventSource` subscription to `GET <prefix>/events` that refreshes the
|
|
202
|
+
list on every event (`event_source_dependency` given), and a Stats panel
|
|
203
|
+
(a plain `<table>` of numeric/categorical rows plus a small inline-SVG bar
|
|
204
|
+
chart of the time series) with a Predict control (pick a field + periods,
|
|
205
|
+
show the projected values) (`stats_enabled=True`). Plain HTML/JS/inline
|
|
206
|
+
SVG only, no charting dependency.
|
|
207
|
+
|
|
208
|
+
The generated route functions' `crud`/`record` parameters are annotated
|
|
209
|
+
with a TypeVar-bound runtime value (e.g. `create_schema`, a `type[CreateT]`
|
|
210
|
+
parameter of the enclosing factory) — mypy cannot resolve that statically,
|
|
211
|
+
so those specific lines carry a narrow `# type: ignore[valid-type]`/
|
|
212
|
+
`# type: ignore[no-any-return]`, justified by `crud_router.py`'s own module
|
|
213
|
+
docstring; the factories' own public signatures stay fully strict-typed, so
|
|
214
|
+
a caller like `app.crud_1.heroes.heroes_v2` gets normal type-checking on
|
|
215
|
+
its `build_resource_router(...)` call.
|
|
216
|
+
|
|
217
|
+
`build_xml_router`/`build_web_router`'s routes construct and return their
|
|
218
|
+
own `Response`/`RedirectResponse` directly (XML bodies, redirects, JS) —
|
|
219
|
+
FastAPI does **not** merge a `dependencies=[...]` entry's `response.headers`
|
|
220
|
+
mutations (e.g. `app.http_headers.sunset(...)`, see `../../app/crud_1/
|
|
221
|
+
README.md`'s "API and model versioning") into a route's own returned
|
|
222
|
+
`Response`, only into its own auto-built one, so every such route also
|
|
223
|
+
takes the injected `response: Response` and merges it in via
|
|
224
|
+
`crud_router.py`'s private `_with_dependency_headers` before returning.
|
|
225
|
+
Skipping this silently drops router-level headers on every XML/web route
|
|
226
|
+
with no visible error — this bit the deprecated v1 XML/web routes once,
|
|
227
|
+
before the helper was introduced.
|
|
228
|
+
|
|
229
|
+
`build_web_router`'s `/form` POST route parses `Request.form()` generically
|
|
230
|
+
(field names aren't known until the factory is called, so a typed
|
|
231
|
+
`Form()` parameter per field isn't possible) — it attaches an
|
|
232
|
+
`openapi_extra` describing each field as a required string so Swagger UI
|
|
233
|
+
still documents the submission shape, rather than showing an undocumented
|
|
234
|
+
body.
|
|
235
|
+
|
|
236
|
+
## Conditional requests
|
|
237
|
+
|
|
238
|
+
`build_json_router`/`build_xml_router` give record reads an `ETag` and
|
|
239
|
+
honor `If-None-Match`/`If-Match` (RFC 9110); `build_web_router` serves no
|
|
240
|
+
records, so it has none.
|
|
241
|
+
|
|
242
|
+
- **ETag:** a single-record GET gets a strong tag from the record's `id` +
|
|
243
|
+
`updated_at` (a view without `updated_at` falls back to a hash of its
|
|
244
|
+
serialized form). A list GET gets a weak (`W/`) tag over the page's ids
|
|
245
|
+
and `updated_at` values. Both send `Cache-Control: private, no-cache`.
|
|
246
|
+
- **304:** a matching `If-None-Match` (weak comparison; `*` or a tag list
|
|
247
|
+
also match) returns `304` with no body, keeping the `ETag`,
|
|
248
|
+
`Cache-Control` and router-level dependency headers.
|
|
249
|
+
- **If-Match / 412:** on `PATCH`/`DELETE` with `?id=`, a stale tag raises
|
|
250
|
+
`412` (problem details); strong comparison, so a weak tag never matches;
|
|
251
|
+
`*` matches any existing record; a missing record still gets the write's
|
|
252
|
+
own `404`. A successful `PATCH` returns the new `ETag`.
|
|
253
|
+
- **Race caveat:** the `If-Match` check (`crud.get`) and the write are
|
|
254
|
+
separate statements, so two writers racing inside that gap can both
|
|
255
|
+
pass. It closes the read-modify-write window a client holds open, not
|
|
256
|
+
that one.
|
|
257
|
+
- **Bulk actions** (no `?id=`) are unconditional: `If-Match` is ignored.
|
|
258
|
+
|
|
259
|
+
## CRUD manifest routes
|
|
260
|
+
|
|
261
|
+
`crud_manifest.py` serves the manifest (`docs/manifest.md`) the router factories
|
|
262
|
+
registered into a `ManifestRegistry`:
|
|
263
|
+
|
|
264
|
+
- `crud_manifest_router(registry, *, service_name, service_version, stats_ttl=None,
|
|
265
|
+
oidc_discovery_url=None, prefix="/api/_crud")` serves `GET <prefix>/manifest`.
|
|
266
|
+
`stats_ttl` is host input (the library cannot see the app's stats cache TTL).
|
|
267
|
+
- `api_catalog_router(*, manifest_url, openapi_url="/openapi.json", anchor=None)`
|
|
268
|
+
serves `GET /.well-known/api-catalog` (RFC 9727 linkset, no auth); mount it at the
|
|
269
|
+
app root. `anchor` defaults to the request's base URL.
|
|
270
|
+
- A router joins the manifest through `manifest=ManifestOptions(...)` on
|
|
271
|
+
`build_resource_router` (JSON, XML and web formats under `api_prefix`) or
|
|
272
|
+
`build_json_router` (JSON only; `manifest.base_path` names its collection URL).
|
|
273
|
+
Optional routes, `events.resource` and the schemas come from the factory's own
|
|
274
|
+
arguments. What the factory cannot see is host input in `ManifestOptions`:
|
|
275
|
+
`name`/`api_version`, `model` (`capabilities.schedulable` is
|
|
276
|
+
`issubclass(model, Schedulable)`), `owner_scoped`, `public_read`, and the role
|
|
277
|
+
names (or a `roles` attribute on the role dependency's callable).
|
|
278
|
+
- **Caller filtering:** each resource's `read_roles` dependency is solved for the
|
|
279
|
+
manifest request (with the app's `dependency_overrides`; shared sub-dependencies run
|
|
280
|
+
once). A 401 or 403 omits the resource; any other error propagates. `public_read`
|
|
281
|
+
resources are listed for everyone.
|
|
282
|
+
- **Conditional requests:** the weak `ETag` is a digest of the caller-filtered body, so
|
|
283
|
+
callers who see different resources get different tags; a matching `If-None-Match`
|
|
284
|
+
gets a bodiless `304`, with `Cache-Control: private, no-cache` (the same helpers
|
|
285
|
+
as the record routes, see "Conditional requests").
|
|
286
|
+
- Registering one `(name, api_version)` twice raises `ValueError`; v1 and v2 of one
|
|
287
|
+
name are two entries.
|
|
288
|
+
|
|
289
|
+
## Do
|
|
290
|
+
|
|
291
|
+
- Add a resource-agnostic router-building helper (usable by any future
|
|
292
|
+
resource) to `crud_router.py` — a resource-specific router belongs in
|
|
293
|
+
`app.crud_1` instead, see its `README.md`.
|
|
294
|
+
- Add auth to a route with `Depends(get_current_claims)` from
|
|
295
|
+
`app.oidc` — a route with no such dependency is public.
|
|
296
|
+
|
|
297
|
+
## Don't
|
|
298
|
+
|
|
299
|
+
- Put persistence or conversion logic directly in a route body — that
|
|
300
|
+
belongs in `craftainer_crud.interfaces`/`craftainer_crud.repositories`; a route should stay
|
|
301
|
+
a thin translation between HTTP and a `CRUDInterface` call.
|
|
302
|
+
- Add a resource's own router module here — resources live in
|
|
303
|
+
`app.crud_1` so `controllers/` stays generic, reusable machinery only.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The generic CRUD router factories every resource under `app.crud_1` builds on."""
|