csrd-versioning 0.1.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 (58) hide show
  1. csrd_versioning-0.1.0/.gitignore +217 -0
  2. csrd_versioning-0.1.0/PKG-INFO +15 -0
  3. csrd_versioning-0.1.0/README.md +55 -0
  4. csrd_versioning-0.1.0/pyproject.toml +30 -0
  5. csrd_versioning-0.1.0/src/csrd/versioning/__init__.py +99 -0
  6. csrd_versioning-0.1.0/src/csrd/versioning/_constants.py +28 -0
  7. csrd_versioning-0.1.0/src/csrd/versioning/_core.py +240 -0
  8. csrd_versioning-0.1.0/src/csrd/versioning/_dependencies.py +67 -0
  9. csrd_versioning-0.1.0/src/csrd/versioning/_dependency_wiring.py +272 -0
  10. csrd_versioning-0.1.0/src/csrd/versioning/_dispatch.py +203 -0
  11. csrd_versioning-0.1.0/src/csrd/versioning/_docs.py +495 -0
  12. csrd_versioning-0.1.0/src/csrd/versioning/_fastapi_types.py +44 -0
  13. csrd_versioning-0.1.0/src/csrd/versioning/_helpers.py +149 -0
  14. csrd_versioning-0.1.0/src/csrd/versioning/_orchestration.py +399 -0
  15. csrd_versioning-0.1.0/src/csrd/versioning/_redoc.py +98 -0
  16. csrd_versioning-0.1.0/src/csrd/versioning/_settings.py +88 -0
  17. csrd_versioning-0.1.0/src/csrd/versioning/_swagger_ui_version.py +12 -0
  18. csrd_versioning-0.1.0/src/csrd/versioning/_types.py +14 -0
  19. csrd_versioning-0.1.0/src/csrd/versioning/actuator/README.md +261 -0
  20. csrd_versioning-0.1.0/src/csrd/versioning/actuator/__init__.py +3 -0
  21. csrd_versioning-0.1.0/src/csrd/versioning/actuator/actuator.py +111 -0
  22. csrd_versioning-0.1.0/src/csrd/versioning/actuator/plugins/__init__.py +65 -0
  23. csrd_versioning-0.1.0/src/csrd/versioning/actuator/plugins/base.py +77 -0
  24. csrd_versioning-0.1.0/src/csrd/versioning/actuator/plugins/env/__init__.py +31 -0
  25. csrd_versioning-0.1.0/src/csrd/versioning/actuator/plugins/env/plugin.py +145 -0
  26. csrd_versioning-0.1.0/src/csrd/versioning/actuator/plugins/env/providers.py +105 -0
  27. csrd_versioning-0.1.0/src/csrd/versioning/actuator/plugins/env/registry.py +211 -0
  28. csrd_versioning-0.1.0/src/csrd/versioning/actuator/plugins/health/__init__.py +37 -0
  29. csrd_versioning-0.1.0/src/csrd/versioning/actuator/plugins/health/auto.py +244 -0
  30. csrd_versioning-0.1.0/src/csrd/versioning/actuator/plugins/health/indicators.py +137 -0
  31. csrd_versioning-0.1.0/src/csrd/versioning/actuator/plugins/health/plugin.py +271 -0
  32. csrd_versioning-0.1.0/src/csrd/versioning/actuator/plugins/info.py +120 -0
  33. csrd_versioning-0.1.0/src/csrd/versioning/actuator/tools/README.md +54 -0
  34. csrd_versioning-0.1.0/src/csrd/versioning/actuator/tools/__init__.py +0 -0
  35. csrd_versioning-0.1.0/src/csrd/versioning/actuator/tools/generate_service_info_from_git.py +126 -0
  36. csrd_versioning-0.1.0/src/csrd/versioning/exception_handlers.py +126 -0
  37. csrd_versioning-0.1.0/src/csrd/versioning/py.typed +0 -0
  38. csrd_versioning-0.1.0/src/csrd/versioning/swagger_plugins/__init__.py +15 -0
  39. csrd_versioning-0.1.0/src/csrd/versioning/swagger_plugins/_base.py +153 -0
  40. csrd_versioning-0.1.0/src/csrd/versioning/swagger_plugins/file_upload/__init__.py +35 -0
  41. csrd_versioning-0.1.0/src/csrd/versioning/swagger_plugins/file_upload/_body_factory.py +121 -0
  42. csrd_versioning-0.1.0/src/csrd/versioning/swagger_plugins/file_upload/_schema_patcher.py +165 -0
  43. csrd_versioning-0.1.0/src/csrd/versioning/swagger_plugins/file_upload/file_upload_plugin.css +181 -0
  44. csrd_versioning-0.1.0/src/csrd/versioning/swagger_plugins/file_upload/file_upload_plugin.js +529 -0
  45. csrd_versioning-0.1.0/src/csrd/versioning/templates/__init__.py +0 -0
  46. csrd_versioning-0.1.0/src/csrd/versioning/templates/favicon.png +0 -0
  47. csrd_versioning-0.1.0/src/csrd/versioning/templates/swagger_ui.css +616 -0
  48. csrd_versioning-0.1.0/src/csrd/versioning/templates/swagger_ui.html +43 -0
  49. csrd_versioning-0.1.0/src/csrd/versioning/templates/swagger_ui.js +131 -0
  50. csrd_versioning-0.1.0/tests/test_actuator.py +186 -0
  51. csrd_versioning-0.1.0/tests/test_core.py +164 -0
  52. csrd_versioning-0.1.0/tests/test_dependency_wiring.py +186 -0
  53. csrd_versioning-0.1.0/tests/test_dispatch.py +210 -0
  54. csrd_versioning-0.1.0/tests/test_docs.py +225 -0
  55. csrd_versioning-0.1.0/tests/test_exception_handlers.py +105 -0
  56. csrd_versioning-0.1.0/tests/test_helpers.py +105 -0
  57. csrd_versioning-0.1.0/tests/test_orchestration.py +183 -0
  58. csrd_versioning-0.1.0/tests/test_settings.py +44 -0
