rn-forge-fastapi 0.4.0__tar.gz → 0.5.0__tar.gz

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 (32) hide show
  1. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/PKG-INFO +34 -22
  2. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/README.md +26 -17
  3. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/pyproject.toml +20 -9
  4. rn_forge_fastapi-0.5.0/pyproject.toml.orig +115 -0
  5. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/__init__.py +2 -3
  6. rn_forge_fastapi-0.5.0/src/rn_forge/fastapi/_batch.py +147 -0
  7. rn_forge_fastapi-0.5.0/src/rn_forge/fastapi/_tabular.py +106 -0
  8. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/__init__.py +0 -2
  9. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/dependencies.py +12 -44
  10. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/rate_limit.py +9 -6
  11. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/redis.py +2 -1
  12. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/routes.py +24 -76
  13. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/idempotency.py +13 -4
  14. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/problem.py +35 -1
  15. rn_forge_fastapi-0.5.0/src/rn_forge/fastapi/sse.py +133 -0
  16. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/transfer.py +60 -200
  17. rn_forge_fastapi-0.4.0/pyproject.toml.orig +0 -113
  18. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/LICENSE +0 -0
  19. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/app.py +0 -0
  20. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/authorization.py +0 -0
  21. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/csrf.py +0 -0
  22. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/proxies.py +0 -0
  23. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/auth/sessions.py +0 -0
  24. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/cors.py +0 -0
  25. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/dependencies.py +0 -0
  26. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/deprecation.py +0 -0
  27. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/health.py +0 -0
  28. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/merge_patch.py +0 -0
  29. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/openapi.py +0 -0
  30. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/py.typed +0 -0
  31. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/read_mask.py +0 -0
  32. {rn_forge_fastapi-0.4.0 → rn_forge_fastapi-0.5.0}/src/rn_forge/fastapi/soft_delete.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rn-forge-fastapi
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: FastAPI adapters over rn-forge-web
5
5
  Author: Rohit Narayanan
6
6
  Author-email: Rohit Narayanan <rohit.nn@gmail.com>
@@ -14,13 +14,15 @@ Classifier: Programming Language :: Python :: 3
14
14
  Classifier: Programming Language :: Python :: 3 :: Only
15
15
  Classifier: Programming Language :: Python :: 3.14
16
16
  Classifier: Typing :: Typed
17
- Requires-Dist: rn-forge-auth>=0.1.0,<0.2
17
+ Requires-Dist: rn-forge-auth>=0.2.0,<0.3
18
+ Requires-Dist: rn-forge-commons>=0.8.0,<0.11
18
19
  Requires-Dist: rn-forge-web[security]>=0.3.0,<0.4
19
20
  Requires-Dist: fastapi>=0.141.1
20
21
  Requires-Dist: opentelemetry-instrumentation-fastapi>=0.65b0
21
- Requires-Dist: rn-forge-auth[oidc]>=0.1.0,<0.2 ; extra == 'oidc'
22
- Requires-Dist: rn-forge-auth[redis]>=0.1.0,<0.2 ; extra == 'redis'
23
- Requires-Dist: assertpy>=1.1 ; extra == 'testing'
22
+ Requires-Dist: rn-forge-auth[oidc]>=0.2.0,<0.3 ; extra == 'oidc'
23
+ Requires-Dist: rn-forge-auth[redis]>=0.2.0,<0.3 ; extra == 'redis'
24
+ Requires-Dist: sse-starlette>=3.4.11 ; extra == 'sse'
25
+ Requires-Dist: assertpy>=2.35 ; extra == 'testing'
24
26
  Requires-Dist: httpx>=0.28.1 ; extra == 'testing'
25
27
  Requires-Dist: pytest>=9.1.1 ; extra == 'testing'
26
28
  Requires-Dist: rn-forge-data>=0.1.1,<0.2 ; extra == 'transfer'
@@ -32,6 +34,7 @@ Project-URL: Changelog, https://github.com/rn-forge/pykit/blob/main/packages/rn-
32
34
  Project-URL: Issues, https://github.com/rn-forge/pykit/issues
33
35
  Provides-Extra: oidc
34
36
  Provides-Extra: redis
37
+ Provides-Extra: sse
35
38
  Provides-Extra: testing
36
39
  Provides-Extra: transfer
37
40
  Description-Content-Type: text/markdown
