Skip to content

Commit 56c002c

Browse files
acn-ericlawclaude
andcommitted
feat: actuator endpoints - the engines' operational surface for Kubernetes
GET /info, /info/routes, /env, /health, /livenessprobe on the Event API host, mirroring the Java ActuatorServices shapes as ported to Rust. Health-check functions are normal registered functions speaking the engines' type=info / type=health contract, listed in mandatory/optional.health.dependencies and called through the event bus; /livenessprobe follows the most recent /health outcome (400 when down, engine parity). Version moved to version.py (single Python-side source). Co-Authored-By: Claude Code <noreply@anthropic.com>
1 parent 338cbfa commit 56c002c

9 files changed

Lines changed: 497 additions & 16 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,13 @@
22

33
## 0.1.0 (unreleased)
44

5+
- Actuator endpoints `/info`, `/info/routes`, `/env`, `/health` and `/livenessprobe` -
6+
the engines' operational surface, for Kubernetes probes and one-dashboard monitoring
7+
of polyglot installations. Health-check functions are normal registered functions
8+
speaking the engines' `type=info` / `type=health` interface contract, listed in
9+
`mandatory.health.dependencies` / `optional.health.dependencies` and called through
10+
the event bus. `/health` answers `UP` (200) / `DOWN` (400); `/livenessprobe` follows
11+
the most recent health outcome.
512
- Primitive in-process event bus - the single dispatch pipeline: one FIFO mailbox per
613
route consumed by `instances` worker tasks (the parameter is faithful); RPC deliveries
714
are ttl-bounded with a dead-work skip; drop-n-forget returns the 202-shape ack. The

