hexastack-fastapi 0.8.0__tar.gz → 0.10.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 (35) hide show
  1. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/PKG-INFO +1 -1
  2. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/pyproject.toml +2 -2
  3. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/pyproject.toml.orig +2 -2
  4. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/adapters/openziti.py +7 -9
  5. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/adapters/ratelimit.py +15 -9
  6. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/adapters/sse.py +1 -1
  7. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/infra/decorators.py +2 -3
  8. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/testing/recorder.py +7 -8
  9. hexastack_fastapi-0.10.0/src/hexastack_fastapi/testing/server.py +195 -0
  10. hexastack_fastapi-0.8.0/src/hexastack_fastapi/testing/server.py +0 -120
  11. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/README.md +0 -0
  12. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/__init__.py +0 -0
  13. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/adapters/__init__.py +0 -0
  14. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/adapters/db_session.py +0 -0
  15. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/adapters/dependencies.py +0 -0
  16. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/adapters/docs.py +0 -0
  17. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/adapters/health.py +0 -0
  18. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/adapters/metrics.py +0 -0
  19. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/adapters/routing.py +0 -0
  20. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/adapters/websockets.py +0 -0
  21. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/domain/__init__.py +0 -0
  22. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/domain/config.py +0 -0
  23. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/infra/__init__.py +0 -0
  24. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/infra/app.py +0 -0
  25. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/infra/autodiscovery.py +0 -0
  26. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/infra/bootstrap.py +0 -0
  27. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/infra/config.py +0 -0
  28. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/infra/exception_handlers.py +0 -0
  29. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/infra/middleware/__init__.py +0 -0
  30. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/infra/middleware/correlation.py +0 -0
  31. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/infra/middleware/logging.py +0 -0
  32. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/infra/middleware/metrics.py +0 -0
  33. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/py.typed +0 -0
  34. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/testing/__init__.py +0 -0
  35. {hexastack_fastapi-0.8.0 → hexastack_fastapi-0.10.0}/src/hexastack_fastapi/testing/cursor.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hexastack-fastapi
3
- Version: 0.8.0
3
+ Version: 0.10.0
4
4
  Summary: FastAPI presentation adapter for Hexastack
5
5
  Author: Richard West
6
6
  Author-email: Richard West <dopplereffect.us@gmail.com>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "hexastack-fastapi"
3
- version = "0.8.0"
3
+ version = "0.10.0"
4
4
  description = "FastAPI presentation adapter for Hexastack"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -32,7 +32,7 @@ ziti = ["openziti>=1.0.0"]
32
32
  fastapi = "hexastack_fastapi.infra.bootstrap:FastApiBootstrapper"
33
33
 
34
34
  [build-system]
35
- requires = ["uv_build>=0.12.3,<0.13.0"]
35
+ requires = ["uv_build>=0.12.3,<0.14.0"]
36
36
  build-backend = "uv_build"
37
37
 
38
38
  [tool.uv.sources.hexastack-auth]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "hexastack-fastapi"
