Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
505 lines (418 loc) · 17.2 KB
/
Copy pathserver.py
File metadata and controls
505 lines (418 loc) · 17.2 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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
"""
A multi-threaded HTTP web server built from scratch using only the Python
standard library (socket + threading). No Flask, no http.server.
Features:
- TCP socket listening, raw HTTP/1.1 request parsing
- Routing (exact + dynamic paths)
- Static file serving from ./static with MIME types
- JSON API endpoints (GET/POST)
- 404 / 405 / 400 error responses
- Thread-per-client concurrency
- Graceful shutdown on Ctrl+C
- Token-bucket rate limiting per client IP (429 when exceeded)
- LRU cache with TTL for expensive GET endpoints (X-Cache: HIT/MISS)
"""
import argparse
import json
import logging
import mimetypes
import os
import signal
import socket
import sys
import threading
import time
from collections import OrderedDict
from datetime import datetime, timezone
from urllib.parse import parse_qs, unquote, urlsplit
HOST = "127.0.0.1"
PORT = 8000
STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
MAX_REQUEST_BYTES = 64 * 1024
RECV_CHUNK = 4096
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(threadName)s] %(levelname)s %(message)s",
datefmt="%H:%M:%S",
)
log = logging.getLogger("pyserver")
# -- Caching & Rate Limiting --
class TTLCache:
"""Thread-safe LRU cache with per-entry time-to-live.
Uses an OrderedDict for O(1) get/put with LRU eviction, and stores an
expiry timestamp per entry. Safe under concurrent access via a lock.
"""
def __init__(self, max_size: int = 256, ttl_seconds: float = 5.0):
self.max_size = max_size
self.ttl = ttl_seconds
self._data: OrderedDict = OrderedDict()
self._lock = threading.Lock()
self.hits = 0
self.misses = 0
self.evictions = 0
def get(self, key):
now = time.monotonic()
with self._lock:
item = self._data.get(key)
if item is None:
self.misses += 1
return None
value, expires_at = item
if now >= expires_at:
del self._data[key] # expired
self.misses += 1
return None
self._data.move_to_end(key) # mark as recently used
self.hits += 1
return value
def put(self, key, value):
now = time.monotonic()
with self._lock:
self._data[key] = (value, now + self.ttl)
self._data.move_to_end(key)
while len(self._data) > self.max_size:
self._data.popitem(last=False) # evict least-recently-used
self.evictions += 1
def clear(self):
"""Invalidate all entries (called after write operations)."""
with self._lock:
self._data.clear()
def stats(self) -> dict:
total = self.hits + self.misses
ratio = (self.hits / total * 100) if total else 0.0
return {"hits": self.hits, "misses": self.misses,"hit_ratio_pct": round(ratio, 2),"evictions": self.evictions, "size": len(self._data)}
class RateLimiter:
"""Token-bucket rate limiter, one bucket per client IP.
Each bucket holds `capacity` tokens and refills at `refill_per_sec`.
A request consumes one token; empty bucket -> HTTP 429 Too Many Requests.
"""
def __init__(self, capacity: int = 30, refill_per_sec: float = 10.0):
self.capacity = capacity
self.refill_per_sec = refill_per_sec
self._buckets: dict[str, tuple[float, float]] = {} # ip -> (tokens, last)
self._lock = threading.Lock()
self.rejected = 0
def allow(self, client_ip: str) -> bool:
now = time.monotonic()
with self._lock:
tokens, last = self._buckets.get(client_ip,(float(self.capacity), now))
tokens = min(self.capacity, tokens + (now - last) * self.refill_per_sec)
if tokens >= 1.0:
tokens -= 1.0
allowed = True
else:
allowed = False
self.rejected += 1
self._buckets[client_ip] = (tokens, now)
return allowed
# -- Request / Response objects --
class HTTPRequest:
"""Parsed representation of an incoming HTTP request."""
def __init__(self, method: str, path: str, query: dict, headers: dict, body: bytes):
self.method = method.upper()
self.path = unquote(path) or "/"
self.query = query # dict[str, list[str]]
self.headers = headers # dict[str, str]
self.body = body
def json(self):
"""Parse the body as JSON, or raise ValueError."""
return json.loads(self.body.decode("utf-8"))
def form(self) -> dict:
"""Parse url-encoded form bodies."""
return {k: v[0] for k, v in parse_qs(self.body.decode("utf-8")).items()}
def __repr__(self):
return f"<HTTPRequest {self.method} {self.path}>"
class HTTPResponse:
"""An outgoing HTTP response."""
STATUS_TEXT = {
200: "OK", 201: "Created", 204: "No Content",
301: "Moved Permanently", 302: "Found",
400: "Bad Request", 403: "Forbidden", 404: "Not Found",
405: "Method Not Allowed", 411: "Length Required",
413: "Payload Too Large", 500: "Internal Server Error",
}
def __init__(self, status: int = 200, body: bytes = b"", content_type: str = "text/plain; charset=utf-8", headers: dict | None = None):
self.status = status
self.body = body if isinstance(body, bytes) else str(body).encode("utf-8")
self.headers = {"Content-Type": content_type}
if headers:
self.headers.update(headers)
@classmethod
def html(cls, text: str, status: int = 200) -> "HTTPResponse":
return cls(status, text.encode("utf-8"), "text/html; charset=utf-8")
@classmethod
def json_response(cls, data, status: int = 200) -> "HTTPResponse":
return cls(status, json.dumps(data).encode("utf-8"),
"application/json; charset=utf-8")
def to_bytes(self) -> bytes:
reason = self.STATUS_TEXT.get(self.status, "Unknown")
head = f"HTTP/1.1 {self.status} {reason}\r\n"
self.headers.setdefault("Content-Length", str(len(self.body)))
self.headers.setdefault("Date", datetime.now(timezone.utc).strftime("%a, %d %b %Y %H:%M:%S GMT"))
self.headers.setdefault("Server", "PyServer/1.0")
self.headers.setdefault("Connection", "close")
for k, v in self.headers.items():
head += f"{k}: {v}\r\n"
return head.encode("utf-8") + b"\r\n" + self.body
# -- Router --
class Router:
"""Maps (method, path-pattern) to handler functions.
Patterns may contain dynamic segments like '/users/<id>'.
"""
def __init__(self):
self._routes: list[tuple[str, list[str], object]] = []
def add(self, method: str, pattern: str, handler):
segments = pattern.strip("/").split("/") if pattern != "/" else []
self._routes.append((method.upper(), segments, handler))
def get(self, pattern):
return self._decorator("GET", pattern)
def post(self, pattern):
return self._decorator("POST", pattern)
def _decorator(self, method, pattern):
def wrap(fn):
self.add(method, pattern, fn)
return fn
return wrap
def resolve(self, method: str, path: str):
"""Return (handler, params) or (None, allowed_methods)."""
parts = path.strip("/").split("/") if path != "/" else []
allowed = set()
for m, segs, handler in self._routes:
params = self._match(segs, parts)
if params is None:
continue
if m == method:
return handler, params
allowed.add(m)
return None, allowed
@staticmethod
def _match(pattern_segs, path_segs):
if len(pattern_segs) != len(path_segs):
return None
params = {}
for p, s in zip(pattern_segs, path_segs):
if p.startswith("<") and p.endswith(">"):
params[p[1:-1]] = s
elif p != s:
return None
return params
# -- The Server --
class PyServer:
instances: list["PyServer"] = []
def __init__(self, host: str, port: int, router: Router,rate_limiter: RateLimiter | None = None,cache: TTLCache | None = None):
self.host = host
self.port = port
self.router = router
self.rate_limiter = rate_limiter or RateLimiter(capacity=50,refill_per_sec=25)
self.cache = cache or TTLCache(max_size=256, ttl_seconds=5.0)
self._sock: socket.socket | None = None
self._shutdown = threading.Event()
PyServer.instances.append(self)
@classmethod
def invalidate_caches(cls):
"""Clear caches on all running servers (used after writes)."""
for inst in cls.instances:
inst.cache.clear()
def serve_forever(self):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._sock.bind((self.host, self.port))
self._sock.listen(128)
log.info("Serving on http://%s:%s ", self.host, self.port)
while not self._shutdown.is_set():
try:
conn, addr = self._sock.accept()
except OSError:
break
t = threading.Thread(target=self._handle_client, args=(conn, addr), daemon=True)
t.start()
self._sock.close()
log.info("Server stopped.")
def stop(self):
self._shutdown.set()
# Wake up accept() by connecting to ourselves
try:
with socket.create_connection((self.host, self.port), timeout=1):
pass
except OSError:
pass
def _handle_client(self, conn: socket.socket, addr):
try:
conn.settimeout(10)
request = self._read_request(conn)
if request is None:
return
if not self.rate_limiter.allow(addr[0]):
response = HTTPResponse.json_response({"error": "rate limit exceeded, slow down"}, 429)
log.warning("429 rate-limited %s", addr[0])
conn.sendall(response.to_bytes())
conn.close()
return
log.info("%s %s %s -> %s:%s", addr[0], request.method, request.path + (f"?{request.query}" if False else ""), *addr)
response = self._dispatch(request)
except Exception:
log.exception("Unhandled error for %s", addr)
response = HTTPResponse.html("<h1>500 Internal Server Error</h1>", 500)
finally:
try:
conn.sendall(response.to_bytes())
conn.close()
except OSError:
pass
def _read_request(self, conn: socket.socket) -> HTTPRequest | None:
"""Read and parse one HTTP request. Returns None on malformed input."""
buf = b""
while b"\r\n\r\n" not in buf:
chunk = conn.recv(RECV_CHUNK)
if not chunk:
return None
buf += chunk
if len(buf) > MAX_REQUEST_BYTES:
return None
head, _, rest = buf.partition(b"\r\n\r\n")
lines = head.decode("latin-1").split("\r\n")
try:
method, target, _version = lines[0].split(" ", 2)
except ValueError:
return None
headers = {}
for line in lines[1:]:
if ":" in line:
key, _, value = line.partition(":")
headers[key.strip().lower()] = value.strip()
# Read body according to Content-Length
body = rest
length = int(headers.get("content-length", 0) or 0)
while len(body) < length:
chunk = conn.recv(RECV_CHUNK)
if not chunk:
break
body += chunk
body = body[:length]
split = urlsplit(target)
query = parse_qs(split.query)
return HTTPRequest(method, split.path, query, headers, body)
def _dispatch(self, req: HTTPRequest) -> HTTPResponse:
if req.method == "GET":
cache_key = f"{req.method} {req.path}?{sorted(req.query.items())}"
cached = self.cache.get(cache_key)
if cached is not None:
cached.headers["X-Cache"] = "HIT"
return cached
handler, extra = self.router.resolve(req.method, req.path)
if handler is None:
if extra:
resp = HTTPResponse.html("<h1>405 Method Not Allowed</h1>", 405)
resp.headers["Allow"] = ", ".join(sorted(extra))
return resp
return self._serve_static(req)
try:
result = handler(req, **extra)
if isinstance(result, HTTPResponse):
response = result
else:
response = HTTPResponse.json_response(result)
except ValueError as e:
return HTTPResponse.json_response({"error": str(e)}, 400)
if req.method == "GET":
self.cache.put(cache_key, response)
response.headers["X-Cache"] = "MISS"
return response
def _serve_static(self, req: HTTPRequest) -> HTTPResponse:
"""Serve files from STATIC_DIR; anything unresolved becomes 404."""
rel = req.path.lstrip("/")
if rel == "":
rel = "index.html"
full = os.path.normpath(os.path.join(STATIC_DIR, rel))
if not full.startswith(STATIC_DIR):
return HTTPResponse.html("<h1>403 Forbidden</h1>", 403)
if not os.path.isfile(full):
return HTTPResponse.html("<h1>404 Not Found</h1>"
f"<p>No route or file for {req.path}</p>", 404)
mime, _ = mimetypes.guess_type(full)
with open(full, "rb") as f:
data = f.read()
return HTTPResponse(200, data, mime or "application/octet-stream")
# -- Application routes --
router = Router()
server_instance: PyServer | None = None
# Simple in-memory data store so POST actually does something persistent-ish
NOTES: list[dict] = [{"id": 1, "title": "First note", "body": "Hello!"}]
@router.get("/api/hello")
def api_hello(req: HTTPRequest):
name = (req.query.get("name", ["world"]))[0]
return {"message": f"Hello, {name}!", "time": datetime.now().isoformat()}
@router.get("/api/notes")
def api_notes(req: HTTPRequest):
return {"count": len(NOTES), "notes": NOTES}
@router.post("/api/notes")
def api_create_note(req: HTTPRequest):
data = req.json()
if "title" not in data:
raise ValueError("'title' is required")
if "body" not in data:
raise ValueError("'body' is required")
note = {"id": (NOTES[-1]["id"] + 1) if NOTES else 1,"title": str(data["title"]),"body": str(data.get("body", ""))}
NOTES.append(note)
PyServer.invalidate_caches() # writes must invalidate cached reads
return HTTPResponse.json_response(note, 201)
@router.get("/api/notes/<id>")
def api_note(req: HTTPRequest, id: str):
if not id.isdigit():
raise ValueError("note id must be a number")
for note in NOTES:
if note["id"] == int(id):
return note
return HTTPResponse.json_response({"error": "note not found"}, 404)
@router.get("/api/slow")
def api_slow(req: HTTPRequest):
"""Deliberately expensive endpoint (~30ms) to demonstrate the cache."""
time.sleep(0.03)
return {"result": "expensive computation done","computed_at": datetime.now().isoformat()}
@router.get("/api/stats")
def api_stats(req: HTTPRequest):
"""Live server statistics: cache performance and rate limiting."""
return {
"cache": server_instance.cache.stats(),
"rate_limiter": {
"capacity": server_instance.rate_limiter.capacity,
"refill_per_sec": server_instance.rate_limiter.refill_per_sec,
"rejected_total": server_instance.rate_limiter.rejected,
},
}
@router.get("/api/info")
def api_info(req: HTTPRequest):
return {
"server": "PyServer/1.0 (pure stdlib)",
"user_agent": req.headers.get("user-agent", "unknown"),
"your_address": req.headers.get("host", "unknown"),
"endpoints": [
"GET /api/hello?name=You",
"GET /api/notes",
"POST /api/notes {\"title\": \"...\", \"body\": \"...\"}",
"GET /api/notes/<id>",
"GET /api/info",
"GET / (static index.html)",
],
}
# -- Entry Point For Running the Server --
def main():
parser = argparse.ArgumentParser(description="Pure-Python HTTP server")
parser.add_argument("--host", default=HOST)
parser.add_argument("--port", type=int, default=PORT)
parser.add_argument("--no-limit", action="store_true",
help="disable rate limiting (for benchmarking)")
args = parser.parse_args()
server = PyServer(args.host, args.port, router,
rate_limiter=(RateLimiter(capacity=10**9,
refill_per_sec=10**9)
if args.no_limit else None))
global server_instance
server_instance = server
def handle_sigint(signum, frame):
log.info("Shutting down...")
server.stop()
signal.signal(signal.SIGINT, handle_sigint)
server.serve_forever()
if __name__ == "__main__":
sys.exit(main())