-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
374 lines (315 loc) · 12.1 KB
/
Copy pathmain.py
File metadata and controls
374 lines (315 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
"""FastAPI app: Azur Lane server status API.
Endpoints:
GET / server-rendered cache diagnostics page
GET /api/v1/status full server lists
GET /api/v1/summary per-region counts
GET /api/v1/regions region list
GET /api/v1/regions/{key} single region detail
GET /api/v1/servers/{composite_id} single server
GET /healthz liveness probe
"""
from __future__ import annotations
import logging
import sys
import time
from collections.abc import AsyncGenerator, MutableMapping
from contextlib import asynccontextmanager
from typing import Any
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import HTMLResponse, JSONResponse
from starlette.types import ASGIApp, Receive, Scope, Send
from cache import (
RegionCache,
begin_request_tracking,
finish_request_tracking,
)
from checker import REGIONS, RawServer, RegionQueryError
from dashboard import render_dashboard
from models import (
HealthResponse,
RegionInfoOut,
RegionOut,
RegionsResponse,
ServerOut,
SingleRegionResponse,
SingleServerResponse,
StatusResponse,
SummaryRegionOut,
SummaryResponse,
utc_now_iso,
)
@asynccontextmanager
async def _lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
cache.start_background_refresh()
try:
yield
finally:
await cache.stop_background_refresh()
app = FastAPI(
title="Azur Lane Server Status API",
version="0.1.0",
description="Query Azur Lane region gateway server status.",
lifespan=_lifespan,
)
# Default TTLs (overridable by tests / config)
CACHE_TTL = 8.0
BG_REFRESH_INTERVAL = 5.0
QUERY_TIMEOUT = 10.0
cache: RegionCache = RegionCache(
ttl=CACHE_TTL,
bg_refresh_interval=BG_REFRESH_INTERVAL,
query_timeout=QUERY_TIMEOUT,
)
# ---------------------------------------------------------------------------
# Rate limiting middleware: per-IP in-flight concurrency cap
# ---------------------------------------------------------------------------
MAX_CONCURRENT_PER_IP = 10
_ip_inflight: dict[str, int] = {}
logger = logging.getLogger("server-status")
if not logger.handlers:
logger.setLevel(logging.INFO)
_handler = logging.StreamHandler(sys.stderr)
_handler.setFormatter(
logging.Formatter("%(levelname)s: %(message)s")
)
logger.addHandler(_handler)
logger.propagate = False
class ConcurrencyLimitMiddleware:
"""ASGI middleware: reject requests when an IP has >MAX_CONCURRENT_PER_IP
requests in flight. Pure async, no locks (asyncio is single-threaded)."""
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
client_ip = scope.get("client", ("unknown", 0))[0]
# honor proxy header if present
headers = dict(scope.get("headers", []))
fwd = headers.get(b"x-forwarded-for")
if fwd:
client_ip = fwd.decode("latin-1").split(",")[0].strip()
count = _ip_inflight.get(client_ip, 0)
if count >= MAX_CONCURRENT_PER_IP:
logger.info(
"request rejected: ip=%s method=%s path=%s status=429 reason=concurrency_limit",
client_ip,
scope.get("method", ""),
scope.get("path", ""),
)
response = JSONResponse(
status_code=429,
content={"detail": "too many concurrent requests"},
)
await response(scope, receive, send)
return
begin_request_tracking()
_ip_inflight[client_ip] = count + 1
started = time.monotonic()
status = 0
async def send_with_status(
message: MutableMapping[str, Any],
) -> None:
nonlocal status
if message.get("type") == "http.response.start":
status = int(message.get("status", 0))
await send(message)
try:
await self.app(scope, receive, send_with_status)
finally:
remaining = _ip_inflight.get(client_ip, 1) - 1
if remaining <= 0:
_ip_inflight.pop(client_ip, None)
else:
_ip_inflight[client_ip] = remaining
elapsed_ms = (time.monotonic() - started) * 1000.0
cache_stats = finish_request_tracking()
hits, misses = cache_stats if cache_stats is not None else (0, 0)
cache_flag = "HIT" if hits > 0 else ("Miss" if misses > 0 else "-")
status_line = f"{status} OK" if status == 200 else f"{status}"
logger.info("%s %s %s %.1fms", client_ip, cache_flag, status_line, elapsed_ms)
app.add_middleware(ConcurrencyLimitMiddleware)
# ---------------------------------------------------------------------------
# App lifecycle: background keep-alive refresh
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _server_out(s: RawServer) -> ServerOut:
return ServerOut(id=s.id, name=s.name, status=s.status, tag=s.tag)
def _parse_regions(region_param: str | None) -> list[str]:
"""Parse the comma-separated region param; None/empty -> all regions."""
if not region_param:
return list(REGIONS.keys())
keys = [k.strip() for k in region_param.split(",") if k.strip()]
unknown = [k for k in keys if k not in REGIONS]
if unknown:
raise HTTPException(status_code=404, detail=f"unknown region: {unknown[0]}")
return keys
def _filter_servers(servers: list[RawServer], states: list[str]) -> list[RawServer]:
if not states:
return servers
return [s for s in servers if s.status in states]
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@app.get("/healthz", response_model=HealthResponse, tags=["meta"])
async def healthz() -> HealthResponse:
return HealthResponse(status="ok")
@app.get("/", response_class=HTMLResponse, tags=["meta"])
async def dashboard() -> HTMLResponse:
"""Server-rendered cache diagnostics page (no client-side JS)."""
return HTMLResponse(render_dashboard(cache))
@app.get("/api/v1/regions", response_model=RegionsResponse, tags=["regions"])
async def regions_list() -> RegionsResponse:
return RegionsResponse(
regions=[
RegionInfoOut(key=k, name=v["name"], protocol=v["protocol"])
for k, v in REGIONS.items()
]
)
@app.get("/api/v1/status", response_model=StatusResponse, tags=["status"])
async def status(
region: str | None = Query(None, description="comma-separated region keys"),
state: str | None = Query(None, description="comma-separated status filter"),
) -> StatusResponse:
keys = _parse_regions(region)
states = [s.strip() for s in (state or "").split(",") if s.strip()]
regions_out: list[RegionOut] = []
for key in keys:
try:
entry, cached = await cache.get(key)
except RegionQueryError as e:
# query failed and no cache exists -> mark the region failed
regions_out.append(
RegionOut(
key=key,
name=REGIONS[key]["name"],
error=e.code,
cached=False,
queried_at=utc_now_iso(),
total=0,
servers=[],
)
)
continue
filtered = _filter_servers(entry.servers, states)
regions_out.append(
RegionOut(
key=key,
name=REGIONS[key]["name"],
error=entry.error,
cached=cached,
queried_at=utc_now_iso(),
total=len(entry.servers),
servers=[
_server_out(s) for s in sorted(filtered, key=lambda x: x.sort)
],
)
)
return StatusResponse(generated_at=utc_now_iso(), regions=regions_out)
@app.get("/api/v1/summary", response_model=SummaryResponse, tags=["status"])
async def summary(
region: str | None = Query(None, description="comma-separated region keys"),
) -> SummaryResponse:
keys = _parse_regions(region)
regions_out: list[SummaryRegionOut] = []
for key in keys:
try:
entry, cached = await cache.get(key)
except RegionQueryError as e:
regions_out.append(
SummaryRegionOut(
key=key,
name=REGIONS[key]["name"],
error=e.code,
cached=False,
queried_at=utc_now_iso(),
total=0,
)
)
continue
counts = {
"normal": 0,
"maintenance": 0,
"full": 0,
"reg_full": 0,
"unopened": 0,
"unknown": 0,
}
for s in entry.servers:
counts[s.status] = counts.get(s.status, 0) + 1
regions_out.append(
SummaryRegionOut(
key=key,
name=REGIONS[key]["name"],
error=entry.error,
cached=cached,
queried_at=utc_now_iso(),
total=len(entry.servers),
**counts,
)
)
return SummaryResponse(generated_at=utc_now_iso(), regions=regions_out)
@app.get("/api/v1/regions/{key}", response_model=SingleRegionResponse, tags=["regions"])
async def region_detail(
key: str,
state: str | None = Query(None, description="comma-separated status filter"),
) -> SingleRegionResponse:
if key not in REGIONS:
raise HTTPException(status_code=404, detail=f"unknown region: {key}")
try:
entry, cached = await cache.get(key)
except RegionQueryError as e:
raise HTTPException(status_code=502, detail={"error": e.code}) from e
states = [s.strip() for s in (state or "").split(",") if s.strip()]
filtered = _filter_servers(entry.servers, states)
return SingleRegionResponse(
key=key,
name=REGIONS[key]["name"],
error=entry.error,
cached=cached,
queried_at=utc_now_iso(),
total=len(entry.servers),
servers=[_server_out(s) for s in sorted(filtered, key=lambda x: x.sort)],
)
def _parse_composite(composite_id: str) -> tuple[str, int]:
"""'{region}_{server_id}' — split on the LAST underscore so that
'cn_ios_1' parses as region='cn_ios', id=1."""
idx = composite_id.rfind("_")
if idx <= 0 or idx == len(composite_id) - 1:
raise HTTPException(
status_code=422,
detail="invalid composite id, expected format: {region}_{server_id}",
)
region_key = composite_id[:idx]
server_id_str = composite_id[idx + 1 :]
if region_key not in REGIONS:
raise HTTPException(status_code=404, detail=f"unknown region: {region_key}")
try:
server_id = int(server_id_str)
except ValueError:
raise HTTPException(
status_code=422,
detail="invalid composite id, expected format: {region}_{server_id}",
) from None
return region_key, server_id
@app.get(
"/api/v1/servers/{composite_id}",
response_model=SingleServerResponse,
tags=["servers"],
)
async def server_detail(composite_id: str) -> SingleServerResponse:
region_key, server_id = _parse_composite(composite_id)
try:
entry, _ = await cache.get(region_key)
except RegionQueryError as e:
raise HTTPException(status_code=502, detail={"error": e.code}) from e
server = next((s for s in entry.servers if s.id == server_id), None)
if server is None:
raise HTTPException(status_code=404, detail=f"server not found: {composite_id}")
return SingleServerResponse(
region=region_key,
region_name=REGIONS[region_key]["name"],
server=_server_out(server),
)