3
- version = "0.8.0"
3
+ version = "0.10.0"
4
4
  description = "FastAPI presentation adapter for Hexastack"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -37,7 +37,7 @@ ziti = [
37
37
  fastapi = "hexastack_fastapi.infra.bootstrap:FastApiBootstrapper"
38
38
 
39
39
  [build-system]
40
- requires = ["uv_build>=0.12.3,<0.13.0"]
40
+ requires = ["uv_build>=0.12.3,<0.14.0"]
41
41
  build-backend = "uv_build"
42
42
 
43
43
  [tool.uv.sources]
@@ -16,6 +16,7 @@ from pathlib import Path
16
16
  from typing import Any
17
17
 
18
18
  from hexastack_core.domain.exceptions import MissingDependencyError
19
+ from hexastack_core.utils import require_dependency
19
20
 
20
21
  __all__ = [
21
22
  "openziti_bind",
@@ -90,15 +91,12 @@ class OpenZitiASGIAdapter:
90
91
  Raises:
91
92
  MissingDependencyError: If openziti is not installed.
92
93
  """
93
- try:
94
- import openziti
95
-
96
- return openziti
97
- except ImportError as exc:
98
- raise MissingDependencyError(
99
- "openziti is required for OpenZiti zero-trust networking. "
100
- "Install with 'pip install hexastack-fastapi[ziti]' or 'pip install openziti'."
101
- ) from exc
94
+ return require_dependency(
95
+ "openziti",
96
+ extra="ziti",
97
+ package="hexastack-fastapi",
98
+ feature_name="OpenZiti Zero-Trust Network",
99
+ )
102
100
 
103
101
  def get_bindings(
104
102
  self, host: str | None = None, port: int | None = None
@@ -5,8 +5,8 @@ from typing import Any, cast
5
5
 
6
6
  from fastapi import HTTPException, Request, status
7
7
 
8
- from hexastack_core.domain.exceptions import MissingDependencyError
9
8
  from hexastack_core.ports.ratelimit import RateLimiterPort
9
+ from hexastack_core.utils import require_dependency
10
10
  from hexastack_core.utils.context import get_user_context
11
11
 
12
12
 
@@ -77,14 +77,20 @@ class SlowapiRateLimiterAdapter(RateLimiterPort):
77
77
  Raises:
78
78
  MissingDependencyError: If slowapi or limits is not installed.
79
79
  """
80
- try:
81
- from limits.storage import storage_from_string
82
- from slowapi import Limiter
83
- except ImportError as e:
84
- raise MissingDependencyError(
85
- "slowapi and limits are required for SlowapiRateLimiterAdapter. "
86
- "Install with 'pip install hexastack-fastapi[ratelimit]'."
87
- ) from e
80
+ limits_storage = require_dependency(
81
+ "limits.storage",
82
+ extra="ratelimit",
83
+ package="hexastack-fastapi",
84
+ feature_name="Slowapi Rate Limiter Storage",
85
+ )
86
+ slowapi = require_dependency(
87
+ "slowapi",
88
+ extra="ratelimit",
89
+ package="hexastack-fastapi",
90
+ feature_name="Slowapi Rate Limiter",
91
+ )
92
+ storage_from_string = limits_storage.storage_from_string
93
+ Limiter = slowapi.Limiter
88
94
 
89
95
  self._key_func = key_func or get_user_or_ip_key
90
96
  self._default_limits: list[Any] = list(default_limits or ["100/minute"])
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
+ import json
6
7
  from collections.abc import AsyncIterable, AsyncIterator
7
8
  from dataclasses import dataclass
8
9
  from typing import Any
@@ -68,7 +69,6 @@ def _encode_sse_item(item: Any) -> bytes:
68
69
  return item
69
70
  if isinstance(item, str):
70
71
  return ServerSentEvent(data=item).encode()
71
- import json
72
72
 
73
73
  return ServerSentEvent(data=json.dumps(item)).encode()
74
74
 
@@ -1,6 +1,8 @@
1
+ import inspect
1
2
  from collections.abc import Callable
2
3
  from dataclasses import dataclass
3
4
  from enum import Enum
5
+ from functools import wraps
4
6
  from typing import Any, Literal, TypeVar
5
7
 
6
8
  from hexastack_core.domain import Command, Query
@@ -157,9 +159,6 @@ def feature_flag_route(
157
159
  Returns:
158
160
  Decorator wrapping the endpoint callable.
159
161
  """
160
- import inspect
161
- from functools import wraps
162
-
163
162
  from fastapi import HTTPException
164
163
 
165
164
  from hexastack_core.adapters.feature_flags.config import ConfigFeatureFlagAdapter
@@ -7,7 +7,7 @@ import time
7
7
  from pathlib import Path
8
8
  from typing import Any
9
9
 
10
- from hexastack_core.domain.exceptions import MissingDependencyError
10
+ from hexastack_core.utils import require_dependency
11
11
  from hexastack_core.utils.fs import atomic_write_text
12
12
  from hexastack_fastapi.testing.cursor import VIRTUAL_CURSOR_SCRIPT
13
13
 
@@ -71,13 +71,12 @@ class DemoNarrator:
71
71
  Raises:
72
72
  MissingDependencyError: If `playwright` is not installed.
73
73
  """
74
- try:
75
- import playwright # noqa: F401
76
- except ImportError as e:
77
- raise MissingDependencyError(
78
- "Playwright is required to record feature demos. "
79
- "Install with 'pip install hexastack-fastapi[testing]' or 'pip install playwright'."
80
- ) from e
74
+ require_dependency(
75
+ "playwright",
76
+ extra="testing",
77
+ package="hexastack-fastapi",
78
+ feature_name="Feature Demo Recording",
79
+ )
81
80
 
82
81
  self.page = page
83
82
  self.output_name = output_name
@@ -0,0 +1,195 @@
1
+ """Ephemeral background server utility for Playwright and integration testing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import http.client
6
+ import os
7
+ import socket
8
+ import subprocess
9
+ import sys
10
+ import tempfile
11
+ import time
12
+ from collections.abc import Generator
13
+ from contextlib import contextmanager, suppress
14
+ from typing import IO, Any
15
+
16
+
17
+ def find_free_port() -> int:
18
+ """Find a dynamically available free TCP port on localhost.
19
+
20
+ Returns:
21
+ An available integer TCP port number on 127.0.0.1.
22
+
23
+ Notes/Architectural Intent:
24
+ Binds to port 0 to allow OS kernel assignment, immediately closing socket
25
+ to return an ephemeral port for test server isolation.
26
+ """
27
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
28
+ s.bind(("127.0.0.1", 0))
29
+ return int(s.getsockname()[1])
30
+
31
+
32
+ class EphemeralServer:
33
+ """Manages lifecycle of an ephemeral Uvicorn web server running in background."""
34
+
35
+ def __init__(
36
+ self,
37
+ app_factory_code: str,
38
+ port: int | None = None,
39
+ env: dict[str, str] | None = None,
40
+ ) -> None:
41
+ """Initialize ephemeral server with Python factory script code.
42
+
43
+ Args:
44
+ app_factory_code: Python code string that creates and runs the ASGI app.
45
+ port: Optional fixed port. If omitted, finds an ephemeral free port.
46
+ env: Optional environment variables dictionary for subprocess.
47
+
48
+ Notes/Architectural Intent:
49
+ Configures process environment and binds to an ephemeral port to provide
50
+ isolated background server processes for integration and E2E browser tests.
51
+ """
52
+ self.port = port or find_free_port()
53
+ self.app_factory_code = app_factory_code
54
+ self.env = env
55
+ self.proc: subprocess.Popen[Any] | None = None
56
+ self._log_file: IO[str] | None = None
57
+ self.base_url = f"http://127.0.0.1:{self.port}"
58
+
59
+ def start(self, ready_path: str = "/", timeout: float = 30.0) -> str:
60
+ """Start the server process and poll until healthy.
61
+
62
+ Args:
63
+ ready_path: Relative URL path to poll for HTTP readiness.
64
+ timeout: Maximum seconds to wait before failing (default: 30.0s).
65
+
66
+ Returns:
67
+ The base URL of the running server.
68
+
69
+ Raises:
70
+ RuntimeError: If server exits prematurely or fails to start within timeout.
71
+
72
+ Notes/Architectural Intent:
73
+ Spawns background Uvicorn/ASGI process with captured stdout and stderr in a
74
+ temporary file. Continuously monitors process health and readiness endpoint,
75
+ failing immediately with complete diagnostic logs if the subprocess crashes.
76
+ """
77
+ cmd = [
78
+ sys.executable,
79
+ "-c",
80
+ self.app_factory_code.format(port=self.port),
81
+ ]
82
+ proc_env = dict(os.environ)
83
+ if self.env:
84
+ proc_env.update(self.env)
85
+
86
+ self._log_file = tempfile.TemporaryFile(mode="w+t", encoding="utf-8") # noqa: SIM115
87
+ self.proc = subprocess.Popen(
88
+ cmd,
89
+ stdout=self._log_file,
90
+ stderr=subprocess.STDOUT,
91
+ env=proc_env,
92
+ )
93
+
94
+ start_time = time.time()
95
+ while time.time() - start_time < timeout:
96
+ if self.proc.poll() is not None:
97
+ returncode = self.proc.returncode
98
+ log_output = self._read_logs()
99
+ self.stop()
100
+ raise RuntimeError(
101
+ f"Ephemeral server failed to start at {self.base_url} "
102
+ f"(process exited prematurely with code {returncode}):\n{log_output}"
103
+ )
104
+
105
+ try:
106
+ conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=1.0)
107
+ conn.request("GET", ready_path)
108
+ resp = conn.getresponse()
109
+ if resp.status in (200, 301, 302, 307, 308, 404): # Responding is ready
110
+ conn.close()
111
+ return self.base_url
112
+ conn.close()
113
+ except Exception:
114
+ time.sleep(0.25)
115
+
116
+ log_output = self._read_logs()
117
+ self.stop()
118
+ raise RuntimeError(
119
+ f"Ephemeral server failed to start at {self.base_url} within {timeout}s:\n{log_output}"
120
+ )
121
+
122
+ def _read_logs(self) -> str:
123
+ """Read captured stdout/stderr logs from the temporary log file.
124
+
125
+ Returns:
126
+ String contents of captured subprocess logs.
127
+
128
+ Notes/Architectural Intent:
129
+ Flushes and rewinds the temporary log file to safely inspect output without blocking.
130
+ """
131
+ if self._log_file is not None:
132
+ with suppress(Exception):
133
+ self._log_file.flush()
134
+ self._log_file.seek(0)
135
+ return self._log_file.read().strip()
136
+ return ""
137
+
138
+ def stop(self) -> None:
139
+ """Stop and terminate the background server process.
140
+
141
+ Notes/Architectural Intent:
142
+ Sends SIGTERM, waits gracefully, and falls back to SIGKILL to guarantee
143
+ no orphan subprocesses linger in testing environments. Cleans up log file.
144
+ """
145
+ if self.proc is not None:
146
+ self.proc.terminate()
147
+ try:
148
+ self.proc.wait(timeout=3.0)
149
+ except subprocess.TimeoutExpired:
150
+ self.proc.kill()
151
+ self.proc = None
152
+
153
+ if self._log_file is not None:
154
+ with suppress(Exception):
155
+ self._log_file.close()
156
+ self._log_file = None
157
+
158
+
159
+ @contextmanager
160
+ def ephemeral_server(
161
+ app_factory_code: str,
162
+ ready_path: str = "/",
163
+ env: dict[str, str] | None = None,
164
+ timeout: float = 30.0,
165
+ ) -> Generator[str]:
166
+ """Context manager launching an ephemeral server on a free port.
167
+
168
+ Args:
169
+ app_factory_code: Python code string creating and launching the ASGI server.
170
+ ready_path: Relative URL path to poll for HTTP readiness.
171
+ env: Optional environment variables dictionary for subprocess.
172
+ timeout: Maximum seconds to wait for server readiness (default: 30.0s).
173
+
174
+ Yields:
175
+ The base URL of the running server.
176
+
177
+ Raises:
178
+ RuntimeError: If server fails to start within timeout.
179
+
180
+ Notes/Architectural Intent:
181
+ Wraps EphemeralServer in a context manager to ensure guaranteed process shutdown.
182
+ """
183
+ server = EphemeralServer(app_factory_code, env=env)
184
+ try:
185
+ url = server.start(ready_path=ready_path, timeout=timeout)
186
+ yield url
187
+ finally:
188
+ server.stop()
189
+
190
+
191
+ __all__ = [
192
+ "ephemeral_server",
193
+ "EphemeralServer",
194
+ "find_free_port",
195
+ ]
@@ -1,120 +0,0 @@
1
- """Ephemeral background server utility for Playwright and integration testing."""
2
-
3
- from __future__ import annotations
4
-
5
- import http.client
6
- import os
7
- import socket
8
- import subprocess
9
- import sys
10
- import time
11
- from collections.abc import Generator
12
- from contextlib import contextmanager
13
- from typing import Any
14
-
15
-
16
- def find_free_port() -> int:
17
- """Find a dynamically available free TCP port on localhost."""
18
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
19
- s.bind(("127.0.0.1", 0))
20
- return int(s.getsockname()[1])
21
-
22
-
23
- class EphemeralServer:
24
- """Manages lifecycle of an ephemeral Uvicorn web server running in background."""
25
-
26
- def __init__(
27
- self,
28
- app_factory_code: str,
29
- port: int | None = None,
30
- env: dict[str, str] | None = None,
31
- ) -> None:
32
- """Initialize ephemeral server with Python factory script code.
33
-
34
- Args:
35
- app_factory_code: Python code string that creates and runs the ASGI app.
36
- port: Optional fixed port. If omitted, finds an ephemeral free port.
37
- env: Optional environment variables dictionary for subprocess.
38
- """
39
- self.port = port or find_free_port()
40
- self.app_factory_code = app_factory_code
41
- self.env = env
42
- self.proc: subprocess.Popen[Any] | None = None
43
- self.base_url = f"http://127.0.0.1:{self.port}"
44
-
45
- def start(self, ready_path: str = "/", timeout: float = 10.0) -> str:
46
- """Start the server process and poll until healthy.
47
-
48
- Args:
49
- ready_path: Relative URL path to poll for HTTP 200 readiness.
50
- timeout: Maximum seconds to wait before failing.
51
-
52
- Returns:
53
- The base URL of the running server.
54
-
55
- Raises:
56
- RuntimeError: If server fails to start within timeout.
57
- """
58
- cmd = [
59
- sys.executable,
60
- "-c",
61
- self.app_factory_code.format(port=self.port),
62
- ]
63
- proc_env = dict(os.environ)
64
- if self.env:
65
- proc_env.update(self.env)
66
-
67
- self.proc = subprocess.Popen(
68
- cmd,
69
- stdout=subprocess.DEVNULL,
70
- stderr=subprocess.DEVNULL,
71
- env=proc_env,
72
- )
73
-
74
- start_time = time.time()
75
- while time.time() - start_time < timeout:
76
- try:
77
- conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=1.0)
78
- conn.request("GET", ready_path)
79
- resp = conn.getresponse()
80
- if resp.status in (200, 404): # Responding is ready
81
- conn.close()
82
- return self.base_url
83
- conn.close()
84
- except Exception:
85
- time.sleep(0.25)
86
-
87
- self.stop()
88
- raise RuntimeError(f"Ephemeral server failed to start at {self.base_url}")
89
-
90
- def stop(self) -> None:
91
- """Stop and terminate the background server process."""
92
- if self.proc is not None:
93
- self.proc.terminate()
94
- try:
95
- self.proc.wait(timeout=3.0)
96
- except subprocess.TimeoutExpired:
97
- self.proc.kill()
98
- self.proc = None
99
-
100
-
101
- @contextmanager
102
- def ephemeral_server(
103
- app_factory_code: str,
104
- ready_path: str = "/",
105
- env: dict[str, str] | None = None,
106
- ) -> Generator[str]:
107
- """Context manager launching an ephemeral server on a free port."""
108
- server = EphemeralServer(app_factory_code, env=env)
109
- try:
110
- url = server.start(ready_path=ready_path)
111
- yield url
112
- finally:
113
- server.stop()
114
-
115
-
116
- __all__ = [
117
- "ephemeral_server",
118
- "EphemeralServer",
119
- "find_free_port",
120
- ]