@@ -60,20 +63,14 @@ router factory and an OpenAPI repair. **It makes no wire decision of its own.**
60
63
  | `dependencies` | `page_params`, `require_idempotency_key`, `require_if_match` |
61
64
  | `health` | `health_router(checks=...)` — `/healthz` and `/readyz` |
62
65
  | `auth` | `auth_router` and `SessionMiddleware` — the `/auth` routes, login sessions and CSRF protection over `rn-forge-auth`; `bearer_auth`, `basic_auth`, `current_principal`, `requires`, `requires_permission`, `PolicyGuard` — `Security` dependencies; rate limiting; `auth.redis` — the Redis CSRF store and rate limiter (`redis` extra) |
66
+ | `sse` | `sse_response(events)` — an `EventSourceResponse` that rejects forged frame fields, sends a `retry` frame first and ends a failed stream with one problem frame (`sse` extra) |
63
67
  | `app` | `FastApiApp(config)` — a `FastAPI` subclass with the standard adapters installed |
64
68
 
65
69
  ## Where it sits
66
70
 
67
- ```text
68
- commons ──► web ──► auth ──► django
69
- └───► fastapi (this package)
70
- ```
71
-
72
- `rn-forge-fastapi` depends on `rn-forge-web`, `rn-forge-auth` and FastAPI. It
73
- never imports `rn_forge.django` — the two framework packages are independent
74
- siblings — nor `rn_forge.cli` or `rn_forge.tooling`. `.importlinter` carries the
75
- `fastapi-runtime-has-no-tooling` and `web-layers` contracts, and
76
- `uv run lint-imports` proves them.
71
+ `rn-forge-fastapi` depends on `rn-forge-web`, `rn-forge-auth` and FastAPI; it
72
+ never imports `rn_forge.django`, `rn_forge.cli` or `rn_forge.tooling`;
73
+ `task lint` proves it.
77
74
 
78
75
  ## The import path
79
76
 
@@ -97,8 +94,24 @@ problem types, the auth contract), and this package does not re-export it.
97
94
  Declare `rn-forge-web` as well, so the import is not an undeclared transitive
98
95
  dependency.
99
96
 
100
- Inside this workspace, `[tool.uv.sources]` overrides the requirement with the
101
- local checkout, for local development only.
97
+ Extras: `oidc` (JWKS bearer auth and OIDC login, `rn-forge-auth[oidc]`), `redis`
98
+ (the Redis stores and `rn_forge.fastapi.auth.redis`), `transfer`
99
+ (`rn-forge-data` and `python-multipart`, for `rn_forge.fastapi.transfer`), `sse`
100
+ (`sse-starlette`, for `rn_forge.fastapi.sse`) and `testing` (`assertpy`, `httpx`
101
+ and `pytest`).
102
+
103
+ ## Minimum example
104
+
105
+ ```python
106
+ from rn_forge.fastapi import FastApiApp
107
+
108
+ app = FastApiApp(title="Orders")
109
+ ```
110
+
111
+ The app serves `/healthz` and `/readyz` and renders every error as a problem
112
+ body; the
113
+ [quickstart](https://rn-forge.github.io/pykit/packages/rn-forge-fastapi/latest/guides/quickstart.html)
114
+ adds pagination and readiness checks.
102
115
 
103
116
  ## What this package deliberately does not ship
104
117
 
@@ -125,8 +138,8 @@ local checkout, for local development only.
125
138
  ## Dependencies
126
139
 
127
140
  **`rn-forge-web`** — every module adapts one of its primitives.
128
- `rn-forge-commons` is not declared: nothing here imports it directly, and it
129
- arrives through `rn-forge-web`.
141
+
142
+ **`rn-forge-commons`** — declared directly: `problem` uses its `AppLogger`.
130
143
 
131
144
  **`rn-forge-auth`** — a base dependency: the `auth` package is built on its
132
145
  login flows, `Principal`, `Requirement` and authenticator contracts. Its OIDC
@@ -160,6 +173,5 @@ the same literal segment collide silently here.
160
173
 
161
174
  ## Documentation
162
175
 
163
- `uv run --directory packages/rn-forge-fastapi --group docs mkdocs build --strict`,
164
- or the combined site from the repo root. The wiring guide is the page an
165
- application is written from.
176
+ `task docs:build` builds the combined site and every package site. The wiring
177
+ guide is the page an application is written from.
@@ -22,20 +22,14 @@ router factory and an OpenAPI repair. **It makes no wire decision of its own.**
22
22
  | `dependencies` | `page_params`, `require_idempotency_key`, `require_if_match` |
23
23
  | `health` | `health_router(checks=...)` — `/healthz` and `/readyz` |
24
24
  | `auth` | `auth_router` and `SessionMiddleware` — the `/auth` routes, login sessions and CSRF protection over `rn-forge-auth`; `bearer_auth`, `basic_auth`, `current_principal`, `requires`, `requires_permission`, `PolicyGuard` — `Security` dependencies; rate limiting; `auth.redis` — the Redis CSRF store and rate limiter (`redis` extra) |
25
+ | `sse` | `sse_response(events)` — an `EventSourceResponse` that rejects forged frame fields, sends a `retry` frame first and ends a failed stream with one problem frame (`sse` extra) |
25
26
  | `app` | `FastApiApp(config)` — a `FastAPI` subclass with the standard adapters installed |
26
27
 
27
28
  ## Where it sits
28
29
 
29
- ```text
30
- commons ──► web ──► auth ──► django
31
- └───► fastapi (this package)
32
- ```
33
-
34
- `rn-forge-fastapi` depends on `rn-forge-web`, `rn-forge-auth` and FastAPI. It
35
- never imports `rn_forge.django` — the two framework packages are independent
36
- siblings — nor `rn_forge.cli` or `rn_forge.tooling`. `.importlinter` carries the
37
- `fastapi-runtime-has-no-tooling` and `web-layers` contracts, and
38
- `uv run lint-imports` proves them.
30
+ `rn-forge-fastapi` depends on `rn-forge-web`, `rn-forge-auth` and FastAPI; it
31
+ never imports `rn_forge.django`, `rn_forge.cli` or `rn_forge.tooling`;
32
+ `task lint` proves it.
39
33
 
40
34
  ## The import path
41
35
 
@@ -59,8 +53,24 @@ problem types, the auth contract), and this package does not re-export it.
59
53
  Declare `rn-forge-web` as well, so the import is not an undeclared transitive
