Skip to content

Commit d7bd10a

Browse files
committed
Harden Flask health endpoint registration
1 parent 81b0bd5 commit d7bd10a

2 files changed

Lines changed: 48 additions & 4 deletions

File tree

src/quant_platform_kit/common/health.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -180,13 +180,26 @@ def read(self) -> Heartbeat | None:
180180

181181
def _register_flask(self) -> None:
182182
from flask import jsonify
183-
monitor = self
184183

185-
@self._app.route("/health", methods=["GET"])
186-
@self._app.route("/healthz", methods=["GET"])
187-
def health():
184+
def qpk_health():
188185
return jsonify({"status": "ok", "timestamp": datetime.now(timezone.utc).isoformat()})
189186

187+
existing_rules = {getattr(rule, "rule", "") for rule in self._app.url_map.iter_rules()}
188+
if "/health" not in existing_rules:
189+
self._app.add_url_rule(
190+
"/health",
191+
endpoint="qpk_health",
192+
view_func=qpk_health,
193+
methods=["GET"],
194+
)
195+
if "/healthz" not in existing_rules:
196+
self._app.add_url_rule(
197+
"/healthz",
198+
endpoint="qpk_healthz",
199+
view_func=qpk_health,
200+
methods=["GET"],
201+
)
202+
190203
def _start_http_server(self) -> None:
191204
import http.server
192205
port = self._http_port

tests/test_common_health.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from __future__ import annotations
2+
3+
from flask import Flask
4+
5+
from quant_platform_kit.common.health import register_health_endpoint
6+
7+
8+
def test_register_health_endpoint_uses_non_colliding_endpoint_names():
9+
app = Flask(__name__)
10+
register_health_endpoint(app)
11+
12+
@app.get("/")
13+
def health():
14+
return "service-info"
15+
16+
assert app.test_client().get("/").text == "service-info"
17+
assert app.test_client().get("/health").status_code == 200
18+
assert app.test_client().get("/healthz").status_code == 200
19+
20+
21+
def test_register_health_endpoint_preserves_existing_health_route():
22+
app = Flask(__name__)
23+
24+
@app.get("/health")
25+
def platform_health():
26+
return "platform-ok"
27+
28+
register_health_endpoint(app)
29+
30+
assert app.test_client().get("/health").text == "platform-ok"
31+
assert app.test_client().get("/healthz").status_code == 200

0 commit comments

Comments
 (0)