Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
965b24a183 | ||
|
|
9ea8667264 | ||
|
|
9cdf9110fb | ||
|
|
360425d3ca | ||
|
|
324e1cab4e | ||
|
|
16e54b63f2 | ||
|
|
610b659fd4 | ||
|
|
a87e9d2db4 | ||
|
|
5a3f0128c4 | ||
|
|
1e17771840 | ||
|
|
286680c053 |
No files matched your search
@@ -28,6 +28,11 @@ Gitea connection directly, request
|
||||
`user`, `repos`, `issues`, and `pull_requests`. Never commit the token or place
|
||||
it in a tracked configuration file.
|
||||
|
||||
For service monitoring, GET `/healthz` is a liveness check that confirms the
|
||||
API process is running and does not contact Gitea. GET `/readyz` is the
|
||||
readiness check: it validates the configured Gitea credentials and returns
|
||||
HTTP 503 with an error when Gitea is unavailable or authentication fails.
|
||||
|
||||
Run the test suite with:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -102,6 +102,7 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
<details class="panel" data-panel-key="gitea-events" open>
|
||||
<summary><h2>Gitea event stream</h2></summary>
|
||||
<div id="gitea-events" class="muted" aria-live="polite">Loading…</div>
|
||||
<div id="gitea-events-status" class="small" aria-live="polite">Waiting for activity…</div>
|
||||
</details>
|
||||
<details class="panel" data-panel-key="widgets" open>
|
||||
<summary><h2>Live Widgets</h2></summary>
|
||||
@@ -245,11 +246,17 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
).join('') : '<div class="muted">No recent Gitea activity.</div>';
|
||||
}
|
||||
|
||||
function setEventStreamStatus(message) {
|
||||
qs('#gitea-events-status').textContent = message;
|
||||
}
|
||||
|
||||
async function loadEventStream() {
|
||||
setEventStreamStatus('Updating…');
|
||||
try {
|
||||
const res = await fetch('/api/v1/events', { headers: { Accept: 'application/json' } });
|
||||
if (!res.ok) throw new Error('HTTP ' + res.status);
|
||||
paintEventStream(await res.json());
|
||||
setEventStreamStatus('Updated ' + fmt(new Date()));
|
||||
} catch (e) {
|
||||
qs('#gitea-events').innerHTML = '<div class="muted">Event stream unavailable.</div>';
|
||||
}
|
||||
|
||||
+38
-6
@@ -1,3 +1,6 @@
|
||||
import asyncio
|
||||
import math
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
@@ -9,6 +12,7 @@ from src.suggestion_engine import compute
|
||||
from src.views import router as frontend_router
|
||||
|
||||
app = FastAPI(title="Stackchain Dashboard")
|
||||
CONTEXT_TIMEOUT_SECONDS = 5.0
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
@@ -27,14 +31,40 @@ def health() -> dict[str, str]:
|
||||
return {"status": "ok", "service": "stackchain-dashboard"}
|
||||
|
||||
|
||||
@app.get("/readyz")
|
||||
async def readiness():
|
||||
"""Return readiness after verifying the configured Gitea connection."""
|
||||
try:
|
||||
user = await current_user()
|
||||
except Exception as exc:
|
||||
return JSONResponse(
|
||||
{
|
||||
"status": "not_ready",
|
||||
"service": "stackchain-dashboard",
|
||||
"error": str(exc),
|
||||
},
|
||||
status_code=503,
|
||||
)
|
||||
return {
|
||||
"status": "ready",
|
||||
"service": "stackchain-dashboard",
|
||||
"gitea_user": user["login"],
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/v1/context")
|
||||
async def context() -> JSONResponse:
|
||||
try:
|
||||
user_data = await current_user()
|
||||
repo_data = await repos()
|
||||
issues_data = await issues()
|
||||
prs_data = await pull_requests()
|
||||
user_data, repo_data, issues_data, prs_data = await asyncio.wait_for(
|
||||
asyncio.gather(current_user(), repos(), issues(), pull_requests()),
|
||||
timeout=CONTEXT_TIMEOUT_SECONDS,
|
||||
)
|
||||
except Exception as e:
|
||||
error_message = (
|
||||
f"Gitea context request timed out after {CONTEXT_TIMEOUT_SECONDS:g}s"
|
||||
if isinstance(e, TimeoutError)
|
||||
else str(e)
|
||||
)
|
||||
return JSONResponse({
|
||||
"user": {"id": None, "login": "timmy", "full_name": "Timmy Jr", "email": ""},
|
||||
"repos": [],
|
||||
@@ -45,8 +75,10 @@ async def context() -> JSONResponse:
|
||||
{"panel": "auth", "action": "connect", "target": "stackchain-dashboard backend", "priority": "high"},
|
||||
{"panel": "gitea", "action": "set GITEA_URL + GITEA_TOKEN", "target": "/root/stackchain-dashboard/.env or systemd env", "priority": "high"},
|
||||
],
|
||||
"error": str(e),
|
||||
})
|
||||
"error": error_message,
|
||||
}, headers={
|
||||
"Retry-After": str(max(1, math.ceil(CONTEXT_TIMEOUT_SECONDS)))
|
||||
} if isinstance(e, TimeoutError) else None)
|
||||
user_model = User(id=user_data["id"], login=user_data["login"], full_name=user_data.get("full_name", ""), email=user_data.get("email", ""))
|
||||
repo_models = [
|
||||
Repo(id=r["id"], name=r["name"], full_name=r["full_name"], description=r.get("description", ""), url=r["html_url"], updated_at=r.get("updated_at", ""))
|
||||
|
||||
@@ -147,6 +147,8 @@ class GiteaClient:
|
||||
return json.loads(raw) if raw else None
|
||||
except error.HTTPError as exc:
|
||||
detail = exc.read().decode(errors="replace")
|
||||
if exc.code == 401:
|
||||
detail += " (authentication rejected; refresh the cron GITEA_TOKEN)"
|
||||
raise RuntimeError(f"Gitea {method} {path} failed: HTTP {exc.code}: {detail}") from exc
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from src import main
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_context_returns_fallback_when_gitea_exceeds_deadline(monkeypatch):
|
||||
cancelled = asyncio.Event()
|
||||
|
||||
async def hanging_current_user():
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
finally:
|
||||
cancelled.set()
|
||||
|
||||
async def empty_collection():
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(main, "CONTEXT_TIMEOUT_SECONDS", 0.01)
|
||||
monkeypatch.setattr(main, "current_user", hanging_current_user)
|
||||
monkeypatch.setattr(main, "repos", empty_collection)
|
||||
monkeypatch.setattr(main, "issues", empty_collection)
|
||||
monkeypatch.setattr(main, "pull_requests", empty_collection)
|
||||
|
||||
response = await main.context()
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.headers["retry-after"] == "1"
|
||||
assert b'"repos":[]' in response.body
|
||||
assert b'"error":"Gitea context request timed out after 0.01s"' in response.body
|
||||
assert cancelled.is_set()
|
||||
@@ -20,6 +20,14 @@ def test_dashboard_has_realtime_gitea_event_stream_widget():
|
||||
assert "event.repo?.full_name" in html
|
||||
|
||||
|
||||
def test_event_stream_reports_when_activity_was_refreshed():
|
||||
html = DASHBOARD.read_text()
|
||||
|
||||
assert 'id="gitea-events-status"' in html
|
||||
assert "setEventStreamStatus('Updating…')" in html
|
||||
assert "setEventStreamStatus('Updated ' + fmt(new Date()))" in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_event_stream_returns_recent_authenticated_gitea_activity(monkeypatch):
|
||||
expected = [{"type": "create", "actor": {"login": "timmy"}}]
|
||||
|
||||
+36
-3
@@ -1,6 +1,39 @@
|
||||
from src.main import app, health
|
||||
import pytest
|
||||
|
||||
from src import main
|
||||
|
||||
|
||||
def test_health_endpoint_reports_service_liveness_without_gitea_access():
|
||||
assert any(getattr(route, "path", None) == "/healthz" for route in app.routes)
|
||||
assert health() == {"status": "ok", "service": "stackchain-dashboard"}
|
||||
assert any(getattr(route, "path", None) == "/healthz" for route in main.app.routes)
|
||||
assert main.health() == {"status": "ok", "service": "stackchain-dashboard"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_readiness_endpoint_reports_connected_gitea_user(monkeypatch):
|
||||
async def connected_user():
|
||||
return {"login": "timmy"}
|
||||
|
||||
monkeypatch.setattr(main, "current_user", connected_user)
|
||||
|
||||
response = await main.readiness()
|
||||
|
||||
assert any(getattr(route, "path", None) == "/readyz" for route in main.app.routes)
|
||||
assert response == {
|
||||
"status": "ready",
|
||||
"service": "stackchain-dashboard",
|
||||
"gitea_user": "timmy",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_readiness_endpoint_returns_503_when_gitea_is_unavailable(monkeypatch):
|
||||
async def unavailable_user():
|
||||
raise RuntimeError("connection refused")
|
||||
|
||||
monkeypatch.setattr(main, "current_user", unavailable_user)
|
||||
|
||||
response = await main.readiness()
|
||||
|
||||
assert response.status_code == 503
|
||||
assert b'"status":"not_ready"' in response.body
|
||||
assert b'"error":"connection refused"' in response.body
|
||||
@@ -23,3 +23,12 @@ def test_readme_documents_a_complete_local_quickstart():
|
||||
assert "uvicorn src.main:app" in text
|
||||
assert "http://127.0.0.1:8000/api/v1/context" in text
|
||||
assert "uvicorn==" in REQUIREMENTS.read_text()
|
||||
|
||||
|
||||
def test_readme_documents_liveness_and_gitea_readiness_checks():
|
||||
text = README.read_text()
|
||||
|
||||
assert "`/healthz`" in text
|
||||
assert "`/readyz`" in text
|
||||
assert "does not contact Gitea" in text
|
||||
assert "HTTP 503" in text
|
||||
@@ -1,4 +1,6 @@
|
||||
import json
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -6,6 +8,7 @@ import pytest
|
||||
from src.release_engine import (
|
||||
CommandResult,
|
||||
EngineConfig,
|
||||
GiteaClient,
|
||||
Issue,
|
||||
ReleaseEngine,
|
||||
RunState,
|
||||
@@ -15,6 +18,28 @@ from src.release_engine import (
|
||||
)
|
||||
|
||||
|
||||
def test_stale_token_error_explains_how_to_restore_cron_authentication():
|
||||
class UnauthorizedHandler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
self.send_response(401)
|
||||
self.end_headers()
|
||||
self.wfile.write(b'{"message":"user does not exist [uid: 0, name: ]"}')
|
||||
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
|
||||
server = HTTPServer(("127.0.0.1", 0), UnauthorizedHandler)
|
||||
thread = threading.Thread(target=server.handle_request)
|
||||
thread.start()
|
||||
try:
|
||||
client = GiteaClient(f"http://127.0.0.1:{server.server_port}", "stale-token")
|
||||
with pytest.raises(RuntimeError, match="refresh the cron GITEA_TOKEN"):
|
||||
client.list_open_issues("stackchain/stackchain-dashboard")
|
||||
finally:
|
||||
thread.join(timeout=2)
|
||||
server.server_close()
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, issues, verified_assignee="timmy", existing_pr=None):
|
||||
self.issues = issues
|
||||
|
||||
Reference in new issue
Block a user