platform-commons 0.3.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.
@@ -0,0 +1,13 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.egg-info/
4
+ .venv/
5
+ .pytest_cache/
6
+ .DS_Store
7
+ dist/
8
+ build/
9
+ *.whl
10
+ .pip-cache/
11
+ .ruff_cache/
12
+ .mypy_cache/
13
+ reports/
@@ -0,0 +1,84 @@
1
+ stages:
2
+ - lint
3
+ - security
4
+ - test
5
+ - publish
6
+
7
+ variables:
8
+ PIP_CACHE_DIR: "$CI_PROJECT_DIR/.pip-cache"
9
+ PYTHONDONTWRITEBYTECODE: "1"
10
+
11
+ default:
12
+ tags:
13
+ - software-ci
14
+ before_script:
15
+ - rm -rf .venv
16
+ - python3 -m venv .venv
17
+ - . .venv/bin/activate
18
+ - python -m pip install --upgrade pip
19
+ - python -m pip install -e ".[test]"
20
+ - python -m pip install ruff mypy
21
+ cache:
22
+ key: pip-${CI_COMMIT_REF_SLUG}
23
+ paths:
24
+ - .pip-cache/
25
+ - .venv/
26
+
27
+ # ── Lint ─────────────────────────────────────────────
28
+ ruff-lint:
29
+ stage: lint
30
+ script:
31
+ - ruff check platform_commons/ tests/
32
+ - ruff format --check platform_commons/ tests/
33
+ rules:
34
+ - if: $CI_PIPELINE_SOURCE == "merge_request_event"
35
+ - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
36
+
37
+ mypy-check:
38
+ stage: lint
39
+ script:
40
+ - mypy platform_commons/ --strict
41
+ rules:
42
+ - if: $CI_PIPELINE_SOURCE == "merge_request_event"
43
+ - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
44
+
45
+ # ── Security ─────────────────────────────────────────
46
+ gitleaks:
47
+ stage: security
48
+ before_script: []
49
+ cache: {}
50
+ script:
51
+ - which gitleaks && gitleaks detect --source . --verbose || echo "gitleaks not available, skipped"
52
+ allow_failure: true
53
+ rules:
54
+ - if: $CI_PIPELINE_SOURCE == "merge_request_event"
55
+ - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
56
+
57
+ # ── Test ─────────────────────────────────────────────
58
+ pytest:
59
+ stage: test
60
+ script:
61
+ - python -m pytest tests/ -v --tb=short --junitxml=reports/unit.xml
62
+ artifacts:
63
+ when: always
64
+ reports:
65
+ junit: reports/unit.xml
66
+ rules:
67
+ - if: $CI_PIPELINE_SOURCE == "merge_request_event"
68
+ - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
69
+ - if: $CI_COMMIT_TAG
70
+
71
+ # ── Publish ──────────────────────────────────────────
72
+ # Triggers ONLY on version tags (v0.3.0, v1.0.0, etc.)
73
+ # Requires CI/CD variable: PYPI_TOKEN (PyPI API token)
74
+ publish-pypi:
75
+ stage: publish
76
+ before_script:
77
+ - python3 -m venv .venv
78
+ - . .venv/bin/activate
79
+ - python -m pip install --upgrade pip build twine
80
+ script:
81
+ - python -m build
82
+ - python -m twine upload dist/* --username __token__ --password ${PYPI_TOKEN}
83
+ rules:
84
+ - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
@@ -0,0 +1,17 @@
1
+ # Gitleaks configuration for platform-commons
2
+ # See https://github.com/gitleaks/gitleaks
3
+
4
+ title = "Platform Commons Gitleaks Configuration"
5
+
6
+ [allowlist]
7
+ description = "Global allowlist"
8
+ paths = [
9
+ '''\.venv/''',
10
+ '''\.git/''',
11
+ '''\.mypy_cache/''',
12
+ '''\.pytest_cache/''',
13
+ '''\.ruff_cache/''',
14
+ '''__pycache__/''',
15
+ '''\.egg-info/''',
16
+ '''\.pip-cache/''',
17
+ ]
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: platform-commons
3
+ Version: 0.3.0
4
+ Summary: Shared platform libraries for AI Development Platform
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: fastapi>=0.109.0
7
+ Requires-Dist: httpx>=0.26.0
8
+ Requires-Dist: starlette>=0.36.0
9
+ Provides-Extra: dev
10
+ Requires-Dist: build>=1.0.0; extra == 'dev'
11
+ Requires-Dist: mypy>=1.8.0; extra == 'dev'
12
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
13
+ Requires-Dist: pytest>=8.0; extra == 'dev'
14
+ Requires-Dist: ruff>=0.3.0; extra == 'dev'
15
+ Requires-Dist: twine>=5.0.0; extra == 'dev'
16
+ Provides-Extra: structured-logging
17
+ Requires-Dist: structlog>=24.0.0; extra == 'structured-logging'
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
20
+ Requires-Dist: pytest>=8.0; extra == 'test'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # platform_commons
24
+
25
+
26
+
27
+ ## Getting started
28
+
29
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
30
+
31
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
32
+
33
+ ## Add your files
34
+
35
+ * [Create](https://docs.gitlab.com/user/project/repository/web_editor/#create-a-file) or [upload](https://docs.gitlab.com/user/project/repository/web_editor/#upload-a-file) files
36
+ * [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
37
+
38
+ ```
39
+ cd existing_repo
40
+ git remote add origin https://gitlab.com/sharabarov/platform_commons.git
41
+ git branch -M main
42
+ git push -uf origin main
43
+ ```
44
+
45
+ ## Integrate with your tools
46
+
47
+ * [Set up project integrations](https://gitlab.com/sharabarov/platform_commons/-/settings/integrations)
48
+
49
+ ## Collaborate with your team
50
+
51
+ * [Invite team members and collaborators](https://docs.gitlab.com/user/project/members/)
52
+ * [Create a new merge request](https://docs.gitlab.com/user/project/merge_requests/creating_merge_requests/)
53
+ * [Automatically close issues from merge requests](https://docs.gitlab.com/user/project/issues/managing_issues/#closing-issues-automatically)
54
+ * [Enable merge request approvals](https://docs.gitlab.com/user/project/merge_requests/approvals/)
55
+ * [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
56
+
57
+ ## Test and Deploy
58
+
59
+ Use the built-in continuous integration in GitLab.
60
+
61
+ * [Get started with GitLab CI/CD](https://docs.gitlab.com/ci/quick_start/)
62
+ * [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/user/application_security/sast/)
63
+ * [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/topics/autodevops/requirements/)
64
+ * [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/user/clusters/agent/)
65
+ * [Set up protected environments](https://docs.gitlab.com/ci/environments/protected_environments/)
66
+
67
+ ***
68
+
69
+ # Editing this README
70
+
71
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
72
+
73
+ ## Suggestions for a good README
74
+
75
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
76
+
77
+ ## Name
78
+ Choose a self-explaining name for your project.
79
+
80
+ ## Description
81
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
82
+
83
+ ## Badges
84
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
85
+
86
+ ## Visuals
87
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
88
+
89
+ ## Installation
90
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
91
+
92
+ ## Usage
93
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
94
+
95
+ ## Support
96
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
97
+
98
+ ## Roadmap
99
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
100
+
101
+ ## Contributing
102
+ State if you are open to contributions and what your requirements are for accepting them.
103
+
104
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
105
+
106
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
107
+
108
+ ## Authors and acknowledgment
109
+ Show your appreciation to those who have contributed to the project.
110
+
111
+ ## License
112
+ For open source projects, say how it is licensed.
113
+
114
+ ## Project status
115
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
@@ -0,0 +1,93 @@
1
+ # platform_commons
2
+
3
+
4
+
5
+ ## Getting started
6
+
7
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
8
+
9
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
10
+
11
+ ## Add your files
12
+
13
+ * [Create](https://docs.gitlab.com/user/project/repository/web_editor/#create-a-file) or [upload](https://docs.gitlab.com/user/project/repository/web_editor/#upload-a-file) files
14
+ * [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
15
+
16
+ ```
17
+ cd existing_repo
18
+ git remote add origin https://gitlab.com/sharabarov/platform_commons.git
19
+ git branch -M main
20
+ git push -uf origin main
21
+ ```
22
+
23
+ ## Integrate with your tools
24
+
25
+ * [Set up project integrations](https://gitlab.com/sharabarov/platform_commons/-/settings/integrations)
26
+
27
+ ## Collaborate with your team
28
+
29
+ * [Invite team members and collaborators](https://docs.gitlab.com/user/project/members/)
30
+ * [Create a new merge request](https://docs.gitlab.com/user/project/merge_requests/creating_merge_requests/)
31
+ * [Automatically close issues from merge requests](https://docs.gitlab.com/user/project/issues/managing_issues/#closing-issues-automatically)
32
+ * [Enable merge request approvals](https://docs.gitlab.com/user/project/merge_requests/approvals/)
33
+ * [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
34
+
35
+ ## Test and Deploy
36
+
37
+ Use the built-in continuous integration in GitLab.
38
+
39
+ * [Get started with GitLab CI/CD](https://docs.gitlab.com/ci/quick_start/)
40
+ * [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/user/application_security/sast/)
41
+ * [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/topics/autodevops/requirements/)
42
+ * [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/user/clusters/agent/)
43
+ * [Set up protected environments](https://docs.gitlab.com/ci/environments/protected_environments/)
44
+
45
+ ***
46
+
47
+ # Editing this README
48
+
49
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
50
+
51
+ ## Suggestions for a good README
52
+
53
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
54
+
55
+ ## Name
56
+ Choose a self-explaining name for your project.
57
+
58
+ ## Description
59
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
60
+
61
+ ## Badges
62
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
63
+
64
+ ## Visuals
65
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
66
+
67
+ ## Installation
68
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
69
+
70
+ ## Usage
71
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
72
+
73
+ ## Support
74
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
75
+
76
+ ## Roadmap
77
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
78
+
79
+ ## Contributing
80
+ State if you are open to contributions and what your requirements are for accepting them.
81
+
82
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
83
+
84
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
85
+
86
+ ## Authors and acknowledgment
87
+ Show your appreciation to those who have contributed to the project.
88
+
89
+ ## License
90
+ For open source projects, say how it is licensed.
91
+
92
+ ## Project status
93
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
@@ -0,0 +1 @@
1
+ """Platform Commons — shared libraries for AI Development Platform."""
@@ -0,0 +1,145 @@
1
+ """Unified error middleware — PLATFORM_CONTRACT_STANDARD §4.
2
+
3
+ Catches PlatformError and unhandled exceptions, returns unified JSON:
4
+ {
5
+ "error": {
6
+ "code": "<ERROR_CODE>",
7
+ "message": "<human-readable>",
8
+ "details": {<structured>},
9
+ "trace_id": "<from X-Trace-Id>"
10
+ }
11
+ }
12
+
13
+ Usage:
14
+ from platform_commons.error_middleware import setup_error_handling
15
+ setup_error_handling(app)
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
+ import uuid
22
+
23
+ from fastapi import FastAPI, HTTPException, Request
24
+ from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
25
+ from starlette.responses import JSONResponse, Response
26
+
27
+ from .exceptions import PlatformError
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ def _generate_trace_id() -> str:
33
+ return f"trace_{uuid.uuid4().hex[:12]}"
34
+
35
+
36
+ def _get_trace_id(request: Request) -> str:
37
+ return (
38
+ request.headers.get("x-trace-id")
39
+ or getattr(request.state, "trace_id", None)
40
+ or _generate_trace_id()
41
+ )
42
+
43
+
44
+ def _error_response(
45
+ status_code: int, code: str, message: str, details: dict[str, object], trace_id: str
46
+ ) -> JSONResponse:
47
+ return JSONResponse(
48
+ status_code=status_code,
49
+ content={
50
+ "error": {
51
+ "code": code,
52
+ "message": message,
53
+ "details": details,
54
+ "trace_id": trace_id,
55
+ }
56
+ },
57
+ headers={"X-Trace-Id": trace_id},
58
+ )
59
+
60
+
61
+ class PlatformErrorMiddleware(BaseHTTPMiddleware):
62
+ """Unified error handling middleware.
63
+
64
+ 1. Extracts trace_id from X-Trace-Id header (or generates one)
65
+ 2. Catches PlatformError → structured JSON response
66
+ 3. Catches unhandled Exception → 500 INTERNAL_ERROR
67
+ 4. Always includes trace_id in response header
68
+
69
+ Note: HTTPException is handled by FastAPI exception handlers registered
70
+ via setup_error_handling(), not by this middleware.
71
+ """
72
+
73
+ async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
74
+ trace_id = _get_trace_id(request)
75
+ request.state.trace_id = trace_id
76
+
77
+ try:
78
+ return await call_next(request)
79
+
80
+ except PlatformError as exc:
81
+ logger.warning(
82
+ "PlatformError: %s [%s] trace_id=%s path=%s",
83
+ exc.code,
84
+ exc.status_code,
85
+ trace_id,
86
+ request.url.path,
87
+ )
88
+ return _error_response(exc.status_code, exc.code, exc.message, exc.details, trace_id)
89
+
90
+ except Exception:
91
+ logger.exception(
92
+ "Unhandled exception trace_id=%s path=%s",
93
+ trace_id,
94
+ request.url.path,
95
+ )
96
+ return _error_response(500, "INTERNAL_ERROR", "Internal server error", {}, trace_id)
97
+
98
+
99
+ def setup_error_handling(app: FastAPI) -> None:
100
+ """Register PlatformErrorMiddleware + exception handlers on a FastAPI app.
101
+
102
+ This is the recommended single entry point. It:
103
+ 1. Adds PlatformErrorMiddleware (catches PlatformError + unhandled)
104
+ 2. Registers exception_handler for HTTPException (standard format)
105
+ 3. Registers exception_handler for PlatformError (fallback for
106
+ exceptions raised in dependencies/middleware that bypass dispatch)
107
+ """
108
+ app.add_middleware(PlatformErrorMiddleware)
109
+
110
+ @app.exception_handler(HTTPException)
111
+ async def _handle_http_exception(request: Request, exc: HTTPException) -> JSONResponse:
112
+ trace_id = _get_trace_id(request)
113
+
114
+ # If detail is already a dict with "code"/"message", use it directly
115
+ # (supports services that already pass structured error dicts)
116
+ details: dict[str, object]
117
+ if isinstance(exc.detail, dict) and "code" in exc.detail:
118
+ code = exc.detail["code"]
119
+ message = exc.detail.get("message", str(exc.detail))
120
+ details = {k: v for k, v in exc.detail.items() if k not in ("code", "message")}
121
+ else:
122
+ code = f"HTTP_{exc.status_code}"
123
+ message = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
124
+ details = {}
125
+
126
+ logger.warning(
127
+ "HTTPException: %s [%d] trace_id=%s path=%s",
128
+ code,
129
+ exc.status_code,
130
+ trace_id,
131
+ request.url.path,
132
+ )
133
+ return _error_response(exc.status_code, code, message, details, trace_id)
134
+
135
+ @app.exception_handler(PlatformError)
136
+ async def _handle_platform_error(request: Request, exc: PlatformError) -> JSONResponse:
137
+ trace_id = _get_trace_id(request)
138
+ logger.warning(
139
+ "PlatformError (handler): %s [%s] trace_id=%s path=%s",
140
+ exc.code,
141
+ exc.status_code,
142
+ trace_id,
143
+ request.url.path,
144
+ )
145
+ return _error_response(exc.status_code, exc.code, exc.message, exc.details, trace_id)
@@ -0,0 +1,105 @@
1
+ """Platform-standard exception hierarchy.
2
+
3
+ All exceptions follow PLATFORM_CONTRACT_STANDARD §4:
4
+ {error: {code, message, details, trace_id}}
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+
10
+ class PlatformError(Exception):
11
+ """Base exception for all platform services.
12
+
13
+ Caught by PlatformErrorMiddleware and rendered as:
14
+ {
15
+ "error": {
16
+ "code": self.code,
17
+ "message": self.message,
18
+ "details": self.details,
19
+ "trace_id": <from X-Trace-Id header>
20
+ }
21
+ }
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ code: str,
27
+ message: str,
28
+ status_code: int = 400,
29
+ details: dict[str, object] | None = None,
30
+ ):
31
+ self.code = code
32
+ self.message = message
33
+ self.status_code = status_code
34
+ self.details = details or {}
35
+ super().__init__(message)
36
+
37
+
38
+ class NotFoundError(PlatformError):
39
+ """Resource not found (404)."""
40
+
41
+ def __init__(self, resource: str, resource_id: str, **extra_details: object):
42
+ super().__init__(
43
+ code=f"{resource.upper()}_NOT_FOUND",
44
+ message=f"{resource} {resource_id} not found",
45
+ status_code=404,
46
+ details={"resource": resource, "id": resource_id, **extra_details},
47
+ )
48
+
49
+
50
+ class ValidationError(PlatformError):
51
+ """Invalid request payload (400)."""
52
+
53
+ def __init__(self, code: str, message: str, **extra_details: object):
54
+ super().__init__(
55
+ code=code,
56
+ message=message,
57
+ status_code=400,
58
+ details=dict(extra_details),
59
+ )
60
+
61
+
62
+ class ConflictError(PlatformError):
63
+ """State conflict or duplicate (409)."""
64
+
65
+ def __init__(self, code: str, message: str, **extra_details: object):
66
+ super().__init__(
67
+ code=code,
68
+ message=message,
69
+ status_code=409,
70
+ details=dict(extra_details),
71
+ )
72
+
73
+
74
+ class ForbiddenError(PlatformError):
75
+ """Insufficient permissions (403)."""
76
+
77
+ def __init__(
78
+ self,
79
+ code: str = "SCOPE_INSUFFICIENT",
80
+ message: str = "Insufficient permissions",
81
+ **extra_details: object,
82
+ ):
83
+ super().__init__(
84
+ code=code,
85
+ message=message,
86
+ status_code=403,
87
+ details=dict(extra_details),
88
+ )
89
+
90
+
91
+ class ServiceUnavailableError(PlatformError):
92
+ """Downstream service unavailable (503)."""
93
+
94
+ def __init__(
95
+ self,
96
+ service: str,
97
+ message: str | None = None,
98
+ **extra_details: object,
99
+ ):
100
+ super().__init__(
101
+ code="SERVICE_UNAVAILABLE",
102
+ message=message or f"{service} is temporarily unavailable",
103
+ status_code=503,
104
+ details={"service": service, **extra_details},
105
+ )
@@ -0,0 +1,68 @@
1
+ """Platform HTTP client with automatic trace header propagation.
2
+
3
+ Usage:
4
+ from platform_commons.http_client import get_trace_headers
5
+
6
+ # In any outgoing HTTP call:
7
+ headers = {**existing_headers, **get_trace_headers()}
8
+ await httpx_client.post(url, json=data, headers=headers)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import uuid
14
+ from typing import Any
15
+
16
+ import httpx
17
+
18
+ from .trace_middleware import get_trace_context
19
+
20
+
21
+ def _generate_request_id() -> str:
22
+ return f"req_{uuid.uuid4().hex[:12]}"
23
+
24
+
25
+ def get_trace_headers() -> dict[str, str]:
26
+ """Get trace headers for outgoing HTTP requests.
27
+
28
+ X-Trace-Id: same as incoming (preserved through chain)
29
+ X-Request-Id: NEW for each outgoing call (unique per hop)
30
+ """
31
+ ctx = get_trace_context()
32
+ headers: dict[str, str] = {"X-Request-Id": _generate_request_id()}
33
+ if ctx:
34
+ headers["X-Trace-Id"] = ctx.trace_id
35
+ return headers
36
+
37
+
38
+ class PlatformHTTPClient:
39
+ """httpx.AsyncClient wrapper with automatic trace propagation."""
40
+
41
+ def __init__(self, base_url: str = "", timeout: float = 30.0, **kwargs: Any) -> None:
42
+ self._client = httpx.AsyncClient(base_url=base_url, timeout=timeout, **kwargs)
43
+
44
+ async def request(self, method: str, url: str, **kwargs: Any) -> httpx.Response:
45
+ headers: dict[str, str] = dict(kwargs.pop("headers", None) or {})
46
+ headers.update(get_trace_headers())
47
+ return await self._client.request(method, url, headers=headers, **kwargs)
48
+
49
+ async def get(self, url: str, **kwargs: Any) -> httpx.Response:
50
+ return await self.request("GET", url, **kwargs)
51
+
52
+ async def post(self, url: str, **kwargs: Any) -> httpx.Response:
53
+ return await self.request("POST", url, **kwargs)
54
+
55
+ async def put(self, url: str, **kwargs: Any) -> httpx.Response:
56
+ return await self.request("PUT", url, **kwargs)
57
+
58
+ async def delete(self, url: str, **kwargs: Any) -> httpx.Response:
59
+ return await self.request("DELETE", url, **kwargs)
60
+
61
+ async def aclose(self) -> None:
62
+ await self._client.aclose()
63
+
64
+ async def __aenter__(self) -> PlatformHTTPClient:
65
+ return self
66
+
67
+ async def __aexit__(self, *args: object) -> None:
68
+ await self.aclose()
@@ -0,0 +1,87 @@
1
+ """Unified trace context middleware — PLATFORM_CONTRACT_STANDARD §5.
2
+
3
+ Extracts/generates X-Trace-Id and X-Request-Id, stores in request.state
4
+ and contextvars for logging and outgoing HTTP propagation.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import uuid
10
+ from contextvars import ContextVar
11
+ from dataclasses import dataclass
12
+
13
+ from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
14
+ from starlette.requests import Request
15
+ from starlette.responses import Response
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class TraceContext:
20
+ """Immutable trace context propagated via contextvars."""
21
+
22
+ trace_id: str
23
+ request_id: str
24
+
25
+
26
+ trace_context: ContextVar[TraceContext] = ContextVar("trace_context")
27
+
28
+
29
+ def get_trace_context() -> TraceContext | None:
30
+ """Get current trace context from contextvars."""
31
+ return trace_context.get(None)
32
+
33
+
34
+ def _generate_id(prefix: str) -> str:
35
+ return f"{prefix}_{uuid.uuid4().hex[:12]}"
36
+
37
+
38
+ class PlatformTracingMiddleware(BaseHTTPMiddleware):
39
+ """Extract/generate trace headers, propagate through request lifecycle.
40
+
41
+ - X-Trace-Id: preserved from incoming request or generated.
42
+ SAME across entire call chain (ADM -> Router -> WM -> Worker).
43
+ - X-Request-Id: preserved from incoming or generated.
44
+ New per hop for outgoing calls.
45
+ - Also extracts context headers into request.state.
46
+ """
47
+
48
+ async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
49
+ trace_id = request.headers.get("x-trace-id") or _generate_id("trace")
50
+ request_id = request.headers.get("x-request-id") or _generate_id("req")
51
+
52
+ # Store in request.state
53
+ request.state.trace_id = trace_id
54
+ request.state.request_id = request_id
55
+
56
+ # Extract context headers
57
+ request.state.execution_id = request.headers.get("x-execution-id") or ""
58
+ request.state.task_id = request.headers.get("x-task-id") or ""
59
+ request.state.org_id = request.headers.get("x-org-id") or ""
60
+ request.state.membership_id = request.headers.get("x-membership-id") or ""
61
+ request.state.workflow_instance_id = request.headers.get("x-workflow-instance-id") or ""
62
+
63
+ # Store in contextvars for outgoing HTTP calls
64
+ ctx = TraceContext(trace_id=trace_id, request_id=request_id)
65
+ token = trace_context.set(ctx)
66
+
67
+ # Optional structlog binding (if available)
68
+ try:
69
+ import structlog # type: ignore[import-not-found] # noqa: PLC0415
70
+
71
+ structlog.contextvars.clear_contextvars()
72
+ bind_kwargs: dict[str, str] = {"trace_id": trace_id}
73
+ if request.state.workflow_instance_id:
74
+ bind_kwargs["workflow_instance_id"] = request.state.workflow_instance_id
75
+ if request.state.task_id:
76
+ bind_kwargs["task_id"] = request.state.task_id
77
+ structlog.contextvars.bind_contextvars(**bind_kwargs)
78
+ except ImportError:
79
+ pass
80
+
81
+ try:
82
+ response = await call_next(request)
83
+ response.headers["X-Trace-Id"] = trace_id
84
+ response.headers["X-Request-Id"] = request_id
85
+ return response
86
+ finally:
87
+ trace_context.reset(token)
@@ -0,0 +1,93 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "platform-commons"
7
+ version = "0.3.0"
8
+ description = "Shared platform libraries for AI Development Platform"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ dependencies = [
12
+ "fastapi>=0.109.0",
13
+ "starlette>=0.36.0",
14
+ "httpx>=0.26.0",
15
+ ]
16
+
17
+ [project.optional-dependencies]
18
+ test = [
19
+ "pytest>=8.0",
20
+ "pytest-asyncio>=0.23",
21
+ ]
22
+ dev = [
23
+ "pytest>=8.0",
24
+ "pytest-asyncio>=0.23",
25
+ "ruff>=0.3.0",
26
+ "mypy>=1.8.0",
27
+ "build>=1.0.0",
28
+ "twine>=5.0.0",
29
+ ]
30
+ structured-logging = [
31
+ "structlog>=24.0.0",
32
+ ]
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["platform_commons"]
36
+
37
+ [tool.pytest.ini_options]
38
+ asyncio_mode = "auto"
39
+ testpaths = ["tests"]
40
+
41
+ [tool.ruff]
42
+ target-version = "py311"
43
+ line-length = 100
44
+
45
+ [tool.ruff.lint]
46
+ select = [
47
+ "E", # pycodestyle errors
48
+ "W", # pycodestyle warnings
49
+ "F", # pyflakes
50
+ "I", # isort
51
+ "B", # flake8-bugbear
52
+ "UP", # pyupgrade
53
+ "SIM", # flake8-simplify
54
+ "C90", # mccabe complexity
55
+ "S", # flake8-bandit (security)
56
+ "T20", # flake8-print
57
+ "RET", # flake8-return
58
+ "ARG", # flake8-unused-arguments
59
+ "PTH", # flake8-use-pathlib
60
+ "ERA", # eradicate (commented-out code)
61
+ "PL", # pylint subset
62
+ "RUF", # ruff-specific
63
+ ]
64
+ ignore = [
65
+ "S101", # allow assert in tests
66
+ "PLR0913", # allow many function args
67
+ "PLR2004", # allow magic numbers in comparisons
68
+ ]
69
+
70
+ [tool.ruff.lint.mccabe]
71
+ max-complexity = 10
72
+
73
+ [tool.ruff.lint.per-file-ignores]
74
+ "tests/**" = ["S101", "ARG", "PLR2004"]
75
+
76
+ [tool.ruff.lint.isort]
77
+ known-first-party = ["platform_commons"]
78
+
79
+ [tool.ruff.format]
80
+ quote-style = "double"
81
+ indent-style = "space"
82
+
83
+ [tool.mypy]
84
+ python_version = "3.11"
85
+ strict = true
86
+ warn_return_any = true
87
+ warn_unused_configs = true
88
+ disallow_untyped_defs = true
89
+ disallow_incomplete_defs = true
90
+ check_untyped_defs = true
91
+ no_implicit_optional = true
92
+ warn_redundant_casts = true
93
+ warn_unused_ignores = true
File without changes
@@ -0,0 +1,186 @@
1
+ """Tests for PlatformErrorMiddleware."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+ from fastapi import FastAPI, HTTPException
7
+ from httpx import ASGITransport, AsyncClient
8
+
9
+ from platform_commons.error_middleware import setup_error_handling
10
+ from platform_commons.exceptions import (
11
+ ConflictError,
12
+ ForbiddenError,
13
+ NotFoundError,
14
+ PlatformError,
15
+ ServiceUnavailableError,
16
+ ValidationError,
17
+ )
18
+
19
+
20
+ def _create_test_app() -> FastAPI:
21
+ """Create a minimal FastAPI app with error-triggering routes."""
22
+ app = FastAPI()
23
+ setup_error_handling(app)
24
+
25
+ @app.get("/ok")
26
+ async def ok() -> dict:
27
+ return {"status": "ok"}
28
+
29
+ @app.get("/platform-error")
30
+ async def platform_error() -> None:
31
+ raise PlatformError(
32
+ code="TEST_ERROR",
33
+ message="Something went wrong",
34
+ status_code=418,
35
+ details={"key": "value"},
36
+ )
37
+
38
+ @app.get("/not-found")
39
+ async def not_found() -> None:
40
+ raise NotFoundError("task", "task_01J2M9T4A2")
41
+
42
+ @app.get("/validation-error")
43
+ async def validation_error() -> None:
44
+ raise ValidationError(
45
+ code="DISPATCH_VALIDATION_FAILED",
46
+ message="Invalid task_type",
47
+ field="task_type",
48
+ value="unknown",
49
+ )
50
+
51
+ @app.get("/conflict")
52
+ async def conflict() -> None:
53
+ raise ConflictError(
54
+ code="DISPATCH_ALREADY_RUNNING",
55
+ message="Task already running",
56
+ task_id="task_01J",
57
+ )
58
+
59
+ @app.get("/forbidden")
60
+ async def forbidden() -> None:
61
+ raise ForbiddenError(org_id="org_acme")
62
+
63
+ @app.get("/service-unavailable")
64
+ async def service_unavailable() -> None:
65
+ raise ServiceUnavailableError("vault")
66
+
67
+ @app.get("/http-exception")
68
+ async def http_exception() -> None:
69
+ raise HTTPException(status_code=422, detail="Unprocessable entity")
70
+
71
+ @app.get("/unhandled")
72
+ async def unhandled() -> None:
73
+ raise RuntimeError("unexpected crash")
74
+
75
+ return app
76
+
77
+
78
+ @pytest.fixture
79
+ def app() -> FastAPI:
80
+ return _create_test_app()
81
+
82
+
83
+ @pytest.fixture
84
+ async def client(app: FastAPI) -> AsyncClient:
85
+ transport = ASGITransport(app=app)
86
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
87
+ yield c
88
+
89
+
90
+ async def test_success_returns_ok(client: AsyncClient) -> None:
91
+ resp = await client.get("/ok", headers={"X-Trace-Id": "trace_test123"})
92
+ assert resp.status_code == 200
93
+ assert resp.json() == {"status": "ok"}
94
+
95
+
96
+ async def test_success_does_not_duplicate_trace_header(client: AsyncClient) -> None:
97
+ """PlatformErrorMiddleware only sets trace_id on error responses.
98
+ Success responses rely on per-service tracing middleware."""
99
+ resp = await client.get("/ok")
100
+ assert resp.status_code == 200
101
+
102
+
103
+ async def test_platform_error(client: AsyncClient) -> None:
104
+ resp = await client.get("/platform-error", headers={"X-Trace-Id": "trace_pe01"})
105
+ assert resp.status_code == 418
106
+ body = resp.json()
107
+ assert body["error"]["code"] == "TEST_ERROR"
108
+ assert body["error"]["message"] == "Something went wrong"
109
+ assert body["error"]["details"] == {"key": "value"}
110
+ assert body["error"]["trace_id"] == "trace_pe01"
111
+ assert resp.headers["x-trace-id"] == "trace_pe01"
112
+
113
+
114
+ async def test_not_found_error(client: AsyncClient) -> None:
115
+ resp = await client.get("/not-found")
116
+ assert resp.status_code == 404
117
+ body = resp.json()
118
+ assert body["error"]["code"] == "TASK_NOT_FOUND"
119
+ assert "task_01J2M9T4A2" in body["error"]["message"]
120
+ assert body["error"]["details"]["resource"] == "task"
121
+ assert body["error"]["details"]["id"] == "task_01J2M9T4A2"
122
+
123
+
124
+ async def test_validation_error(client: AsyncClient) -> None:
125
+ resp = await client.get("/validation-error")
126
+ assert resp.status_code == 400
127
+ body = resp.json()
128
+ assert body["error"]["code"] == "DISPATCH_VALIDATION_FAILED"
129
+ assert body["error"]["details"]["field"] == "task_type"
130
+
131
+
132
+ async def test_conflict_error(client: AsyncClient) -> None:
133
+ resp = await client.get("/conflict")
134
+ assert resp.status_code == 409
135
+ body = resp.json()
136
+ assert body["error"]["code"] == "DISPATCH_ALREADY_RUNNING"
137
+ assert body["error"]["details"]["task_id"] == "task_01J"
138
+
139
+
140
+ async def test_forbidden_error(client: AsyncClient) -> None:
141
+ resp = await client.get("/forbidden")
142
+ assert resp.status_code == 403
143
+ body = resp.json()
144
+ assert body["error"]["code"] == "SCOPE_INSUFFICIENT"
145
+ assert body["error"]["details"]["org_id"] == "org_acme"
146
+
147
+
148
+ async def test_service_unavailable_error(client: AsyncClient) -> None:
149
+ resp = await client.get("/service-unavailable")
150
+ assert resp.status_code == 503
151
+ body = resp.json()
152
+ assert body["error"]["code"] == "SERVICE_UNAVAILABLE"
153
+ assert body["error"]["details"]["service"] == "vault"
154
+
155
+
156
+ async def test_http_exception_wrapped(client: AsyncClient) -> None:
157
+ resp = await client.get("/http-exception", headers={"X-Trace-Id": "trace_http01"})
158
+ assert resp.status_code == 422
159
+ body = resp.json()
160
+ assert body["error"]["code"] == "HTTP_422"
161
+ assert body["error"]["message"] == "Unprocessable entity"
162
+ assert body["error"]["trace_id"] == "trace_http01"
163
+
164
+
165
+ async def test_unhandled_exception_returns_500(client: AsyncClient) -> None:
166
+ resp = await client.get("/unhandled", headers={"X-Trace-Id": "trace_crash01"})
167
+ assert resp.status_code == 500
168
+ body = resp.json()
169
+ assert body["error"]["code"] == "INTERNAL_ERROR"
170
+ assert body["error"]["message"] == "Internal server error"
171
+ assert body["error"]["trace_id"] == "trace_crash01"
172
+
173
+
174
+ async def test_trace_id_present_in_all_error_responses(
175
+ client: AsyncClient,
176
+ ) -> None:
177
+ """Every error response must include trace_id in body and header."""
178
+ for path in [
179
+ "/platform-error",
180
+ "/not-found",
181
+ "/http-exception",
182
+ "/unhandled",
183
+ ]:
184
+ resp = await client.get(path, headers={"X-Trace-Id": "trace_check"})
185
+ assert "trace_id" in resp.json()["error"]
186
+ assert resp.headers["x-trace-id"] == "trace_check"
@@ -0,0 +1,39 @@
1
+ """Tests for platform HTTP client with trace propagation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from platform_commons.http_client import get_trace_headers
6
+ from platform_commons.trace_middleware import TraceContext, trace_context
7
+
8
+
9
+ def test_get_trace_headers_without_context() -> None:
10
+ """Without active trace context, only X-Request-Id is generated."""
11
+ headers = get_trace_headers()
12
+ assert "X-Request-Id" in headers
13
+ assert headers["X-Request-Id"].startswith("req_")
14
+ assert "X-Trace-Id" not in headers
15
+
16
+
17
+ def test_get_trace_headers_with_context() -> None:
18
+ """With active trace context, both headers are present."""
19
+ ctx = TraceContext(trace_id="trace_test1", request_id="req_orig")
20
+ token = trace_context.set(ctx)
21
+ try:
22
+ headers = get_trace_headers()
23
+ assert headers["X-Trace-Id"] == "trace_test1"
24
+ assert headers["X-Request-Id"].startswith("req_")
25
+ # Request-Id should be NEW (not the original)
26
+ assert headers["X-Request-Id"] != "req_orig"
27
+ finally:
28
+ trace_context.reset(token)
29
+
30
+
31
+ def test_get_trace_headers_generates_unique_request_ids() -> None:
32
+ """Each call generates a unique X-Request-Id."""
33
+ ctx = TraceContext(trace_id="trace_uniq", request_id="req_orig")
34
+ token = trace_context.set(ctx)
35
+ try:
36
+ ids = {get_trace_headers()["X-Request-Id"] for _ in range(10)}
37
+ assert len(ids) == 10 # All unique
38
+ finally:
39
+ trace_context.reset(token)
@@ -0,0 +1,101 @@
1
+ """Tests for PlatformTracingMiddleware."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+ from fastapi import FastAPI
7
+ from httpx import ASGITransport, AsyncClient
8
+
9
+ from platform_commons.trace_middleware import (
10
+ PlatformTracingMiddleware,
11
+ get_trace_context,
12
+ )
13
+
14
+
15
+ def _create_app() -> FastAPI:
16
+ app = FastAPI()
17
+ app.add_middleware(PlatformTracingMiddleware)
18
+
19
+ @app.get("/echo")
20
+ async def echo() -> dict:
21
+ ctx = get_trace_context()
22
+ return {
23
+ "trace_id": ctx.trace_id if ctx else None,
24
+ "request_id": ctx.request_id if ctx else None,
25
+ }
26
+
27
+ return app
28
+
29
+
30
+ @pytest.fixture
31
+ async def client() -> AsyncClient:
32
+ app = _create_app()
33
+ transport = ASGITransport(app=app)
34
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
35
+ yield c
36
+
37
+
38
+ async def test_generates_trace_id_when_absent(client: AsyncClient) -> None:
39
+ resp = await client.get("/echo")
40
+ assert resp.status_code == 200
41
+ assert resp.headers["x-trace-id"].startswith("trace_")
42
+ assert resp.json()["trace_id"].startswith("trace_")
43
+
44
+
45
+ async def test_preserves_incoming_trace_id(client: AsyncClient) -> None:
46
+ resp = await client.get("/echo", headers={"X-Trace-Id": "trace_incoming"})
47
+ assert resp.headers["x-trace-id"] == "trace_incoming"
48
+ assert resp.json()["trace_id"] == "trace_incoming"
49
+
50
+
51
+ async def test_generates_request_id_when_absent(client: AsyncClient) -> None:
52
+ resp = await client.get("/echo")
53
+ assert resp.status_code == 200
54
+ assert resp.headers["x-request-id"].startswith("req_")
55
+ assert resp.json()["request_id"].startswith("req_")
56
+
57
+
58
+ async def test_preserves_incoming_request_id(client: AsyncClient) -> None:
59
+ resp = await client.get("/echo", headers={"X-Request-Id": "req_incoming"})
60
+ assert resp.headers["x-request-id"] == "req_incoming"
61
+ assert resp.json()["request_id"] == "req_incoming"
62
+
63
+
64
+ async def test_context_headers_in_request_state() -> None:
65
+ """Context headers are extracted into request.state."""
66
+ app = FastAPI()
67
+ app.add_middleware(PlatformTracingMiddleware)
68
+
69
+ @app.get("/state-check")
70
+ async def state_check() -> dict[str, bool]:
71
+ return {"ok": True}
72
+
73
+ transport = ASGITransport(app=app)
74
+ async with AsyncClient(transport=transport, base_url="http://test") as c:
75
+ resp = await c.get(
76
+ "/state-check",
77
+ headers={
78
+ "X-Trace-Id": "trace_t1",
79
+ "X-Execution-Id": "exec_e1",
80
+ "X-Task-Id": "task_t1",
81
+ "X-Org-Id": "org_o1",
82
+ },
83
+ )
84
+ assert resp.status_code == 200
85
+ assert resp.headers["x-trace-id"] == "trace_t1"
86
+
87
+
88
+ async def test_contextvars_set_during_request(client: AsyncClient) -> None:
89
+ """TraceContext is available via get_trace_context() during request."""
90
+ resp = await client.get(
91
+ "/echo",
92
+ headers={"X-Trace-Id": "trace_cv1", "X-Request-Id": "req_cv1"},
93
+ )
94
+ body = resp.json()
95
+ assert body["trace_id"] == "trace_cv1"
96
+ assert body["request_id"] == "req_cv1"
97
+
98
+
99
+ async def test_contextvars_reset_after_request() -> None:
100
+ """TraceContext is reset after request completes."""
101
+ assert get_trace_context() is None