60
54
  dependency.
61
55
 
62
- Inside this workspace, `[tool.uv.sources]` overrides the requirement with the
63
- local checkout, for local development only.
56
+ Extras: `oidc` (JWKS bearer auth and OIDC login, `rn-forge-auth[oidc]`), `redis`
57
+ (the Redis stores and `rn_forge.fastapi.auth.redis`), `transfer`
58
+ (`rn-forge-data` and `python-multipart`, for `rn_forge.fastapi.transfer`), `sse`
59
+ (`sse-starlette`, for `rn_forge.fastapi.sse`) and `testing` (`assertpy`, `httpx`
60
+ and `pytest`).
61
+
62
+ ## Minimum example
63
+
64
+ ```python
65
+ from rn_forge.fastapi import FastApiApp
66
+
67
+ app = FastApiApp(title="Orders")
68
+ ```
69
+
70
+ The app serves `/healthz` and `/readyz` and renders every error as a problem
71
+ body; the
72
+ [quickstart](https://rn-forge.github.io/pykit/packages/rn-forge-fastapi/latest/guides/quickstart.html)
73
+ adds pagination and readiness checks.
64
74
 
65
75
  ## What this package deliberately does not ship
66
76
 
@@ -87,8 +97,8 @@ local checkout, for local development only.
87
97
  ## Dependencies
88
98
 
89
99
  **`rn-forge-web`** — every module adapts one of its primitives.
90
- `rn-forge-commons` is not declared: nothing here imports it directly, and it
91
- arrives through `rn-forge-web`.
100
+
101
+ **`rn-forge-commons`** — declared directly: `problem` uses its `AppLogger`.
92
102
 
93
103
  **`rn-forge-auth`** — a base dependency: the `auth` package is built on its
94
104
  login flows, `Principal`, `Requirement` and authenticator contracts. Its OIDC
@@ -122,6 +132,5 @@ the same literal segment collide silently here.
122
132
 
123
133
  ## Documentation
124
134
 
125
- `uv run --directory packages/rn-forge-fastapi --group docs mkdocs build --strict`,
126
- or the combined site from the repo root. The wiring guide is the page an
127
- application is written from.
135
+ `task docs:build` builds the combined site and every package site. The wiring
136
+ guide is the page an application is written from.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rn-forge-fastapi"
3
- version = "0.4.0"
3
+ version = "0.5.0"
4
4
  description = "FastAPI adapters over rn-forge-web"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -17,7 +17,8 @@ classifiers = [
17
17
  ]
18
18
  requires-python = ">=3.14"
19
19
  dependencies = [
20
- "rn-forge-auth>=0.1.0,<0.2",
20
+ "rn-forge-auth>=0.2.0,<0.3",
21
+ "rn-forge-commons>=0.8.0,<0.11",
21
22
  "rn-forge-web[security]>=0.3.0,<0.4",
22
23
  "fastapi>=0.141.1",
23
24
  "opentelemetry-instrumentation-fastapi>=0.65b0",
@@ -29,16 +30,17 @@ email = "rohit.nn@gmail.com"
29
30
 
30
31
  [project.optional-dependencies]
31
32
  testing = [
32
- "assertpy>=1.1",
33
+ "assertpy>=2.35",
33
34
  "httpx>=0.28.1",
34
35
  "pytest>=9.1.1",
35
36
  ]
36
- oidc = ["rn-forge-auth[oidc]>=0.1.0,<0.2"]
37
- redis = ["rn-forge-auth[redis]>=0.1.0,<0.2"]
37
+ oidc = ["rn-forge-auth[oidc]>=0.2.0,<0.3"]
38
+ redis = ["rn-forge-auth[redis]>=0.2.0,<0.3"]
38
39
  transfer = [
39
40
  "rn-forge-data>=0.1.1,<0.2",
40
41
  "python-multipart>=0.0.20",
41
42
  ]
43
+ sse = ["sse-starlette>=3.4.11"]
42
44
 
43
45
  [project.urls]
44
46
  Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-fastapi/latest/"
@@ -47,11 +49,19 @@ Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-fasta
47
49
  Issues = "https://github.com/rn-forge/pykit/issues"
48
50
 
49
51
  [build-system]
50
- requires = ["uv_build>=0.11.28,<0.12.0"]
52
+ requires = ["uv_build>=0.13.7,<0.14.0"]
51
53
  build-backend = "uv_build"
52
54
 
55
+ [tool.pyright]
56
+ typeCheckingMode = "strict"
57
+ reportMissingTypeStubs = false
58
+ reportUnnecessaryTypeIgnoreComment = "error"
59
+ venv = ".venv"
60
+ venvPath = "../.."
61
+
53
62
  [tool.uv.build-backend]
54
63
  module-name = "rn_forge.fastapi"
64
+ source-exclude = ["**/.DS_Store"]
55
65
 
56
66
  [tool.uv.sources.rn-forge-auth]
57
67
  workspace = true
@@ -77,6 +87,7 @@ redis = [
77
87
  "rn_forge.auth.redis",
78
88
  "rn_forge.fastapi.auth.redis",
79
89
  ]
90
+ sse = ["rn_forge.fastapi.sse"]
80
91
  transfer = ["rn_forge.fastapi.transfer"]
81
92
 
82
93
  [tool.pytest.ini_options]
@@ -89,14 +100,14 @@ markers = [
89
100
 
90
101
  [dependency-groups]
91
102
  dev = [
92
- "assertpy>=1.1",
103
+ "assertpy>=2.35",
93
104
  "httpx>=0.28.1",
94
105
  "opentelemetry-sdk>=1.44",
95
106
  "pyright>=1.1.411",
96
107
  "pytest>=9.1.1",
97
108
  "pytest-cov>=7.1.0",
98
109
  "pytest-randomly>=4.1.0",
99
- "rn-forge-fastapi[oidc,redis,transfer]",
110
+ "rn-forge-fastapi[oidc,redis,sse,transfer]",
100
111
  "ruff>=0.15.21",
101
112
  "sqlalchemy>=2.0",
102
113
  ]
@@ -104,5 +115,5 @@ docs = [
104
115
  "mkdocs>=1.6.1",
105
116
  "mkdocs-material>=9.7.6",
106
117
  "mkdocstrings[python]>=1.0.6",
107
- "rn-forge-fastapi",
118
+ "rn-forge-fastapi[sse]",
108
119
  ]
@@ -0,0 +1,115 @@
1
+ [project]
2
+ name = "rn-forge-fastapi"
3
+ version = "0.5.0"
4
+ description = "FastAPI adapters over rn-forge-web"
5
+ readme = "README.md"
6
+ authors = [{ name = "Rohit Narayanan", email = "rohit.nn@gmail.com" }]
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Intended Audience :: Developers",
12
+ "Framework :: FastAPI",
13
+ "Operating System :: OS Independent",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3 :: Only",
16
+ "Programming Language :: Python :: 3.14",
17
+ "Typing :: Typed",
18
+ ]
19
+ requires-python = ">=3.14"
20
+ # Internal requirements are version ranges (ADR-0004).
21
+ dependencies = [
22
+ "rn-forge-auth>=0.2.0,<0.3",
23
+ "rn-forge-commons>=0.8.0,<0.11",
24
+ # `[security]` is a hard requirement, not an extra: `FastApiApp` installs
25
+ # `SecurityHeadersMiddleware` by default (`AppConfig.security_headers`).
26
+ "rn-forge-web[security]>=0.3.0,<0.4",
27
+ # A hard dependency, not an extra: every module in this package is a FastAPI
28
+ # adapter. The floor is what resolved on 2026-09-12. pydantic arrives with it.
29
+ "fastapi>=0.141.1",
30
+ # `FastApiApp` instruments itself by default (`AppConfig.tracing`). Brings
31
+ # `opentelemetry-instrumentation`, which holds `TraceResponsePropagator`.
32
+ "opentelemetry-instrumentation-fastapi>=0.65b0",
33
+ ]
34
+
35
+ [project.optional-dependencies]
36
+ # httpx is what FastAPI's TestClient drives requests through.
37
+ testing = ["assertpy>=2.35", "httpx>=0.28.1", "pytest>=9.1.1"]
38
+ # JWKS bearer auth: `rn_forge.auth.oidc.OidcAuthenticator` passed to
39
+ # `bearer_auth()`. Nothing in this package imports it; the extra exists so a
40
+ # consumer asks for it by name rather than reaching into auth's extras.
41
+ oidc = ["rn-forge-auth[oidc]>=0.2.0,<0.3"]
42
+ # Redis-backed login sessions and transactions for `rn_forge.fastapi.auth`:
43
+ # `rn_forge.auth.redis`, and the CSRF token store `rn_forge.fastapi.auth.redis`.
44
+ redis = ["rn-forge-auth[redis]>=0.2.0,<0.3"]
45
+ # Tabular export and import: `rn_forge.fastapi.transfer`. Not imported by the
46
+ # package facade. `python-multipart` is what FastAPI's `UploadFile` needs.
47
+ transfer = ["rn-forge-data>=0.1.1,<0.2", "python-multipart>=0.0.20"]
48
+ # Server-sent events: `rn_forge.fastapi.sse`. Not imported by the package facade.
49
+ sse = ["sse-starlette>=3.4.11"]
50
+
51
+ [project.urls]
52
+ Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-fastapi/latest/"
53
+ Source = "https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-fastapi"
54
+ Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-fastapi/CHANGELOG.md"
55
+ Issues = "https://github.com/rn-forge/pykit/issues"
56
+
57
+ [build-system]
58
+ requires = ["uv_build>=0.13.7,<0.14.0"]
59
+ build-backend = "uv_build"
60
+
61
+ [tool.pyright]
62
+ typeCheckingMode = "strict"
63
+ reportMissingTypeStubs = false
64
+ reportUnnecessaryTypeIgnoreComment = "error"
65
+ venv = ".venv"
66
+ venvPath = "../.."
67
+
68
+ [tool.uv.build-backend]
69
+ module-name = "rn_forge.fastapi"
70
+ source-exclude = ["**/.DS_Store"]
71
+
72
+ [tool.uv.sources]
73
+ rn-forge-auth = { workspace = true }
74
+ rn-forge-commons = { workspace = true }
75
+ rn-forge-data = { workspace = true }
76
+ rn-forge-web = { workspace = true }
77
+ rn-forge-fastapi = { workspace = true }
78
+
79
+ [tool.workspace-ci.smoke]
80
+ modules = ["rn_forge.fastapi"]
81
+
82
+ [tool.workspace-ci.smoke.extras]
83
+ oidc = ["rn_forge.auth.oidc"]
84
+ redis = ["rn_forge.auth.redis", "rn_forge.fastapi.auth.redis"]
85
+ sse = ["rn_forge.fastapi.sse"]
86
+ transfer = ["rn_forge.fastapi.transfer"]
87
+
88
+ [tool.pytest.ini_options]
89
+ addopts = "-ra --import-mode=importlib -m 'not scaffold'"
90
+ markers = [
91
+ "unit: fast isolated tests",
92
+ "scaffold: installs built wheels into a scaffolded application (slow)",
93
+ "security_control: demonstrates the security control with the given rn_forge.auth.conformance case ID",
94
+ ]
95
+
96
+ [dependency-groups]
97
+ dev = [
98
+ "assertpy>=2.35",
99
+ "httpx>=0.28.1",
100
+ "opentelemetry-sdk>=1.44",
101
+ "pyright>=1.1.411",
102
+ "pytest>=9.1.1",
103
+ "pytest-cov>=7.1.0",
104
+ "pytest-randomly>=4.1.0",
105
+ "rn-forge-fastapi[oidc,redis,sse,transfer]",
106
+ "ruff>=0.15.21",
107
+ # Test-only: the ResourcePolicy tests scope real `select()` queries.
108
+ "sqlalchemy>=2.0",
109
+ ]
110
+ docs = [
111
+ "mkdocs>=1.6.1",
112
+ "mkdocs-material>=9.7.6",
113
+ "mkdocstrings[python]>=1.0.6",
114
+ "rn-forge-fastapi[sse]",
115
+ ]
@@ -7,7 +7,6 @@ from rn_forge.fastapi.auth import (
7
7
  CSRF_COOKIE,
8
8
  CSRF_HEADER,
9
9
  SESSION_COOKIE,
10
- TRANSACTION_COOKIE,
11
10
  ActiveSession,
12
11
  AuthRoutesConfig,
13
12
  BearerAuth,
@@ -47,7 +46,7 @@ from rn_forge.fastapi.merge_patch import (
47
46
  merge_patch_openapi,
48
47
  )
49
48
  from rn_forge.fastapi.openapi import operation_id
50
- from rn_forge.fastapi.problem import Log, register_problem_handlers
49
+ from rn_forge.fastapi.problem import Log, log_server_errors, register_problem_handlers
51
50
  from rn_forge.fastapi.read_mask import masked, read_mask_param
52
51
  from rn_forge.fastapi.soft_delete import (
53
52
  SoftDeleteState,
@@ -62,7 +61,6 @@ __all__ = [
62
61
  "CSRF_COOKIE",
63
62
  "CSRF_HEADER",
64
63
  "SESSION_COOKIE",
65
- "TRANSACTION_COOKIE",
66
64
  "ActiveSession",
67
65
  "AppConfig",
68
66
  "AuthRoutesConfig",
@@ -91,6 +89,7 @@ __all__ = [
91
89
  "deprecated",
92
90
  "health_router",
93
91
  "idempotent",
92
+ "log_server_errors",
94
93
  "masked",
95
94
  "merge_into",
96
95
  "merge_patch_body",
@@ -0,0 +1,147 @@
1
+ """Checks and validates a batch request body: the guards and the threaded JSON route."""
2
+
3
+ import json
4
+ from collections.abc import Callable, Coroutine, Mapping, Sequence
5
+ from typing import Annotated, Any, cast
6
+
7
+ from fastapi import Depends, Request
8
+ from fastapi.concurrency import run_in_threadpool
9
+ from fastapi.exceptions import RequestValidationError
10
+ from fastapi.params import Depends as DependsParam
11
+ from fastapi.responses import Response
12
+ from fastapi.routing import APIRoute
13
+ from pydantic import (
14
+ BaseModel,
15
+ SkipValidation,
16
+ TypeAdapter,
17
+ ValidationError,
18
+ create_model,
19
+ )
20
+ from rn_forge.web import (
21
+ NULL_FIELD_DETAIL,
22
+ REQUIRED_FIELD_DETAIL,
23
+ RowsInvalid,
24
+ )
25
+ from rn_forge.web.transfer import NON_EMPTY_LIST_DETAIL, RowError, row_cap_problem
26
+
27
+
28
+ def list_model(
29
+ name: str, member: str, item: Any, *, validate_items: bool = True
30
+ ) -> type[BaseModel]:
31
+ """Build ``{member: [item]}``, the schema FastAPI documents and validates."""
32
+ make = cast("Callable[..., type[BaseModel]]", create_model)
33
+ # The guard has already validated each item; FastAPI would do it again.
34
+ items = list[item] if validate_items else Annotated[list[item], SkipValidation]
35
+ return make(name, **{member: (items, ...)})
36
+
37
+
38
+ def rejection(loc: str, kind: str, message: str) -> RequestValidationError:
39
+ return RequestValidationError(
40
+ [{"type": kind, "loc": ("body", loc), "msg": message}]
41
+ )
42
+
43
+
44
+ def error_message(err: Mapping[str, Any]) -> str:
45
+ if err["type"] == "missing":
46
+ return REQUIRED_FIELD_DETAIL
47
+ if "input" in err and err["input"] is None:
48
+ return NULL_FIELD_DETAIL
49
+ if err["type"] == "value_error" and "ctx" in err:
50
+ return str(err["ctx"]["error"])
51
+ return err["msg"]
52
+
53
+
54
+ def item_errors(index: int, exc: ValidationError) -> list[RowError]:
55
+ return [
56
+ RowError(index, ".".join(str(part) for part in err["loc"]), error_message(err))
57
+ for err in exc.errors()
58
+ ]
59
+
60
+
61
+ async def checked_list(
62
+ request: Request, key: str, max_rows: int | None
63
+ ) -> list[object]:
64
+ """Return the raw body's *key* member, which must be a non-empty list within *max_rows*."""
65
+ try:
66
+ body: object = await request.json()
67
+ except ValueError:
68
+ body = None
69
+ members: Mapping[str, object] = (
70
+ cast("Mapping[str, object]", body) if isinstance(body, Mapping) else {}
71
+ )
72
+ if key not in members:
73
+ raise rejection(key, "missing", "Field required")
74
+ value: object = members[key]
75
+ if not isinstance(value, list) or not value:
76
+ raise rejection(key, "value_error", NON_EMPTY_LIST_DETAIL)
77
+ entries = cast("list[object]", value)
78
+ if max_rows is not None and len(entries) > max_rows:
79
+ raise ValueError(
80
+ row_cap_problem("batch", max_rows, instance=request.url.path).problem.detail
81
+ )
82
+ return entries
83
+
84
+
85
+ def list_guard(key: str, max_rows: int | None) -> DependsParam:
86
+ """Check the raw body's *key* member before FastAPI validates the body."""
87
+
88
+ async def guard(request: Request) -> None:
89
+ await checked_list(request, key, max_rows)
90
+
91
+ return Depends(guard)
92
+
93
+
94
+ def validate_items[T: BaseModel](
95
+ items: TypeAdapter[T], entries: Sequence[object]
96
+ ) -> tuple[list[T], list[RowError]]:
97
+ valid: list[T] = []
98
+ errors: list[RowError] = []
99
+ for index, item in enumerate(entries):
100
+ try:
101
+ valid.append(items.validate_python(item))
102
+ except ValidationError as exc:
103
+ errors.extend(item_errors(index, exc))
104
+ return valid, errors
105
+
106
+
107
+ def models_guard[T: BaseModel](
108
+ key: str, max_rows: int | None, item_model: type[T]
109
+ ) -> Any:
110
+ """Check the body's *key* member, validate each item into *item_model* and yield the models.
111
+
112
+ Runs before FastAPI validates the body. The checks fire in the order the
113
+ wire contract states, and item failures use the row-error wording.
114
+ """
115
+ items = TypeAdapter(item_model)
116
+
117
+ async def guard(request: Request) -> list[T]:
118
+ entries = await checked_list(request, key, max_rows)
119
+ valid, errors = await run_in_threadpool(validate_items, items, entries)
120
+ if errors:
121
+ raise RowsInvalid(errors, root=key)
122
+ return valid
123
+
124
+ return Depends(guard)
125
+
126
+
127
+ class ThreadedJsonRequest(Request):
128
+ """A request whose JSON body is parsed in a worker thread."""
129
+
130
+ async def json(self) -> Any:
131
+ if not hasattr(self, "_json"):
132
+ self._json = await run_in_threadpool(json.loads, await self.body())
133
+ return self._json
134
+
135
+
136
+ class ThreadedJsonRoute(APIRoute):
137
+ """A route that reads its request body through :class:`ThreadedJsonRequest`."""
138
+
139
+ # FastAPI parses the body before any dependency runs, so the route has to
140
+ # swap the request class to move that parse off the event loop.
141
+ def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]:
142
+ handler = super().get_route_handler()
143
+
144
+ async def route(request: Request) -> Response:
145
+ return await handler(ThreadedJsonRequest(request.scope, request.receive))
146
+
147
+ return route
@@ -0,0 +1,106 @@
1
+ """Reads tabular files into validated rows and writes rows as CSV chunks or tables."""
2
+
3
+ import csv
4
+ import io
5
+ from collections.abc import Iterable, Iterator, Mapping
6
+ from typing import Any
7
+
8
+ import tablib
9
+ from pydantic import BaseModel, TypeAdapter, ValidationError
10
+ from rn_forge.data import write_xlsx
11
+ from rn_forge.web.transfer import (
12
+ TABULAR_FORMATS,
13
+ RowError,
14
+ TabularFormat,
15
+ unreadable_file_detail,
16
+ )
17
+
18
+ CSV_CHUNK_ROWS = 1_000
19
+
20
+
21
+ def columns(model: type[BaseModel]) -> list[str]:
22
+ fields = [
23
+ info.serialization_alias or name for name, info in model.model_fields.items()
24
+ ]
25
+ computed = [
26
+ info.alias or name for name, info in model.model_computed_fields.items()
27
+ ]
28
+ return [*fields, *computed]
29
+
30
+
31
+ def records(
32
+ rows: Iterable[Any], model: type[BaseModel], mode: str
33
+ ) -> Iterator[dict[str, Any]]:
34
+ for row in rows:
35
+ yield model.model_validate(row, from_attributes=True).model_dump(
36
+ by_alias=True,
37
+ mode=mode,
38
+ )
39
+
40
+
41
+ def csv_chunks(
42
+ rows: Iterable[Any], model: type[BaseModel], names: list[str]
43
+ ) -> Iterator[str]:
44
+ """Yield the CSV text of *rows*, the header first, in chunks of ``CSV_CHUNK_ROWS`` rows."""
45
+ # Streaming one row per chunk costs a worker-thread hop per row.
46
+ buffer = io.StringIO()
47
+ writer = csv.writer(buffer)
48
+ writer.writerow(names)
49
+ count = 0
50
+ for record in records(rows, model, "json"):
51
+ writer.writerow([record[c] for c in names])
52
+ count += 1
53
+ if count == CSV_CHUNK_ROWS:
54
+ yield buffer.getvalue()
55
+ buffer.seek(0)
56
+ buffer.truncate()
57
+ count = 0
58
+ if buffer.tell():
59
+ yield buffer.getvalue()
60
+
61
+
62
+ def build_body(
63
+ rows: Iterable[Any], model: type[BaseModel], fmt: TabularFormat, names: list[str]
64
+ ) -> bytes | str:
65
+ dataset: Any = tablib.Dataset(headers=names)
66
+ for record in records(rows, model, "python"):
67
+ dataset.append([record[c] for c in names])
68
+ if fmt.extension == "xlsx":
69
+ return write_xlsx(dataset)
70
+ return dataset.export(fmt.tablib_name)
71
+
72
+
73
+ def parse_table[T: BaseModel](
74
+ raw: bytes, extension: str, model: type[T]
75
+ ) -> tuple[list[T], list[RowError], int]:
76
+ """Load *raw* as *extension* and validate each row; return the valid rows, errors and row count."""
77
+ data: bytes | str = raw if extension == "xlsx" else raw.decode("utf-8-sig")
78
+ try:
79
+ dataset: Any = tablib.Dataset()
80
+ dataset.load(data, format=TABULAR_FORMATS[extension].tablib_name)
81
+ except Exception as exc:
82
+ raise ValueError(unreadable_file_detail(extension)) from exc
83
+ adapter = TypeAdapter(model)
84
+ rows = dicts(dataset)
85
+ valid: list[T] = []
86
+ errors: list[RowError] = []
87
+ for index, row in enumerate(rows):
88
+ try:
89
+ valid.append(adapter.validate_python(row))
90
+ except ValidationError as exc:
91
+ errors.extend(row_errors(index, exc))
92
+ return valid, errors, len(rows)
93
+
94
+
95
+ def dicts(dataset: Any) -> list[Mapping[str, Any]]:
96
+ return dataset.dict
97
+
98
+
99
+ def row_errors(index: int, exc: ValidationError) -> Iterator[RowError]:
100
+ for err in exc.errors():
101
+ message = (
102
+ str(err["ctx"]["error"])
103
+ if err["type"] == "value_error" and "ctx" in err
104
+ else err["msg"]
105
+ )
106
+ yield RowError(index, str(err["loc"][0]) if err["loc"] else "", message)