‎README.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,37 @@ Log lines follow the Java reference engine's pattern for one-aggregation consist
127127
2026-08-22 10:15:30.123 INFO my_app:42 - Loaded PUBLIC hello.python, instances=10
128128
```
129129

130+
## Actuator endpoints
131+
132+
The host serves the engines' operational endpoints on the same port as `/api/event`, so
133+
Kubernetes probes and dashboards treat a Python app exactly like a Java or Rust engine app:
134+
135+
| Endpoint | Purpose |
136+
|----------|---------|
137+
| `GET /info` | app identity, runtime, origin id, start time, uptime |
138+
| `GET /info/routes` | registered routes split by visibility, with instance counts |
139+
| `GET /env` | selected environment variables and configuration parameters |
140+
| `GET /health` | dependency health checks — `UP` (HTTP 200) or `DOWN` (HTTP 400) |
141+
| `GET /livenessprobe` | `OK` while the last health outcome was good, else HTTP 400 |
142+
143+
Configuration keys carry the engines' names: `info.app.version`, `info.app.description`,
144+
`show.env.variables` and `show.application.properties` (opt-in lists — secrets are never
145+
dumped wholesale), and `mandatory.health.dependencies` / `optional.health.dependencies`
146+
(routes of health-check functions; optional ones never change the overall status). A
147+
health-check function is a normal registered function — usually private — speaking the
148+
engines' interface contract, called through the event bus:
149+
150+
```python
151+
@preload("demo.health", private=True)
152+
async def health(headers: dict[str, str], _body: Body) -> Body:
153+
if headers.get("type") == "info":
154+
return {"service": "demo.service", "href": "http://127.0.0.1"}
155+
return "demo.service is running fine" # a non-200 reply marks it down
156+
```
157+
158+
Kubernetes wiring: point `livenessProbe` at `/livenessprobe` and `readinessProbe` at
159+
`/health`.
160+
130161
## Wire compatibility
131162

132163
The codec implements the

‎examples/demo_app.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,5 +59,17 @@ async def chain(_headers: dict[str, str], body: Body):
5959
return reply.body
6060

6161

62+
@preload(route="demo.health", instances=5, private=True)
63+
async def health_check(headers: dict[str, str], _body: Body):
64+
"""Health check speaking the engines' interface contract (type=info / type=health).
65+
66+
Activate it for the /health actuator endpoint:
67+
mercury-serve examples/demo_app.py -Dmandatory.health.dependencies=demo.health
68+
"""
69+
if headers.get("type") == "info":
70+
return {"service": "demo.service", "href": "http://127.0.0.1"}
71+
return "demo.service is running fine"
72+
73+
6274
if __name__ == "__main__":
6375
platform.run()

‎src/mercury_composable/__init__.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,7 @@
1717
from .registry import FunctionRegistry, Handler, default_registry, preload
1818
from .server import EventApiServer, Platform, platform
1919
from .trace import TraceInfo, annotate_trace, get_trace, trace_context
20-
21-
__version__ = "0.1.0"
20+
from .version import __version__
2221

2322
__all__ = [
2423
"AppConfig",

‎src/mercury_composable/actuator.py‎

Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
"""
2+
Actuator endpoints for operations and Kubernetes deployment.
3+
4+
The same operational surface as the engines (the Java ``ActuatorServices``
5+
and its Rust port), so a polyglot installation monitors every app one way:
6+
7+
- ``GET /info`` - application identity (name, version, description), runtime,
8+
origin id, start/current time and uptime.
9+
- ``GET /info/routes`` - the local routing table split by visibility
10+
(``routing.public`` / ``routing.private``, route -> instance count).
11+
- ``GET /env`` - selected environment variables (``show.env.variables``) and
12+
selected configuration parameters (``show.application.properties``) -
13+
opt-in lists, so secrets are never dumped wholesale (engine parity).
14+
- ``GET /health`` - runs the health-check functions listed in
15+
``mandatory.health.dependencies`` / ``optional.health.dependencies``.
16+
All mandatory up -> ``UP`` (HTTP 200); any mandatory down -> ``DOWN``
17+
(HTTP 400, engine parity). The outcome feeds the liveness state.
18+
- ``GET /livenessprobe`` - ``OK`` (text) while the last health outcome is
19+
good, else HTTP 400 ``Unhealthy. Please check '/health' endpoint.``
20+
21+
A health-check function is a normal registered function (usually private)
22+
speaking the engines' interface contract - called through the same event bus
23+
that serves PostOffice, first with header ``type=info`` (an advisory identity
24+
map merged into its dependency entry), then with ``type=health`` (a status
25+
text or map; a non-200 reply marks the dependency down)::
26+
27+
@preload("demo.health", private=True)
28+
async def health(headers: dict[str, str], _body: Body) -> Body:
29+
if headers.get("type") == "info":
30+
return {"service": "demo.service", "href": "http://127.0.0.1"}
31+
return "demo.service is running fine"
32+
33+
Engine deltas (deliberate, wrapper-scale): no ``/info/lib`` (a wrapper app
34+
has no runtime dependency manifest - deferred on the Rust port too), no XML
35+
responses, and no 5-second info cache (dependencies are in-process
36+
functions, so the ``type=info`` lookup costs nothing).
37+
"""
38+
39+
from __future__ import annotations
40+
41+
import contextlib
42+
import os
43+
import platform as runtime_platform
44+
import re
45+
import time
46+
import uuid
47+
from datetime import datetime, timezone
48+
from typing import Any
49+
50+
from aiohttp import web
51+
52+
from .bus import DeliveryTimeout
53+
from .config import app_config
54+
from .envelope import iso_utc
55+
from .log import get_logger
56+
from .registry import FunctionRegistry
57+
from .version import __version__
58+
59+
log = get_logger("mercury.actuator")
60+
61+
INFO_TIMEOUT_MS = 3000 # engine value for the advisory type=info lookup
62+
HEALTH_TIMEOUT_MS = 10000 # engine value for the type=health probe
63+
UNHEALTHY = "Unhealthy. Please check '/health' endpoint."
64+
65+
_SPLIT = re.compile(r"[,\s]+")
66+
67+
_origin: str | None = None
68+
69+
70+
def app_origin() -> str:
71+
"""Unique instance id, minted once per process (the Java reference
72+
engine's format: UTC yyyyMMdd date prefix + 32-hex uuid)."""
73+
global _origin
74+
if _origin is None:
75+
_origin = time.strftime("%Y%m%d", time.gmtime()) + uuid.uuid4().hex
76+
return _origin
77+
78+
79+
def elapsed_time(milliseconds: float) -> str:
80+
"""Human-readable duration matching the engines' rendering
81+
(including their strict boundary behavior, kept verbatim for parity)."""
82+
one_second = 1000
83+
one_minute = 60 * one_second
84+
one_hour = 60 * one_minute
85+
one_day = 24 * one_hour
86+
remaining = int(milliseconds)
87+
parts: list[str] = []
88+
if remaining > one_day:
89+
days = remaining // one_day
90+
parts.append(f"{days} day" if days == 1 else f"{days} days")
91+
remaining -= days * one_day
92+
if remaining > one_hour:
93+
hours = remaining // one_hour
94+
parts.append(f"{hours} hour" if hours == 1 else f"{hours} hours")
95+
remaining -= hours * one_hour
96+
if remaining > one_minute:
97+
minutes = remaining // one_minute
98+
parts.append(f"{minutes} minute" if minutes == 1 else f"{minutes} minutes")
99+
remaining -= minutes * one_minute
100+
if remaining >= one_second:
101+
seconds = remaining // one_second
102+
parts.append(f"{seconds} second" if seconds == 1 else f"{seconds} seconds")
103+
return " ".join(parts) if parts else f"{remaining} ms"
104+
105+
106+
def _as_list(value: Any) -> list[str]:
107+
"""A comma/space-separated string (engine syntax) or a YAML list."""
108+
if isinstance(value, list):
109+
items = [str(item).strip() for item in value]
110+
else:
111+
items = _SPLIT.split(str(value or ""))
112+
return [item for item in items if item]
113+
114+
115+
class Actuator:
116+
"""HTTP handlers for the actuator endpoints (wired by EventApiServer)."""
117+
118+
def __init__(self, registry: FunctionRegistry):
119+
config = app_config()
120+
self.registry = registry
121+
self.start = datetime.now(timezone.utc)
122+
self.healthy = True # liveness follows the most recent /health outcome
123+
self.app_name = config.get_property("application.name", "application") or "application"
124+
self.app_version = config.get_property("info.app.version", __version__) or __version__
125+
self.description = (config.get_property("info.app.description", self.app_name)
126+
or self.app_name)
127+
self.required = _as_list(config.get("mandatory.health.dependencies"))
128+
self.optional = _as_list(config.get("optional.health.dependencies"))
129+
if self.required:
130+
log.info("Mandatory service dependencies - %s", self.required)
131+
if self.optional:
132+
log.info("Optional services dependencies - %s", self.optional)
133+
134+
def _app_block(self) -> dict[str, Any]:
135+
return {"name": self.app_name, "version": self.app_version,
136+
"description": self.description}
137+
138+
# aiohttp handlers must be coroutines - async is the framework contract
139+
# even when a handler has nothing to await
140+
async def handle_info(self, _request: web.Request) -> web.Response:
141+
now = datetime.now(timezone.utc)
142+
return web.json_response({
143+
"app": self._app_block(),
144+
"runtime": {
145+
"language": "python",
146+
"python": runtime_platform.python_version(),
147+
"mercury_composable": __version__,
148+
},
149+
"origin": app_origin(),
150+
"time": {"start": iso_utc(self.start), "current": iso_utc(now)},
151+
"up_time": elapsed_time((now - self.start).total_seconds() * 1000),
152+
})
153+
154+
async def handle_routes(self, _request: web.Request) -> web.Response:
155+
public: dict[str, int] = {}
156+
private: dict[str, int] = {}
157+
for route, service in sorted(self.registry.routes().items()):
158+
target = private if service.private else public
159+
target[route] = service.instances
160+
return web.json_response({
161+
"app": self._app_block(),
162+
"routing": {"public": public, "private": private},
163+
})
164+
165+
async def handle_env(self, _request: web.Request) -> web.Response:
166+
config = app_config()
167+
environment = {name: os.environ.get(name, "")
168+
for name in _as_list(config.get("show.env.variables"))}
169+
properties = {name: config.get_property(name) or ""
170+
for name in _as_list(config.get("show.application.properties"))}
171+
return web.json_response({
172+
"app": self._app_block(),
173+
"env": {"environment": environment, "properties": properties},
174+
})
175+
176+
async def handle_health(self, _request: web.Request) -> web.Response:
177+
dependency: list[dict[str, Any]] = []
178+
# optional services never affect the overall status (engine semantics)
179+
await self._check_services(self.optional, required=False, dependency=dependency)
180+
up = await self._check_services(self.required, required=True, dependency=dependency)
181+
self.healthy = up
182+
result: dict[str, Any] = {}
183+
if not dependency:
184+
result["message"] = ("Did you forget to define mandatory.health.dependencies "
185+
"or optional.health.dependencies")
186+
result["dependency"] = dependency
187+
result["status"] = "UP" if up else "DOWN"
188+
result["origin"] = app_origin()
189+
result["name"] = self.app_name
190+
return web.json_response(result, status=200 if up else 400)
191+
192+
async def handle_livenessprobe(self, _request: web.Request) -> web.Response:
193+
if self.healthy:
194+
return web.Response(text="OK")
195+
return web.Response(status=400, text=UNHEALTHY)
196+
197+
async def _check_services(self, services: list[str], *, required: bool,
198+
dependency: list[dict[str, Any]]) -> bool:
199+
all_up = True
200+
for route in services:
201+
entry: dict[str, Any] = {"route": route, "required": required}
202+
dependency.append(entry)
203+
service = self.registry.get(route)
204+
if service is None:
205+
all_up = False
206+
entry["status_code"] = 404
207+
entry["message"] = f"Please check - Route {route} not found"
208+
continue
209+
bus = self.registry.bus
210+
# info is advisory - merge whatever the service reports about
211+
# itself; the health probe below decides the status
212+
with contextlib.suppress(DeliveryTimeout):
213+
info = await bus.deliver(service, {"type": "info"}, None, INFO_TIMEOUT_MS)
214+
if isinstance(info.body, dict):
215+
entry.update(info.body)
216+
try:
217+
reply = await bus.deliver(service, {"type": "health"}, None, HEALTH_TIMEOUT_MS)
218+
entry["status_code"] = reply.get_status()
219+
if isinstance(reply.body, (str, dict)):
220+
entry["message"] = reply.body
221+
if reply.has_error():
222+
all_up = False
223+
except DeliveryTimeout as e:
224+
all_up = False
225+
entry["status_code"] = 408
226+
entry["message"] = f"Please check - {e}"
227+
return all_up

‎src/mercury_composable/server.py‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,16 @@
1616
guard) and transported ``my_*`` keys are removed from the handler's header
1717
view; the ``my_cid`` tag is injected as the read-only ``my_correlation_id``
1818
header, per the wire-format contract.
19+
- The host also serves the engines' actuator endpoints (``/info``,
20+
``/info/routes``, ``/env``, ``/health``, ``/livenessprobe``) for
21+
operations and Kubernetes probes - see :mod:`mercury_composable.actuator`.
1922
"""
2023

2124
from __future__ import annotations
2225

2326
from aiohttp import web
2427

28+
from .actuator import Actuator
2529
from .bus import DeliveryTimeout
2630
from .config import app_config
2731
from .envelope import EventEnvelope
@@ -57,6 +61,7 @@ class EventApiServer:
5761

5862
def __init__(self, registry: FunctionRegistry | None = None):
5963
self.registry = registry or default_registry
64+
self.actuator = Actuator(self.registry)
6065

6166
async def handle_event(self, request: web.Request) -> web.Response:
6267
raw = await request.read()
@@ -95,16 +100,14 @@ async def handle_event(self, request: web.Request) -> web.Response:
95100
event.to, reply.get_status(), reply.exec_time, event.trace_id)
96101
return web.Response(status=200, body=reply.to_bytes(), content_type=OCTET_STREAM)
97102

98-
# aiohttp handlers must be coroutines - async is the framework contract
99-
# even though this one has nothing to await
100-
@staticmethod
101-
async def handle_health(_request: web.Request) -> web.Response:
102-
return web.Response(text="OK")
103-
104103
def create_app(self) -> web.Application:
105104
app = web.Application(client_max_size=16 * 1024 * 1024)
106105
app.router.add_post("/api/event", self.handle_event)
107-
app.router.add_get("/health", self.handle_health)
106+
app.router.add_get("/info", self.actuator.handle_info)
107+
app.router.add_get("/info/routes", self.actuator.handle_routes)
108+
app.router.add_get("/env", self.actuator.handle_env)
109+
app.router.add_get("/health", self.actuator.handle_health)
110+
app.router.add_get("/livenessprobe", self.actuator.handle_livenessprobe)
108111
return app
109112

110113

‎src/mercury_composable/version.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"""Package version - the single Python-side source (pyproject.toml mirrors it)."""
2+
3+
__version__ = "0.1.0"

0 commit comments

Comments
 (0)