mistralai-capabilities-backend-fastapi 0.1.36__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Mistral AI
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 2.4
2
+ Name: mistralai-capabilities-backend-fastapi
3
+ Version: 0.1.36
4
+ Summary: The HTTP delivery machinery apps/api is built on: the file-based router loader, the hook runtime other capabilities extend it through, SSE encoding, and the gen-openapi command.
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Dist: pydantic>=2.14.1
8
+ Requires-Dist: fastapi>=0.143.0 ; extra == 'fastapi'
9
+ Requires-Python: >=3.12, <3.15
10
+ Provides-Extra: fastapi
@@ -0,0 +1,33 @@
1
+ [project]
2
+ name = "mistralai-capabilities-backend-fastapi"
3
+ version = "0.1.36"
4
+ description = "The HTTP delivery machinery apps/api is built on: the file-based router loader, the hook runtime other capabilities extend it through, SSE encoding, and the gen-openapi command."
5
+ requires-python = ">=3.12,<3.15"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ dependencies = ["pydantic>=2.14.1"]
9
+
10
+ # An optional extra rather than a base dependency: only the API host imports FastAPI. Keeping the
11
+ # web framework out of the base distribution lets a worker install the toolkit without loading it.
12
+ [project.optional-dependencies]
13
+ # At least 0.137.2: `routing` imports `fastapi.routing.iter_route_contexts`, added in that release.
14
+ fastapi = ["fastapi>=0.143.0"]
15
+
16
+ [build-system]
17
+ # uv_build 0.8 skips a `license-files` glob that matches nothing, while 0.13 fails on it. An app that
18
+ # vendors this package builds it from source, where the root LICENSE is not staged.
19
+ requires = ["uv_build>=0.8.22,<0.9.0"]
20
+ build-backend = "uv_build"
21
+
22
+ # Installed with the capability, this becomes `uv run gen-openapi` in a generated app and backs the
23
+ # `api:gen-openapi` NX target. It imports the app's `api.main` (present whenever this capability is
24
+ # selected) and FastAPI from the API host environment, so no capability.json edge is implied.
25
+ [project.scripts]
26
+ gen-openapi = "mistralai_capabilities.fastapi.cli.gen_openapi:main"
27
+
28
+ [tool.uv.build-backend]
29
+ # The dist name is fixed by the CLI convention (= `<registry id>-<kind>-<capability id>`);
30
+ # `module-name` decouples the IMPORT path from it. `namespace = true` makes this a PEP-420
31
+ # portion so it ships only the `mistralai_capabilities.fastapi` slice alongside the sibling caps.
32
+ module-name = "mistralai_capabilities.fastapi"
33
+ namespace = true
@@ -0,0 +1,18 @@
1
+ """Write the FastAPI app's OpenAPI schema to PATH (default: apps/api/openapi.json)."""
2
+
3
+ import json
4
+ import sys
5
+ from pathlib import Path
6
+
7
+
8
+ def main() -> None:
9
+ # Importing `api.main` builds the app once; use that instance rather than building a second.
10
+ from api.main import app
11
+
12
+ path = Path(sys.argv[1] if len(sys.argv) > 1 else "apps/api/openapi.json")
13
+ path.write_text(json.dumps(app.openapi(), indent=2, sort_keys=True) + "\n")
14
+ print(f"wrote {path}") # noqa: T201
15
+
16
+
17
+ if __name__ == "__main__":
18
+ main()
@@ -0,0 +1,215 @@
1
+ """Deterministic app-local extension hooks for the generated FastAPI host."""
2
+
3
+ import asyncio
4
+ import importlib
5
+ import importlib.util
6
+ import logging
7
+ import pkgutil
8
+ from collections.abc import Awaitable, Callable, Mapping
9
+ from types import MappingProxyType, ModuleType
10
+
11
+ from fastapi import FastAPI
12
+
13
+ ConfigureHook = Callable[[FastAPI], None]
14
+ AsyncHook = Callable[[FastAPI], Awaitable[None]]
15
+ Probe = Callable[[], Awaitable[bool]]
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class FastAPIHookDiscoveryError(RuntimeError):
21
+ """A hook catalog or lifecycle transition could not be used safely."""
22
+
23
+
24
+ class FastAPIHooks:
25
+ def __init__(
26
+ self,
27
+ *,
28
+ configure_hooks: tuple[tuple[str, ConfigureHook], ...] = (),
29
+ startup_hooks: tuple[tuple[str, AsyncHook], ...] = (),
30
+ shutdown_hooks: tuple[tuple[str, AsyncHook], ...] = (),
31
+ report_checks: tuple[tuple[str, Probe], ...] = (),
32
+ readiness_checks: tuple[tuple[str, Probe], ...] = (),
33
+ metadata_values: Mapping[str, str | None] | None = None,
34
+ ) -> None:
35
+ self.configure_hooks = _catalog("configure", configure_hooks)
36
+ self.startup_hooks = _catalog("startup", startup_hooks)
37
+ self.shutdown_hooks = _catalog("shutdown", shutdown_hooks)
38
+ self.report_checks = _catalog("report", report_checks)
39
+ self.readiness_checks = _catalog("readiness", readiness_checks)
40
+ metadata = dict(metadata_values or {})
41
+ self.metadata_values: Mapping[str, str | None] = MappingProxyType(
42
+ dict(sorted(metadata.items()))
43
+ )
44
+ self._configured_app: FastAPI | None = None
45
+ self._startup_attempted = False
46
+ self._shutdown_complete = False
47
+
48
+ @classmethod
49
+ def discover(cls, root: str = "api") -> "FastAPIHooks":
50
+ metadata_providers = _discover(f"{root}.health.metadata", "metadata")
51
+ return cls(
52
+ configure_hooks=_discover(f"{root}.configure", "configure"),
53
+ startup_hooks=_discover(f"{root}.lifespan.startup", "startup"),
54
+ shutdown_hooks=_discover(f"{root}.lifespan.shutdown", "shutdown"),
55
+ report_checks=_discover(f"{root}.health.report", "check"),
56
+ readiness_checks=_discover(f"{root}.health.ready", "check"),
57
+ metadata_values={name: provider() for name, provider in metadata_providers},
58
+ )
59
+
60
+ @classmethod
61
+ def empty(cls) -> "FastAPIHooks":
62
+ return cls()
63
+
64
+ @classmethod
65
+ def compose(cls, *hook_sets: "FastAPIHooks") -> "FastAPIHooks":
66
+ metadata: dict[str, str | None] = {}
67
+ for hooks in hook_sets:
68
+ for key, value in hooks.metadata_values.items():
69
+ if key in metadata:
70
+ raise FastAPIHookDiscoveryError(f"duplicate metadata hook {key!r}")
71
+ metadata[key] = value
72
+ return cls(
73
+ configure_hooks=tuple(
74
+ item for hooks in hook_sets for item in hooks.configure_hooks
75
+ ),
76
+ startup_hooks=tuple(
77
+ item for hooks in hook_sets for item in hooks.startup_hooks
78
+ ),
79
+ shutdown_hooks=tuple(
80
+ item for hooks in hook_sets for item in hooks.shutdown_hooks
81
+ ),
82
+ report_checks=tuple(
83
+ item for hooks in hook_sets for item in hooks.report_checks
84
+ ),
85
+ readiness_checks=tuple(
86
+ item for hooks in hook_sets for item in hooks.readiness_checks
87
+ ),
88
+ metadata_values=metadata,
89
+ )
90
+
91
+ def configure(self, app: FastAPI) -> None:
92
+ if self._configured_app is not None:
93
+ detail = (
94
+ "the same app" if self._configured_app is app else "a different app"
95
+ )
96
+ raise FastAPIHookDiscoveryError(f"configure hooks already ran for {detail}")
97
+ self._configured_app = app
98
+ for _, hook in self.configure_hooks:
99
+ hook(app)
100
+
101
+ async def startup(self, app: FastAPI) -> None:
102
+ self._require_configured_app(app)
103
+ if self._startup_attempted:
104
+ raise FastAPIHookDiscoveryError("startup hooks were already attempted")
105
+ self._startup_attempted = True
106
+ for _, hook in self.startup_hooks:
107
+ await hook(app)
108
+
109
+ async def shutdown(self, app: FastAPI) -> None:
110
+ self._require_configured_app(app)
111
+ if not self._startup_attempted:
112
+ raise FastAPIHookDiscoveryError("shutdown requires a startup attempt")
113
+ if self._shutdown_complete:
114
+ raise FastAPIHookDiscoveryError("shutdown hooks already ran")
115
+ self._shutdown_complete = True
116
+ failures: list[Exception] = []
117
+ for _, hook in reversed(self.shutdown_hooks):
118
+ try:
119
+ await hook(app)
120
+ except Exception as error:
121
+ failures.append(error)
122
+ if failures:
123
+ raise ExceptionGroup("FastAPI shutdown hook failures", failures)
124
+
125
+ async def report(self) -> dict[str, bool]:
126
+ return await _run_probes(self.report_checks)
127
+
128
+ async def ready(self) -> dict[str, bool]:
129
+ return await _run_probes(self.readiness_checks)
130
+
131
+ def _require_configured_app(self, app: FastAPI) -> None:
132
+ if self._configured_app is None:
133
+ raise FastAPIHookDiscoveryError("configure hooks have not run")
134
+ if self._configured_app is not app:
135
+ raise FastAPIHookDiscoveryError("hooks cannot run for a different app")
136
+
137
+
138
+ def _catalog(name: str, entries: tuple[tuple[str, Callable[..., object]], ...]):
139
+ ordered = tuple(sorted(entries, key=lambda item: item[0]))
140
+ seen: set[str] = set()
141
+ for key, _ in ordered:
142
+ if key in seen:
143
+ raise FastAPIHookDiscoveryError(f"duplicate {name} hook {key!r}")
144
+ seen.add(key)
145
+ return ordered
146
+
147
+
148
+ def _discover(package: str, declaration: str):
149
+ try:
150
+ spec = importlib.util.find_spec(package)
151
+ except ModuleNotFoundError as error:
152
+ missing = error.name or ""
153
+ if package == missing or package.startswith(f"{missing}."):
154
+ spec = None
155
+ else:
156
+ raise FastAPIHookDiscoveryError(
157
+ f"FastAPI hook package {package!r} could not be inspected: {error}"
158
+ ) from error
159
+ except Exception as error:
160
+ raise FastAPIHookDiscoveryError(
161
+ f"FastAPI hook package {package!r} could not be inspected: {error}"
162
+ ) from error
163
+ if spec is None:
164
+ logger.debug(
165
+ "no FastAPI hook package %r installed; using an empty catalog", package
166
+ )
167
+ return ()
168
+ if spec.submodule_search_locations is None:
169
+ raise FastAPIHookDiscoveryError(
170
+ f"FastAPI hook package {package!r} is a module, not a package"
171
+ )
172
+
173
+ found = pkgutil.iter_modules(spec.submodule_search_locations, prefix=f"{package}.")
174
+ hooks = []
175
+ seen: set[str] = set()
176
+ for _, module_name, _ in sorted(found, key=lambda entry: entry[1]):
177
+ key = module_name.rpartition(".")[2]
178
+ if key.startswith("_"):
179
+ continue
180
+ if key in seen:
181
+ raise FastAPIHookDiscoveryError(f"duplicate {package} hook {key!r}")
182
+ seen.add(key)
183
+ module = _import_module(module_name)
184
+ if not hasattr(module, declaration):
185
+ raise FastAPIHookDiscoveryError(
186
+ f"FastAPI hook module {module_name!r} does not declare {declaration!r}"
187
+ )
188
+ hook = getattr(module, declaration)
189
+ if not callable(hook):
190
+ raise FastAPIHookDiscoveryError(
191
+ f"FastAPI hook declaration {module_name}.{declaration} is {type(hook).__name__}, not callable"
192
+ )
193
+ hooks.append((key, hook))
194
+ return tuple(hooks)
195
+
196
+
197
+ def _import_module(module_name: str) -> ModuleType:
198
+ try:
199
+ return importlib.import_module(module_name)
200
+ except Exception as error:
201
+ raise FastAPIHookDiscoveryError(
202
+ f"FastAPI hook module {module_name!r} could not be imported: {error}"
203
+ ) from error
204
+
205
+
206
+ async def _run_probes(probes: tuple[tuple[str, Probe], ...]) -> dict[str, bool]:
207
+ async def run(name: str, probe: Probe) -> bool:
208
+ try:
209
+ return await probe()
210
+ except Exception:
211
+ logger.exception("FastAPI health probe %r failed", name)
212
+ return False
213
+
214
+ results = await asyncio.gather(*(run(name, probe) for name, probe in probes))
215
+ return {name: result for (name, _), result in zip(probes, results, strict=True)}
@@ -0,0 +1,63 @@
1
+ """Codegen guard for the OpenAPI document the web client is generated from.
2
+
3
+ The generated TypeScript client is only as typed as the spec: a route annotated ``-> Any`` (or with
4
+ no response model) emits an empty ``{}`` schema and its response silently becomes ``unknown`` in the
5
+ client. :func:`untyped_json_responses` lists every such response so an app's route tests can fail on
6
+ it. Pure functions over the spec dictionary, so they import no web framework.
7
+ """
8
+
9
+ from collections.abc import Mapping
10
+ from typing import Any
11
+
12
+ HTTP_METHODS = frozenset({"get", "post", "put", "patch", "delete"})
13
+
14
+ # JSON Schema leaf types that generate a concrete TypeScript type (`string`, `number`, `boolean`).
15
+ # `null` alone is not one: a route returning only `None` has no body worth typing. `object` and
16
+ # `array` are containers and count only when what they contain is typed.
17
+ _PRIMITIVE_TYPES = frozenset({"string", "integer", "number", "boolean"})
18
+
19
+
20
+ def schema_is_typed(schema: Mapping[str, Any]) -> bool:
21
+ """Whether a response schema resolves to a concrete type the client generator can name.
22
+
23
+ A ``$ref`` to a model, a primitive leaf (``str``, ``int``, ``float``, ``bool``, an enum or a
24
+ ``Literal``), an array of typed items, an object with declared properties or typed
25
+ ``additionalProperties`` (``dict[str, Model]``), or a union with at least one typed member.
26
+ ``{}`` (``Any``), a bare ``dict`` / ``list`` and ``None`` are not.
27
+ """
28
+ if not schema:
29
+ return False
30
+ if "$ref" in schema or "enum" in schema or "const" in schema:
31
+ return True
32
+ declared = schema.get("type")
33
+ types = set(declared) if isinstance(declared, list) else {declared}
34
+ if types & _PRIMITIVE_TYPES:
35
+ return True
36
+ if "array" in types or "items" in schema or "prefixItems" in schema:
37
+ items = [schema["items"]] if isinstance(schema.get("items"), Mapping) else []
38
+ items += [item for item in schema.get("prefixItems", []) if isinstance(item, Mapping)]
39
+ return any(schema_is_typed(item) for item in items)
40
+ if "object" in types:
41
+ additional = schema.get("additionalProperties")
42
+ return bool(schema.get("properties")) or (isinstance(additional, Mapping) and schema_is_typed(additional))
43
+ return any(schema_is_typed(member) for key in ("allOf", "anyOf", "oneOf") for member in schema.get(key, []))
44
+
45
+
46
+ def untyped_json_responses(spec: Mapping[str, Any]) -> list[str]:
47
+ """Every 2xx JSON response in ``spec`` whose schema is not typed, as ``"METHOD /path (code)"``.
48
+
49
+ Non-JSON responses (the plain-text root, an SSE stream) have no ``application/json`` schema and
50
+ are not codegen inputs, so they are skipped.
51
+ """
52
+ offenders: list[str] = []
53
+ for path, item in spec.get("paths", {}).items():
54
+ for method, operation in item.items():
55
+ if method not in HTTP_METHODS:
56
+ continue
57
+ for code, response in operation.get("responses", {}).items():
58
+ if not code.startswith("2"):
59
+ continue
60
+ schema = response.get("content", {}).get("application/json", {}).get("schema")
61
+ if schema is not None and not schema_is_typed(schema):
62
+ offenders.append(f"{method.upper()} {path} ({code})")
63
+ return offenders
@@ -0,0 +1,143 @@
1
+ """File-based routing: the directory tree under a package is the URL tree.
2
+ ``foo/`` contributes ``foo``, unless it declares ``segment``
3
+ ``segment = ""`` contributes nothing
4
+ ``route.py`` the directory index; contributes nothing
5
+ ``bar.py`` contributes ``bar``
6
+ ``[thing]`` contributes ``{thing}`` in a file or directory name
7
+ no module-level ``router`` contributes nothing
8
+ """
9
+
10
+ import importlib
11
+ import pkgutil
12
+ import re
13
+ from collections.abc import Iterator
14
+ from dataclasses import dataclass
15
+
16
+ from fastapi import APIRouter, FastAPI
17
+ from fastapi.params import Depends
18
+ from fastapi.routing import APIRoute, iter_route_contexts
19
+
20
+ _PARAM = re.compile(r"\[(.*?)\]")
21
+ _INDEX = "route"
22
+
23
+
24
+ class UndeclaredAccessRuleError(RuntimeError):
25
+ """Raised when a route would be served from a subtree that declares no access rule."""
26
+
27
+
28
+ class DuplicateRouteError(RuntimeError):
29
+ """Raised when two modules claim the same URL."""
30
+
31
+
32
+ class NoRoutersDiscoveredError(RuntimeError):
33
+ """Raised when a package that should expose routers exposes none."""
34
+
35
+
36
+ def _url_segment(name: str) -> str:
37
+ return _PARAM.sub(lambda m: "{" + m.group(1) + "}", name)
38
+
39
+
40
+ def _sort_key(path: str) -> tuple[tuple[int, str], ...]:
41
+ """Static segments before parameterised ones, at every depth.
42
+
43
+ FastAPI matches in registration order, so ``/users/me`` has to be registered before
44
+ ``/users/{id}`` or the parameterised route swallows it.
45
+ """
46
+ return tuple((1 if "{" in part else 0, part) for part in path.split("/"))
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class _Mount:
51
+ path: str
52
+ router: APIRouter
53
+ dependencies: tuple[Depends, ...]
54
+ source: str
55
+
56
+
57
+ def _collect(
58
+ package_name: str,
59
+ segments: tuple[str, ...],
60
+ dependencies: tuple[Depends, ...] | None,
61
+ ) -> Iterator[_Mount]:
62
+ """Walk one package, yielding a mount per route module under it.
63
+
64
+ ``dependencies`` is ``None`` until a package on the way down declares a rule. This gives the
65
+ fail-closed guarantee: a module reached while it is still ``None`` has no declaring ancestor,
66
+ which is an error and not an anonymous route.
67
+ """
68
+ package = importlib.import_module(package_name)
69
+ if not hasattr(package, "__path__"):
70
+ raise NoRoutersDiscoveredError(f"{package_name!r} is a module, not a package")
71
+
72
+ if hasattr(package, "dependencies"):
73
+ dependencies = (*(dependencies or ()), *package.dependencies)
74
+
75
+ for info in sorted(pkgutil.iter_modules(package.__path__, f"{package_name}."), key=lambda m: m.name):
76
+ name = info.name.rpartition(".")[2]
77
+ # `_`-prefixed modules are private helpers, never routes: the rule hook discovery follows.
78
+ if name.startswith("_"):
79
+ continue
80
+
81
+ if info.ispkg:
82
+ segment = _url_segment(getattr(importlib.import_module(info.name), "segment", name))
83
+ yield from _collect(info.name, (*segments, segment) if segment else segments, dependencies)
84
+ continue
85
+
86
+ router = getattr(importlib.import_module(info.name), "router", None)
87
+ if not isinstance(router, APIRouter):
88
+ continue
89
+ if dependencies is None:
90
+ raise UndeclaredAccessRuleError(
91
+ f"{info.name!r} serves routes but no package above it declares `dependencies`. "
92
+ "Add `dependencies: tuple[params.Depends, ...]` to a parent `__init__` — `()` if the "
93
+ "subtree is meant to be anonymous. It is never inferred, because the default would "
94
+ "be public."
95
+ )
96
+
97
+ own = segments if name == _INDEX else (*segments, _url_segment(name))
98
+ yield _Mount("/" + "/".join(own) if own else "", router, dependencies, info.name)
99
+
100
+
101
+ def _mounts(package_name: str) -> list[_Mount]:
102
+ found = list(_collect(package_name, (), None))
103
+ if not found:
104
+ raise NoRoutersDiscoveredError(f"{package_name!r} exposed no route module")
105
+
106
+ seen: dict[str, str] = {}
107
+ for mount in found:
108
+ if mount.path in seen:
109
+ raise DuplicateRouteError(f"{mount.path or '/'!r} is claimed by both {seen[mount.path]} and {mount.source}")
110
+ seen[mount.path] = mount.source
111
+ return found
112
+
113
+
114
+ def create_api_router(package_name: str, *, prefix: str = "") -> APIRouter:
115
+ """Every route module under ``package_name``, mounted where the tree says it belongs.
116
+
117
+ ``prefix`` is where the caller hangs the tree. Raises if two modules claim one URL, if a
118
+ module serves a subtree with no access rule, or if nothing was found. The last case matters
119
+ because a packaging change that hides every module looks like a healthy app with no routes.
120
+ """
121
+ api = APIRouter(prefix=prefix)
122
+ for mount in sorted(_mounts(package_name), key=lambda m: _sort_key(m.path)):
123
+ api.include_router(mount.router, prefix=mount.path, dependencies=list(mount.dependencies))
124
+ return api
125
+
126
+
127
+ def anonymous_paths(package_name: str) -> frozenset[str]:
128
+ """Every path served with no access rule attached.
129
+
130
+ Reads the rules the loader applied, so a group that gains a dependency leaves this set.
131
+ Mounted on a throwaway app because ``include_router`` resolves against an app. The app has
132
+ no OpenAPI, docs, or redoc url, so every path here came from the tree.
133
+ """
134
+ probe = FastAPI(openapi_url=None, docs_url=None, redoc_url=None)
135
+ for mount in _mounts(package_name):
136
+ if not mount.dependencies:
137
+ probe.include_router(mount.router, prefix=mount.path)
138
+
139
+ return frozenset(
140
+ context.path
141
+ for context in iter_route_contexts(probe.routes)
142
+ if isinstance(context.original_route, APIRoute) and context.path is not None
143
+ )
@@ -0,0 +1,41 @@
1
+ """Encoding server-sent events, shared by every streaming route."""
2
+
3
+ import json
4
+ from collections.abc import AsyncIterator, Mapping
5
+ from typing import Any
6
+
7
+ from fastapi.responses import StreamingResponse
8
+ from pydantic import BaseModel
9
+
10
+
11
+ def event_stream_response(events: AsyncIterator[str]) -> StreamingResponse:
12
+ return StreamingResponse(
13
+ events,
14
+ media_type="text/event-stream",
15
+ headers={
16
+ "Cache-Control": "no-cache",
17
+ "Connection": "keep-alive",
18
+ "X-Accel-Buffering": "no",
19
+ },
20
+ )
21
+
22
+
23
+ def format_sse(*, data: Any, event: str | None = None, event_id: str | None = None) -> str:
24
+ lines: list[str] = []
25
+ if event is not None:
26
+ lines.append(f"event: {event}")
27
+ if event_id is not None:
28
+ lines.append(f"id: {event_id}")
29
+ encoded = json.dumps(_model_dump(data), separators=(",", ":"), default=str)
30
+ lines.extend(f"data: {line}" for line in encoded.splitlines() or [""])
31
+ return "\n".join(lines) + "\n\n"
32
+
33
+
34
+ def _model_dump(value: Any) -> Any:
35
+ if isinstance(value, BaseModel):
36
+ return value.model_dump(mode="json", by_alias=True, exclude_none=True)
37
+ if isinstance(value, Mapping):
38
+ return {key: _model_dump(item) for key, item in value.items()}
39
+ if isinstance(value, (list, tuple)):
40
+ return [_model_dump(item) for item in value]
41
+ return value