-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
210 lines (176 loc) · 6.55 KB
/
Copy pathserver.py
File metadata and controls
210 lines (176 loc) · 6.55 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
import asyncio
import logging
import socket
import time
from collections.abc import Awaitable, Callable
from contextlib import asynccontextmanager
import requests
from fastapi import FastAPI
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, field_validator
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
DNS_TIMEOUT = 5.0
MIN_REQUEST_TIMEOUT = 0.1
MAX_REQUEST_TIMEOUT = 30.0
ALLOWED_METHODS = {"GET", "POST", "PUT", "DELETE", "HEAD", "PATCH", "OPTIONS"}
def clamp_timeout(value: float) -> float:
return max(MIN_REQUEST_TIMEOUT, min(value, MAX_REQUEST_TIMEOUT))
async def try_or_message[T](
work: Callable[[], Awaitable[T]],
*,
handlers: list[tuple[type[BaseException], Callable[[BaseException], T]]],
default: Callable[[BaseException], T],
) -> T:
try:
return await work()
except Exception as e: # noqa: BLE001 - dispatched to caller-supplied handlers below
for exc_type, formatter in handlers:
if isinstance(e, exc_type):
return formatter(e)
return default(e)
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
logger.info("Shutdown event received. Shutting down gracefully...")
app = FastAPI(lifespan=lifespan)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/healthz")
async def healthz():
return JSONResponse(content={"status": "ok"})
@app.get("/")
async def get_home():
return FileResponse("static/index.html")
def parse_headers(raw: str) -> dict[str, str]:
headers = {}
for line in raw.splitlines():
line = line.strip()
if not line or ":" not in line:
continue
key, _, value = line.partition(":")
headers[key.strip()] = value.strip()
return headers
class RequestIn(BaseModel):
url: str
method: str = "GET"
timeout: float = 5.0
headers: str = ""
@field_validator("timeout", mode="before")
@classmethod
def _coerce_timeout(cls, v: object) -> float:
try:
return float(v) # type: ignore[arg-type]
except (TypeError, ValueError):
return 5.0
class RequestOut(BaseModel):
response: str
headers: dict[str, str] = {}
@app.post("/api/request", response_model=RequestOut)
async def post_request(data: RequestIn):
method = data.method.upper() if data.method.upper() in ALLOWED_METHODS else "GET"
timeout_value = clamp_timeout(data.timeout)
async def work() -> tuple[str, dict[str, str]]:
res = await asyncio.to_thread(
requests.request, method, data.url, headers=parse_headers(data.headers), timeout=timeout_value
)
return res.text, dict(res.headers)
response_text, response_headers = await try_or_message(
work,
handlers=[(requests.exceptions.Timeout, lambda e: (f"Timeout: {e}", {}))],
default=lambda e: (f"Fehler: {e}", {}),
)
return RequestOut(response=response_text, headers=response_headers)
class ResolveIn(BaseModel):
hostname: str
class ResolveOut(BaseModel):
result: str
@app.post("/api/resolve", response_model=ResolveOut)
async def resolve_hostname(data: ResolveIn):
async def work() -> str:
ip_address = await asyncio.wait_for(
asyncio.to_thread(socket.gethostbyname, data.hostname), timeout=DNS_TIMEOUT
)
return f"Hostname: {data.hostname} IP-Adresse: {ip_address}"
result = await try_or_message(
work,
handlers=[
(TimeoutError, lambda e: f"Timeout beim Auflösen des Hostnamens '{data.hostname}' nach {DNS_TIMEOUT}s"),
(socket.gaierror, lambda e: f"Fehler beim Auflösen des Hostnamens '{data.hostname}': {e}"),
],
default=lambda e: f"Ein unerwarteter Fehler ist aufgetreten: {e}",
)
return ResolveOut(result=result)
class BodyData(BaseModel):
message: str
value: int
@app.post("/postbody")
async def post_body(data: BodyData):
logger.info(f"Received body: {data}")
return JSONResponse(content={
"echo_message": data.message,
"echo_value": data.value,
"status": "ok"
})
MAX_CHAIN_HOPS = 20
CHAIN_TIMEOUT_DEFAULT = 5.0
class ChainHop(BaseModel):
target: str
status_code: int | None = None
duration_ms: float | None = None
error: str | None = None
class ChainRequest(BaseModel):
message: str | None = None
chain: list[str] = []
timeout: float = CHAIN_TIMEOUT_DEFAULT
class ChainResponse(BaseModel):
message: str | None = None
final_status: int
path: list[ChainHop]
async def _call_next_hop(
next_url: str, rest: list[str], data: ChainRequest, timeout_value: float
) -> tuple[list[ChainHop], int]:
hop = ChainHop(target=next_url)
start = time.monotonic()
try:
res = await asyncio.to_thread(
requests.post,
f"{next_url.rstrip('/')}/chain",
json={"message": data.message, "chain": rest, "timeout": timeout_value},
timeout=timeout_value,
)
hop.duration_ms = round((time.monotonic() - start) * 1000, 1)
hop.status_code = res.status_code
try:
downstream = res.json()
path = [hop] + [ChainHop(**h) for h in downstream.get("path", [])]
final_status = downstream.get("final_status", res.status_code)
except ValueError:
hop.error = "Ungueltige Antwort (kein JSON)"
path = [hop]
final_status = 502
except (requests.exceptions.RequestException, ValueError) as e:
hop.duration_ms = round((time.monotonic() - start) * 1000, 1)
hop.error = str(e)
path = [hop]
final_status = 502
return path, final_status
async def run_chain(data: ChainRequest) -> ChainResponse:
if not data.chain:
return ChainResponse(message=data.message, final_status=200, path=[])
if len(data.chain) > MAX_CHAIN_HOPS:
return ChainResponse(
message=data.message,
final_status=400,
path=[ChainHop(target=data.chain[0], error=f"Kette zu lang (> {MAX_CHAIN_HOPS} Hops), abgebrochen")],
)
next_url, *rest = data.chain
timeout_value = clamp_timeout(data.timeout)
path, final_status = await _call_next_hop(next_url, rest, data, timeout_value)
return ChainResponse(message=data.message, final_status=final_status, path=path)
@app.post("/chain", response_model=ChainResponse)
async def chain(data: ChainRequest):
return await run_chain(data)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=5000)