openframe-protocol-http 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,220 @@
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
+ *.lcov
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ cover/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ .pybuilder/
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ # For a library or package, you might want to ignore these files since the code is
88
+ # intended to run in multiple environments; otherwise, check them in:
89
+ # .python-version
90
+
91
+ # pipenv
92
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
94
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
95
+ # install all needed dependencies.
96
+ # Pipfile.lock
97
+
98
+ # uv
99
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
100
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
101
+ # commonly ignored for libraries.
102
+ # uv.lock
103
+
104
+ # poetry
105
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
106
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
107
+ # commonly ignored for libraries.
108
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
109
+ # poetry.lock
110
+ # poetry.toml
111
+
112
+ # pdm
113
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
114
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
115
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
116
+ # pdm.lock
117
+ # pdm.toml
118
+ .pdm-python
119
+ .pdm-build/
120
+
121
+ # pixi
122
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
123
+ # pixi.lock
124
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
125
+ # in the .venv directory. It is recommended not to include this directory in version control.
126
+ .pixi/*
127
+ !.pixi/config.toml
128
+
129
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
130
+ __pypackages__/
131
+
132
+ # Celery stuff
133
+ celerybeat-schedule*
134
+ celerybeat.pid
135
+
136
+ # Redis
137
+ *.rdb
138
+ *.aof
139
+ *.pid
140
+
141
+ # RabbitMQ
142
+ mnesia/
143
+ rabbitmq/
144
+ rabbitmq-data/
145
+
146
+ # ActiveMQ
147
+ activemq-data/
148
+
149
+ # SageMath parsed files
150
+ *.sage.py
151
+
152
+ # Environments
153
+ .env
154
+ .envrc
155
+ .venv
156
+ env/
157
+ venv/
158
+ ENV/
159
+ env.bak/
160
+ venv.bak/
161
+
162
+ # Spyder project settings
163
+ .spyderproject
164
+ .spyproject
165
+
166
+ # Rope project settings
167
+ .ropeproject
168
+
169
+ # mkdocs/Zensical documentation
170
+ /site
171
+
172
+ # mypy
173
+ .mypy_cache/
174
+ .dmypy.json
175
+ dmypy.json
176
+
177
+ # Pyre type checker
178
+ .pyre/
179
+
180
+ # pytype static type analyzer
181
+ .pytype/
182
+
183
+ # Cython debug symbols
184
+ cython_debug/
185
+
186
+ # PyCharm
187
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
188
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
189
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
190
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
191
+ # .idea/
192
+
193
+ # Abstra
194
+ # Abstra is an AI-powered process automation framework.
195
+ # Ignore directories containing user credentials, local state, and settings.
196
+ # Learn more at https://abstra.io/docs
197
+ .abstra/
198
+
199
+ # Visual Studio Code
200
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore that
201
+ # can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
202
+ # and can be added to the global gitignore or merged into this file. However, if you prefer, you
203
+ # could uncomment the following to ignore the entire vscode folder
204
+ # .vscode/
205
+ # Temporary file for partial code execution
206
+ tempCodeRunnerFile.py
207
+
208
+ # Ruff stuff:
209
+ .ruff_cache/
210
+
211
+ # PyPI configuration file
212
+ .pypirc
213
+
214
+ # Marimo
215
+ marimo/_static/
216
+ marimo/_lsp/
217
+ __marimo__/
218
+
219
+ # Streamlit
220
+ .streamlit/secrets.toml
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.5
2
+ Name: openframe-protocol-http
3
+ Version: 0.5.0
4
+ Summary: OpenFrame Microservice Suite - HTTP/ASGI server binding for openframe.core.inbound handlers.
5
+ Project-URL: Homepage, https://github.com/Furious-Meteors/openframe-protocol
6
+ Project-URL: Documentation, https://furious-meteors.github.io/openframe-protocol/
7
+ Project-URL: Repository, https://github.com/Furious-Meteors/openframe-protocol
8
+ Project-URL: Changelog, https://github.com/Furious-Meteors/openframe-protocol/blob/production/.github/CHANGELOG.md
9
+ Project-URL: Bug Tracker, https://github.com/Furious-Meteors/openframe-protocol/issues
10
+ Author-email: Furious Meteors Engineering <engineering@furiousmeteors.dev>
11
+ Maintainer-email: Furious Meteors Engineering <engineering@furiousmeteors.dev>
12
+ License: MIT
13
+ Keywords: fastapi,hexagonal,http,microservice,openframe,protocol
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.11
25
+ Requires-Dist: openframe-core<4,>=3.2.1
26
+ Requires-Dist: openframe-protocol-base<1,>=0.1
27
+ Provides-Extra: client
28
+ Requires-Dist: httpx>=0.27; extra == 'client'
29
+ Provides-Extra: dev
30
+ Requires-Dist: fastapi>=0.110; extra == 'dev'
31
+ Requires-Dist: httpx>=0.27; extra == 'dev'
32
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
33
+ Requires-Dist: pytest-mock>=3.14; extra == 'dev'
34
+ Requires-Dist: pytest>=8.0; extra == 'dev'
35
+ Provides-Extra: server
36
+ Requires-Dist: fastapi>=0.110; extra == 'server'
37
+ Description-Content-Type: text/markdown
38
+
39
+ # openframe-protocol-http
40
+
41
+ HTTP/ASGI server binding. Wires a `QueryHandler`/`CommandHandler`/`UseCase`
42
+ (`openframe.core.inbound`) to a FastAPI route through the shared error
43
+ mapper and `RequestContext` builder in `openframe-protocol-base`, instead
44
+ of each route hand-mapping `HTTPException`s itself.
45
+
46
+ Install the `[server]` extra for the FastAPI/ASGI dependencies —
47
+ `openframe-protocol-http[server]`.
48
+
49
+ ## Wiring example
50
+
51
+ ```python
52
+ from openframe.protocol.http import bind_query, bind_command, install_error_handlers
53
+
54
+ router = APIRouter(prefix="/items")
55
+
56
+ bind_query(
57
+ router, "/{item_id}",
58
+ handler_dep=get_get_item_handler,
59
+ path_param=("item_id", str),
60
+ response_model=Item,
61
+ not_found_when=lambda item: item is None,
62
+ )
63
+
64
+ bind_command(
65
+ router, "", method="POST",
66
+ handler_dep=get_create_item_handler,
67
+ body_model=Item,
68
+ status_code=201,
69
+ response_model=Item,
70
+ )
71
+
72
+ install_error_handlers(app)
73
+ ```
74
+
75
+ ## Status
76
+
77
+ Experimental, M1 of the project's own build plan — proves the inbound
78
+ handler contract survives a real transport before anything else
79
+ (HTTP client, gRPC, sessions) is attempted.
@@ -0,0 +1,41 @@
1
+ # openframe-protocol-http
2
+
3
+ HTTP/ASGI server binding. Wires a `QueryHandler`/`CommandHandler`/`UseCase`
4
+ (`openframe.core.inbound`) to a FastAPI route through the shared error
5
+ mapper and `RequestContext` builder in `openframe-protocol-base`, instead
6
+ of each route hand-mapping `HTTPException`s itself.
7
+
8
+ Install the `[server]` extra for the FastAPI/ASGI dependencies —
9
+ `openframe-protocol-http[server]`.
10
+
11
+ ## Wiring example
12
+
13
+ ```python
14
+ from openframe.protocol.http import bind_query, bind_command, install_error_handlers
15
+
16
+ router = APIRouter(prefix="/items")
17
+
18
+ bind_query(
19
+ router, "/{item_id}",
20
+ handler_dep=get_get_item_handler,
21
+ path_param=("item_id", str),
22
+ response_model=Item,
23
+ not_found_when=lambda item: item is None,
24
+ )
25
+
26
+ bind_command(
27
+ router, "", method="POST",
28
+ handler_dep=get_create_item_handler,
29
+ body_model=Item,
30
+ status_code=201,
31
+ response_model=Item,
32
+ )
33
+
34
+ install_error_handlers(app)
35
+ ```
36
+
37
+ ## Status
38
+
39
+ Experimental, M1 of the project's own build plan — proves the inbound
40
+ handler contract survives a real transport before anything else
41
+ (HTTP client, gRPC, sessions) is attempted.
@@ -0,0 +1,57 @@
1
+ """
2
+ openframe.protocol.http
3
+ ==========================
4
+ HTTP/ASGI binding, both directions (draft 7/8's redefinition):
5
+
6
+ - `bind_query`/`bind_command`/`install_error_handlers` (`server.py`,
7
+ needs the `[server]` extra, i.e. FastAPI) — wire a `QueryHandler`/
8
+ `CommandHandler`/`UseCase` to a route through the shared error mapper
9
+ and `RequestContext` builder in `openframe.protocol.base`.
10
+ - `HttpRemoteQueryClient`/`HttpRemoteCommandClient` (`client.py`, needs
11
+ the `[client]` extra, i.e. httpx) — call another service built on
12
+ this platform, the outbound counterpart.
13
+
14
+ Lazily imported (PEP 562, `__getattr__` below) rather than eagerly
15
+ importing both submodules here — `server.py` needs FastAPI and
16
+ `client.py` needs httpx, and eagerly importing both from this file
17
+ would mean installing *either* extra alone still fails at
18
+ `import openframe.protocol.http` with the *other* extra's missing
19
+ dependency. Found and fixed before this ever shipped: both submodules
20
+ were originally imported unconditionally here, silently defeating the
21
+ `[server]`/`[client]` extras split this package's own `pyproject.toml`
22
+ already promised.
23
+
24
+ .. stability: experimental
25
+ """
26
+ from __future__ import annotations
27
+
28
+ from typing import TYPE_CHECKING
29
+
30
+ if TYPE_CHECKING:
31
+ from openframe.protocol.http.server import bind_command, bind_query, create_app, install_error_handlers
32
+ from openframe.protocol.http.client import HttpRemoteCommandClient, HttpRemoteQueryClient, RequestSpec
33
+
34
+ __all__ = [
35
+ "bind_query",
36
+ "bind_command",
37
+ "install_error_handlers",
38
+ "create_app",
39
+ "HttpRemoteQueryClient",
40
+ "HttpRemoteCommandClient",
41
+ "RequestSpec",
42
+ ]
43
+
44
+ _FROM_SERVER = {"bind_query", "bind_command", "install_error_handlers", "create_app"}
45
+ _FROM_CLIENT = {"HttpRemoteQueryClient", "HttpRemoteCommandClient", "RequestSpec"}
46
+
47
+
48
+ def __getattr__(name: str):
49
+ if name in _FROM_SERVER:
50
+ from openframe.protocol.http import server
51
+
52
+ return getattr(server, name)
53
+ if name in _FROM_CLIENT:
54
+ from openframe.protocol.http import client
55
+
56
+ return getattr(client, name)
57
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,207 @@
1
+ """
2
+ openframe/protocol/http/client.py
3
+ ====================================
4
+ `HttpRemoteQueryClient`/`HttpRemoteCommandClient` — HTTP implementations
5
+ of `openframe.core.remote`'s `RemoteQueryClient`/`RemoteCommandClient`,
6
+ for calling another service built on this platform (M1b).
7
+
8
+ Lifecycle, per draft 8's D10: no `BasePort`/`PluginRegistry` involvement.
9
+ Each client owns (or borrows) a plain `httpx.AsyncClient` and exposes
10
+ `aclose()` for a caller's own lifespan to manage directly — the same
11
+ reasoning that kept `RemoteQueryClient`/`RemoteCommandClient` themselves
12
+ out of the `Capability` system in the first place applies to their
13
+ lifecycle too: there's no dynamic resolution happening, so there's
14
+ nothing for a registry to orchestrate.
15
+
16
+ Request construction deliberately mirrors `server.py`'s own
17
+ `build_input` philosophy rather than guessing how to serialise an
18
+ arbitrary input: a `build_request` hook returns exactly which path
19
+ params, query params, and JSON body a given call needs. Support exactly
20
+ the shapes `items-postgres`'s own routes need (path param only, query
21
+ params only, JSON body only) — not a fully generic REST client.
22
+
23
+ Dependency order:
24
+ protocol/http/client → protocol/base (errors, for the reverse mapping)
25
+ """
26
+ from __future__ import annotations
27
+
28
+ from dataclasses import dataclass, field
29
+ from typing import Any, Callable, Generic, TypeVar
30
+
31
+ import httpx
32
+ from opentelemetry import propagate
33
+
34
+ from openframe.core.inbound import RequestContext
35
+ from openframe.protocol.base.errors import ErrorCategory, ErrorEnvelope, categorize, raise_for_envelope
36
+
37
+ __all__ = ["RequestSpec", "HttpRemoteQueryClient", "HttpRemoteCommandClient"]
38
+
39
+ TInput = TypeVar("TInput")
40
+ TOutput = TypeVar("TOutput")
41
+
42
+ _STATUS_TO_CATEGORY: dict[int, ErrorCategory] = {
43
+ 404: ErrorCategory.NOT_FOUND,
44
+ 422: ErrorCategory.INVALID,
45
+ 504: ErrorCategory.TIMEOUT,
46
+ 503: ErrorCategory.UNAVAILABLE,
47
+ }
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class RequestSpec:
52
+ """
53
+ What one call actually sends — returned by a `build_request` hook,
54
+ given the handler's own input value.
55
+
56
+ Attributes:
57
+ path_params: Substituted into the client's `path` template via
58
+ `str.format(**path_params)`, e.g. `{"item_id": "abc"}`
59
+ for a path of `"/items/{item_id}"`.
60
+ query_params: Sent as the URL query string.
61
+ json_body: Sent as the request's JSON body. `None` means no
62
+ body at all (correct for GET, not just "empty dict").
63
+ """
64
+
65
+ path_params: dict[str, Any] = field(default_factory=dict)
66
+ query_params: dict[str, Any] = field(default_factory=dict)
67
+ json_body: Any = None
68
+
69
+
70
+ def _default_request_spec(value: Any) -> RequestSpec:
71
+ """
72
+ `build_request=None` default: if the input is falsy/None, send
73
+ nothing; otherwise send it as the JSON body. Covers the common
74
+ "one JSON-body input, no path or query params" case without
75
+ requiring every caller to write a trivial `build_request`.
76
+ """
77
+ if value is None:
78
+ return RequestSpec()
79
+ return RequestSpec(json_body=value)
80
+
81
+
82
+ class _HttpRemoteCallMixin:
83
+ """Shared machinery both client classes below use — not public itself."""
84
+
85
+ def __init__(
86
+ self,
87
+ *,
88
+ base_url: str | None = None,
89
+ path: str,
90
+ method: str,
91
+ client: httpx.AsyncClient | None = None,
92
+ build_request: Callable[[Any], RequestSpec] | None = None,
93
+ remote_name: str | None = None,
94
+ ) -> None:
95
+ if client is None and base_url is None:
96
+ raise ValueError("Either base_url or an existing client must be provided.")
97
+ self._client = client if client is not None else httpx.AsyncClient(base_url=base_url)
98
+ self._owns_client = client is None
99
+ self._path = path
100
+ self._method = method
101
+ self._build_request = build_request or _default_request_spec
102
+ self._remote_name = remote_name or f"http:{method} {path}"
103
+
104
+ async def aclose(self) -> None:
105
+ """Close the underlying httpx client — only if this instance created it."""
106
+ if self._owns_client:
107
+ await self._client.aclose()
108
+
109
+ async def _call(self, value: Any, context: RequestContext | None) -> Any:
110
+ spec = self._build_request(value)
111
+ url = self._path.format(**spec.path_params) if spec.path_params else self._path
112
+
113
+ headers: dict[str, str] = {}
114
+ propagate.inject(headers) # outgoing traceparent — joins the inbound trace, if any is active
115
+ if context is not None:
116
+ headers["X-Correlation-ID"] = context.correlation_id
117
+
118
+ try:
119
+ response = await self._client.request(
120
+ self._method, url, params=spec.query_params or None, json=spec.json_body, headers=headers
121
+ )
122
+ except httpx.TimeoutException as exc:
123
+ from openframe.core.exceptions import AdapterTimeoutError
124
+
125
+ raise AdapterTimeoutError(
126
+ f"Timed out calling {self._remote_name}", adapter=self._remote_name, operation="call", cause=exc
127
+ ) from exc
128
+ except httpx.ConnectError as exc:
129
+ from openframe.core.exceptions import AdapterConnectionError
130
+
131
+ raise AdapterConnectionError(
132
+ f"Could not connect for {self._remote_name}", adapter=self._remote_name, operation="call", cause=exc
133
+ ) from exc
134
+
135
+ if response.status_code < 400:
136
+ if response.status_code == 204 or not response.content:
137
+ return None
138
+ return response.json()
139
+
140
+ category = _STATUS_TO_CATEGORY.get(response.status_code, ErrorCategory.INTERNAL)
141
+ body = response.json() if response.content else {}
142
+ error = body.get("error", body)
143
+ envelope = ErrorEnvelope(
144
+ code=error.get("code", "unknown"),
145
+ message=error.get("message", f"{self._remote_name} failed with status {response.status_code}"),
146
+ retryable=error.get("retryable", False),
147
+ correlation_id=error.get("correlation_id", ""),
148
+ )
149
+ raise_for_envelope(category, envelope, remote_name=self._remote_name)
150
+
151
+
152
+ class HttpRemoteQueryClient(_HttpRemoteCallMixin, Generic[TInput, TOutput]):
153
+ """
154
+ `RemoteQueryClient` over HTTP. Satisfies
155
+ `openframe.core.remote.RemoteQueryClient` structurally.
156
+
157
+ Args: see `_HttpRemoteCallMixin.__init__` — `method` defaults
158
+ naturally to `"GET"` for queries (pass explicitly if a query uses a
159
+ different verb, though that would be unusual).
160
+ """
161
+
162
+ def __init__(
163
+ self,
164
+ *,
165
+ base_url: str | None = None,
166
+ path: str,
167
+ method: str = "GET",
168
+ client: httpx.AsyncClient | None = None,
169
+ build_request: Callable[[TInput], RequestSpec] | None = None,
170
+ remote_name: str | None = None,
171
+ ) -> None:
172
+ super().__init__(
173
+ base_url=base_url, path=path, method=method, client=client,
174
+ build_request=build_request, remote_name=remote_name,
175
+ )
176
+
177
+ async def execute(self, query: TInput, context: RequestContext | None = None) -> TOutput:
178
+ return await self._call(query, context)
179
+
180
+
181
+ class HttpRemoteCommandClient(_HttpRemoteCallMixin, Generic[TInput]):
182
+ """
183
+ `RemoteCommandClient` over HTTP. Satisfies
184
+ `openframe.core.remote.RemoteCommandClient` structurally.
185
+
186
+ `method` has no default here (unlike the query client) — a command
187
+ is meaningfully POST, PUT, PATCH, or DELETE, and none of those is
188
+ clearly "the" default the way GET is for queries.
189
+ """
190
+
191
+ def __init__(
192
+ self,
193
+ *,
194
+ base_url: str | None = None,
195
+ path: str,
196
+ method: str,
197
+ client: httpx.AsyncClient | None = None,
198
+ build_request: Callable[[TInput], RequestSpec] | None = None,
199
+ remote_name: str | None = None,
200
+ ) -> None:
201
+ super().__init__(
202
+ base_url=base_url, path=path, method=method, client=client,
203
+ build_request=build_request, remote_name=remote_name,
204
+ )
205
+
206
+ async def execute(self, command: TInput, context: RequestContext | None = None) -> None:
207
+ await self._call(command, context)