@@ -0,0 +1,217 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ /env/
142
+ /venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
208
+
209
+ *.db
210
+
211
+
212
+ # Import linter cache
213
+ .import_linter_cache/
214
+
215
+ # IDE
216
+ .idea/
217
+ .idea/*
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: csrd-versioning
3
+ Version: 0.1.0
4
+ Summary: API versioning, dispatch, docs, and actuator for FastAPI
5
+ Project-URL: Repository, https://github.com/csrd-api/fastapi-common
6
+ Project-URL: Documentation, https://github.com/csrd-api/fastapi-common/tree/main/packages/versioning
7
+ Project-URL: Changelog, https://github.com/csrd-api/fastapi-common/blob/main/CHANGELOG.md
8
+ License: MIT
9
+ Requires-Python: >=3.12
10
+ Requires-Dist: csrd-context
11
+ Requires-Dist: csrd-models
12
+ Requires-Dist: fastapi<1,>=0.115
13
+ Requires-Dist: httpx<1,>=0.27
14
+ Requires-Dist: pydantic-settings<3,>=2
15
+ Requires-Dist: pydantic<3,>=2
@@ -0,0 +1,55 @@
1
+ # csrd-versioning
2
+
3
+ API versioning, dispatch, docs, and actuator for FastAPI.
4
+
5
+ **Package**: `csrd.versioning` · **Import**: `from csrd.versioning import create_versioned_app, configure_versioned_api`
6
+
7
+ ## What's included
8
+
9
+ - **Version dispatch** — raw ASGI middleware for version-aware routing (streaming/SSE safe)
10
+ - **Swagger UI** — custom docs with version picker, dark mode, SRI hashes, plugin system
11
+ - **Actuator** — Spring Boot-style management endpoints (health, info, env)
12
+ - **Exception handlers** — structured `APIErrorResponse` JSON for HTTP and validation errors
13
+ - **Dependency wiring** — auto path-param injection, bearer guard opt-out
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ uv pip install "csrd-versioning @ git+ssh://git@github.com/csrd-api/fastapi-common.git#subdirectory=packages/versioning"
19
+ ```
20
+
21
+ ## Quick start
22
+
23
+ ```python
24
+ from enum import Enum
25
+ from fastapi import FastAPI
26
+ from csrd.versioning import create_versioned_app
27
+
28
+ class Versions(Enum):
29
+ Unversioned = "Unversioned"
30
+ V1 = "2025-06-20"
31
+
32
+ unv = FastAPI()
33
+ v1 = FastAPI()
34
+
35
+ app = create_versioned_app(
36
+ {Versions.Unversioned: unv, Versions.V1: v1},
37
+ prefix="api",
38
+ )
39
+ ```
40
+
41
+ ## Security notes
42
+
43
+ - **`/actuator/env`**: The `ShowValues.ALWAYS` setting exposes environment variable values. Use `ShowValues.NEVER` (default) in production to redact sensitive data.
44
+ - **CORS**: Add `CORSMiddleware` **before** calling `configure_versioned_api`. The version dispatch middleware must be the outermost middleware. Example:
45
+
46
+ ```python
47
+ app = FastAPI()
48
+ app.add_middleware(CORSMiddleware, allow_origins=["*"], ...)
49
+ configure_versioned_api(app, version_mapping, ...)
50
+ ```
51
+
52
+ ## Dependencies
53
+
54
+ - `csrd-models`, `csrd-context` (Tier 3 — depends on Tier 1 packages)
55
+ - For JWT auth, use [`csrd-auth`](../auth/README.md) alongside this package
@@ -0,0 +1,30 @@
1
+ [project]
2
+ name = "csrd-versioning"
3
+ version = "0.1.0"
4
+ description = "API versioning, dispatch, docs, and actuator for FastAPI"
5
+ license = { text = "MIT" }
6
+ requires-python = ">=3.12"
7
+ dependencies = [
8
+ "fastapi>=0.115,<1",
9
+ "httpx>=0.27,<1",
10
+ "pydantic>=2,<3",
11
+ "pydantic-settings>=2,<3",
12
+ "csrd-context",
13
+ "csrd-models",
14
+ ]
15
+
16
+ [project.urls]
17
+ Repository = "https://github.com/csrd-api/fastapi-common"
18
+ Documentation = "https://github.com/csrd-api/fastapi-common/tree/main/packages/versioning"
19
+ Changelog = "https://github.com/csrd-api/fastapi-common/blob/main/CHANGELOG.md"
20
+
21
+ [build-system]
22
+ requires = ["hatchling"]
23
+ build-backend = "hatchling.build"
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ packages = ["src/csrd"]
27
+
28
+ [tool.uv.sources]
29
+ csrd-context = { workspace = true }
30
+ csrd-models = { workspace = true }
@@ -0,0 +1,99 @@
1
+ """API versioning, dispatch, docs, and actuator for FastAPI."""
2
+
3
+ from ._constants import (
4
+ API_VERSION_HEADER_NAME,
5
+ APP_ID_HEADER_NAME,
6
+ AUTH_HEADER_NAME,
7
+ HIT_ID_HEADER_NAME,
8
+ HTTP_METHODS,
9
+ UNVERSIONED,
10
+ UNVERSIONED_DISPLAY_LABEL,
11
+ VERSIONING_SETTINGS_STATE_KEY,
12
+ )
13
+ from ._core import (
14
+ map_version_path,
15
+ normalize_prefix,
16
+ normalize_unversioned_label,
17
+ normalize_version,
18
+ resolve_prefix,
19
+ resolve_version,
20
+ validate_version_mapping_keys,
21
+ )
22
+ from ._dependencies import (
23
+ ApiVersionDep,
24
+ AppIdDep,
25
+ HitIdDep,
26
+ param_factory,
27
+ uuid_id_factory,
28
+ )
29
+ from ._fastapi_types import (
30
+ ExceptionHandlerProvider,
31
+ ExHandler,
32
+ Middleware,
33
+ NormalizedDependencySpec,
34
+ PathParamDependencies,
35
+ PathParamDependencySpec,
36
+ VersionedAppConfigurer,
37
+ VersionedAppLifespan,
38
+ )
39
+ from ._helpers import (
40
+ HeadersGetter,
41
+ find_bearer,
42
+ find_token,
43
+ )
44
+ from ._orchestration import (
45
+ configure_versioned_api,
46
+ create_versioned_app,
47
+ default_exception_handlers_provider,
48
+ get_current_user_claims,
49
+ )
50
+ from ._settings import VersioningSettings, load_app_name, load_versioning_settings
51
+ from ._swagger_ui_version import SWAGGER_UI_VERSION
52
+ from ._types import VersionedAppState, VersionKey, VersionMap
53
+ from .actuator import register_actuator_router
54
+
55
+ __all__ = (
56
+ "API_VERSION_HEADER_NAME",
57
+ "APP_ID_HEADER_NAME",
58
+ "AUTH_HEADER_NAME",
59
+ "HIT_ID_HEADER_NAME",
60
+ "HTTP_METHODS",
61
+ "SWAGGER_UI_VERSION",
62
+ "UNVERSIONED",
63
+ "UNVERSIONED_DISPLAY_LABEL",
64
+ "VERSIONING_SETTINGS_STATE_KEY",
65
+ "ApiVersionDep",
66
+ "AppIdDep",
67
+ "ExHandler",
68
+ "ExceptionHandlerProvider",
69
+ "HeadersGetter",
70
+ "HitIdDep",
71
+ "Middleware",
72
+ "NormalizedDependencySpec",
73
+ "PathParamDependencies",
74
+ "PathParamDependencySpec",
75
+ "VersionKey",
76
+ "VersionMap",
77
+ "VersionedAppConfigurer",
78
+ "VersionedAppLifespan",
79
+ "VersionedAppState",
80
+ "VersioningSettings",
81
+ "configure_versioned_api",
82
+ "create_versioned_app",
83
+ "default_exception_handlers_provider",
84
+ "find_bearer",
85
+ "find_token",
86
+ "get_current_user_claims",
87
+ "load_app_name",
88
+ "load_versioning_settings",
89
+ "map_version_path",
90
+ "normalize_prefix",
91
+ "normalize_unversioned_label",
92
+ "normalize_version",
93
+ "param_factory",
94
+ "register_actuator_router",
95
+ "resolve_prefix",
96
+ "resolve_version",
97
+ "uuid_id_factory",
98
+ "validate_version_mapping_keys",
99
+ )
@@ -0,0 +1,28 @@
1
+ from csrd.context._constants import APP_ID_HEADER_NAME, HIT_ID_HEADER_NAME
2
+
3
+ AUTH_HEADER_NAME = "authorization"
4
+ API_VERSION_HEADER_NAME = "x-api-version"
5
+ VERSIONING_SETTINGS_STATE_KEY = "_versioning_settings"
6
+ UNVERSIONED_DISPLAY_LABEL = "Unversioned"
7
+ UNVERSIONED = "unv"
8
+ """Sentinel for unversioned routes in version mappings.
9
+
10
+ Use as a key in ``version_mapping`` or as the ``default_version`` argument
11
+ to indicate routes that do not belong to any numbered API version.
12
+ This is the canonical normalized form — ``normalize_version(None)``
13
+ and ``normalize_version("unversioned")`` both produce this value.
14
+ """
15
+
16
+ HTTP_METHODS = frozenset({"get", "post", "put", "delete", "patch", "options", "head"})
17
+
18
+
19
+ __all__ = (
20
+ "API_VERSION_HEADER_NAME",
21
+ "APP_ID_HEADER_NAME",
22
+ "AUTH_HEADER_NAME",
23
+ "HIT_ID_HEADER_NAME",
24
+ "HTTP_METHODS",
25
+ "UNVERSIONED",
26
+ "UNVERSIONED_DISPLAY_LABEL",
27
+ "VERSIONING_SETTINGS_STATE_KEY",
28
+ )
@@ -0,0 +1,240 @@
1
+ import logging
2
+ import re
3
+ from enum import Enum
4
+
5
+ from ._constants import UNVERSIONED_DISPLAY_LABEL
6
+ from ._types import VersionKey, VersionMap
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ _UNVERSIONED_ALIASES: frozenset[str] = frozenset({"null", "unv", "none", "unversioned"})
11
+
12
+
13
+ def normalize_version(version: VersionKey) -> str:
14
+ """Normalize version-like values to lowercase canonical routing keys.
15
+
16
+ - ``Enum`` members are unwrapped via ``.value`` before normalization.
17
+ - ``None``, empty strings, whitespace-only strings, and the aliases
18
+ ``"null"``, ``"unv"``, ``"none"``, ``"unversioned"`` (case-insensitive)
19
+ all normalize to ``"unv"``.
20
+ - All other values are stripped, then lowercased via ``str(version).lower()``,
21
+ including bare integers (e.g. ``3`` → ``"3"``).
22
+ """
23
+ if isinstance(version, Enum):
24
+ version = version.value
25
+ stringified = str(version).strip() if version is not None else ""
26
+ if version is None or not stringified or stringified.lower() in _UNVERSIONED_ALIASES:
27
+ return "unv"
28
+ return stringified.lower()
29
+
30
+
31
+ def normalize_prefix(prefix: str) -> str:
32
+ """Return an API prefix guaranteed to start with ``/``.
33
+
34
+ Raises ``ValueError`` for empty strings — use ``"/"`` explicitly
35
+ if you intend to match all paths.
36
+ """
37
+ if not prefix:
38
+ raise ValueError("prefix must not be empty; pass '/' explicitly to match all paths")
39
+ normalized = prefix if prefix.startswith("/") else f"/{prefix}"
40
+ if normalized != "/":
41
+ normalized = normalized.rstrip("/")
42
+ return normalized
43
+
44
+
45
+ def normalize_unversioned_label(version: VersionKey) -> str:
46
+ """Map unversioned-like keys to a stable display label."""
47
+ normalized = normalize_version(version)
48
+ if normalized == "unv":
49
+ return UNVERSIONED_DISPLAY_LABEL
50
+ return normalized
51
+
52
+
53
+ def validate_version_mapping_keys(version_mapping: VersionMap) -> None:
54
+ """Ensure version keys do not collide after normalization."""
55
+ seen: dict[str, str] = {}
56
+ for key in version_mapping:
57
+ normalized = normalize_version(key)
58
+ if normalized in seen:
59
+ existing_key = seen[normalized]
60
+ raise ValueError(
61
+ "Duplicate version keys after normalization: "
62
+ f"{existing_key!r} and {key!r} both normalize to '{normalized}'."
63
+ )
64
+ seen[normalized] = str(key)
65
+
66
+
67
+ def _latest_mapped_version(version_values: list[str]) -> str:
68
+ """Pick the latest mapped version deterministically.
69
+
70
+ Comparison uses only numeric segments (e.g. ``"v2"`` → ``(2,)``).
71
+ Non-numeric characters between digits are ignored, so versions
72
+ like ``"v1a2"`` and ``"v1b1"`` are compared as ``(1, 2)`` vs ``(1, 1)``.
73
+ """
74
+ candidates = [v for v in version_values if v != "unv"]
75
+ if not candidates:
76
+ return "unv"
77
+
78
+ numeric_candidates = [v for v in candidates if re.search(r"\d", v)]
79
+ if numeric_candidates:
80
+ return max(
81
+ numeric_candidates,
82
+ key=lambda value: (tuple(int(x) for x in re.findall(r"\d+", value)), value),
83
+ )
84
+
85
+ return sorted(candidates)[-1]
86
+
87
+
88
+ def _default_mapped_version(
89
+ *, version_values: set[str], default_version: VersionKey | None
90
+ ) -> str | None:
91
+ """Return a normalized default version only when it exists in the mapping."""
92
+ if default_version is None:
93
+ return None
94
+
95
+ normalized_default = normalize_version(default_version)
96
+ if normalized_default in version_values:
97
+ return normalized_default
98
+
99
+ return None
100
+
101
+
102
+ def _resolve_missing_requested_version(
103
+ *,
104
+ version_values: set[str],
105
+ mapped_default: str | None,
106
+ ) -> str:
107
+ """Resolve version when the request does not include a version header."""
108
+ if "unv" in version_values:
109
+ return "unv"
110
+
111
+ if mapped_default is not None:
112
+ return mapped_default
113
+
114
+ return _latest_mapped_version(list(version_values))
115
+
116
+
117
+ def _resolve_unknown_requested_version(
118
+ *,
119
+ version_values: set[str],
120
+ mapped_default: str | None,
121
+ ) -> str:
122
+ """Resolve version when the request header is present but not mapped."""
123
+ if mapped_default is not None:
124
+ return mapped_default
125
+
126
+ if "unv" in version_values:
127
+ return "unv"
128
+
129
+ return _latest_mapped_version(list(version_values))
130
+
131
+
132
+ def resolve_version(
133
+ *,
134
+ requested_version: str | None,
135
+ version_mapping: VersionMap | None = None,
136
+ default_version: VersionKey | None = None,
137
+ strict: bool = False,
138
+ ) -> str:
139
+ """Resolve request version using explicit, deterministic fallback precedence.
140
+
141
+ Fallback order when the requested version is not in *version_mapping*:
142
+
143
+ 1. *default_version* (if provided and present in the mapping)
144
+ 2. ``"unv"`` (if present in the mapping)
145
+ 3. Latest numeric version
146
+
147
+ When *strict* is ``True``, an unrecognised requested version raises
148
+ ``ValueError`` instead of falling back. Missing headers (``None``)
149
+ still fall back normally — strict mode only rejects explicit but
150
+ unknown version values.
151
+
152
+ .. important::
153
+
154
+ Raises ``ValueError`` if *version_mapping* keys collide after
155
+ normalization (e.g. ``None`` and ``"unversioned"`` both normalize
156
+ to ``"unv"``).
157
+ """
158
+ if version_mapping is None:
159
+ if requested_version is None:
160
+ return "unv"
161
+ return normalize_version(requested_version)
162
+
163
+ version_values = {normalize_version(key) for key in version_mapping}
164
+ if len(version_values) < len(version_mapping):
165
+ validate_version_mapping_keys(version_mapping)
166
+ mapped_default = _default_mapped_version(
167
+ version_values=version_values,
168
+ default_version=default_version,
169
+ )
170
+ requested_normalized = (
171
+ normalize_version(requested_version) if requested_version is not None else None
172
+ )
173
+
174
+ if requested_normalized in version_values:
175
+ return requested_normalized
176
+
177
+ if requested_normalized is None:
178
+ return _resolve_missing_requested_version(
179
+ version_values=version_values,
180
+ mapped_default=mapped_default,
181
+ )
182
+
183
+ if strict:
184
+ raise ValueError(
185
+ f"Requested API version {requested_normalized!r} is not available. "
186
+ f"Available versions: {', '.join(sorted(version_values))}"
187
+ )
188
+
189
+ resolved = _resolve_unknown_requested_version(
190
+ version_values=version_values,
191
+ mapped_default=mapped_default,
192
+ )
193
+ logger.warning(
194
+ "Requested API version %r is not mapped (available: %s); falling back to %r",
195
+ requested_normalized,
196
+ ", ".join(sorted(version_values)),
197
+ resolved,
198
+ )
199
+ return resolved
200
+
201
+
202
+ def map_version_path(path: str, *, version: str, prefix: str) -> str:
203
+ """Rewrite an incoming path to include resolved version under the API prefix.
204
+
205
+ The prefix precondition is also enforced upstream by the dispatch guard
206
+ ``_should_dispatch_request``, but the check here is intentional
207
+ defense-in-depth — do not remove it.
208
+ """
209
+ if prefix == "/":
210
+ if not path.startswith("/"):
211
+ raise ValueError(f"path {path!r} does not start with prefix {prefix!r}")
212
+ elif not (path == prefix or path.startswith(f"{prefix}/")):
213
+ raise ValueError(f"path {path!r} does not start with prefix {prefix!r}")
214
+ normalized_version = normalize_version(version)
215
+ remainder = path[len(prefix) :]
216
+ if remainder and not remainder.startswith("/"):
217
+ remainder = f"/{remainder}"
218
+ # Normalize bare trailing slash so /api/ behaves identically to /api.
219
+ if remainder == "/":
220
+ remainder = ""
221
+ return f"{prefix.rstrip('/')}/{normalized_version}{remainder}"
222
+
223
+
224
+ def resolve_prefix(prefix: str | None) -> str:
225
+ """Return normalized API prefix, defaulting to `/api`."""
226
+ if prefix is None:
227
+ prefix = "/api"
228
+
229
+ return normalize_prefix(prefix)
230
+
231
+
232
+ __all__ = (
233
+ "map_version_path",
234
+ "normalize_prefix",
235
+ "normalize_unversioned_label",
236
+ "normalize_version",
237
+ "resolve_prefix",
238
+ "resolve_version",
239
+ "validate_version_mapping_keys",
240
+ )