Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
3325 lines (3094 loc) · 130 KB
/
Copy pathserver.py
File metadata and controls
3325 lines (3094 loc) · 130 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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Main HTTP server entry point and connection lifecycle orchestration."""
from __future__ import annotations
import argparse
import gzip
import json
import logging
import os
import random
import selectors
import signal
import socket
import ssl
import threading
import time
import urllib.error
import urllib.request
import uuid
from collections import deque
from collections.abc import Iterator
from dataclasses import dataclass, field
from pathlib import Path
from typing import BinaryIO
from auth_store import AuthStore
from config import (
AUTH_USERS_FILE,
CLI_REFRESH_MS_DEFAULT,
DEFAULT_CHAOS_SEED,
DEMO_TOKEN,
DRAIN_TIMEOUT_SECS,
ENABLE_EXPECT_CONTINUE,
ENABLE_INCIDENT_MODE,
ENABLE_LIVE_EVENTS,
ENABLE_PLAYGROUND,
ENABLE_SCENARIOS,
ENABLE_TARGET_PROXY,
ENABLE_TLS,
EVENT_BUFFER_SIZE,
EVENT_HEARTBEAT_SECS,
HISTORY_LIMIT,
HOST,
HTTPS_PORT,
IDLE_SWEEP_INTERVAL_SECS,
INCIDENT_DEFAULT_LATENCY_MS,
INCIDENT_DEFAULT_PROBABILITY,
INCIDENT_MAX_LATENCY_MS,
KEEPALIVE_TIMEOUT_SECS,
LIVE_EVENTS_REQUIRE_SELECTORS,
LOG_FORMAT,
MAX_ACTIVE_CONNECTIONS,
MAX_ASSERTIONS_PER_STEP,
MAX_KEEPALIVE_REQUESTS,
MAX_MOCK_BODY_BYTES,
MAX_MOCK_ROUTES,
MAX_SCENARIOS,
MAX_STEPS_PER_SCENARIO,
MAX_TARGETS,
METRICS_BACKEND,
METRICS_FLUSH_INTERVAL_SECS,
METRICS_RETENTION_DAYS,
METRICS_SQLITE_FILE,
PORT,
PUBLIC_BASE_URL,
REDIRECT_HTTP_TO_HTTPS,
REQUEST_QUEUE_SIZE,
REQUIRE_DEMO_TOKEN,
SCENARIO_STATE_FILE,
SELECT_TIMEOUT_SECS,
SERVER_ENGINE,
SESSION_TTL_MINUTES,
SHUTDOWN_POLL_INTERVAL_SECS,
SOCKET_TIMEOUT_SECS,
STATE_FILE,
TARGET_STATE_FILE,
TLS_CERT_FILE,
TLS_KEY_FILE,
WORKER_COUNT,
WRITE_CHUNK_SIZE,
)
from dynamic_mock_dispatch import response_from_mock
from event_hub import EventHub
from handlers.example_handlers import home, serve_static, stream_demo, submit
from metrics import MetricsRegistry
from metrics_store import create_metrics_store
from playground_api import PlaygroundAPI
from playground_store import PlaygroundStore
from request import KNOWN_METHODS, HTTPRequest, HTTPRequestParseError
from response import REASON_PHRASES, HTTPResponse, iter_chunked_encoded, prepare_response
from router import Router
from scenario_api import ScenarioAPI
from scenario_engine import ScenarioEngine
from scenario_store import ScenarioStore
from session_store import SessionStore
from socket_handler import (
HeaderTooLargeError,
MalformedRequestError,
PayloadTooLargeError,
SocketTimeoutError,
extract_http_request_message,
inspect_http_request_head,
read_http_request_message,
write_http_response,
write_http_response_message,
)
from target_store import TargetStore
from target_store import utc_now as target_utc_now
from thread_pool import ThreadPool
logger = logging.getLogger(__name__)
ROLE_RANK = {"viewer": 1, "operator": 2, "admin": 3}
WRITE_METHODS = {"POST", "PUT", "PATCH", "DELETE"}
@dataclass(slots=True)
class OutboundResponse:
"""Tracks incremental write state for a queued HTTP response."""
response: HTTPResponse
method: str
path: str
started_at: float
connection_reused: bool
connection_id: int
request_id: int
bytes_in: int
route_key: str
trace_id: str
close_after: bool
metrics_started: bool
replay_input: dict[str, object] | None = None
pending_chunks: deque[memoryview] = field(default_factory=deque)
stream_iter: Iterator[bytes] | None = None
file_obj: BinaryIO | None = None
file_remaining: int = 0
file_offset: int = 0
bytes_sent: int = 0
@classmethod
def from_http_response(
cls,
*,
response: HTTPResponse,
method: str,
path: str,
started_at: float,
connection_reused: bool,
connection_id: int,
request_id: int,
bytes_in: int,
route_key: str,
trace_id: str,
close_after: bool,
metrics_started: bool,
replay_input: dict[str, object] | None = None,
) -> "OutboundResponse":
prepared = prepare_response(response)
outbound = cls(
response=response,
method=method,
path=path,
started_at=started_at,
connection_reused=connection_reused,
connection_id=connection_id,
request_id=request_id,
bytes_in=bytes_in,
route_key=route_key,
trace_id=trace_id,
close_after=close_after,
metrics_started=metrics_started,
replay_input=replay_input,
)
outbound.pending_chunks.append(memoryview(prepared.head))
if prepared.body is not None and prepared.body:
outbound.pending_chunks.append(memoryview(prepared.body))
elif prepared.stream is not None:
outbound.stream_iter = iter_chunked_encoded(prepared.stream)
elif prepared.file_path is not None:
outbound.file_obj = prepared.file_path.open("rb")
outbound.file_remaining = prepared.file_path.stat().st_size
return outbound
def close_resources(self) -> None:
if self.file_obj is not None:
self.file_obj.close()
self.file_obj = None
@dataclass(slots=True)
class ConnectionState:
sock: socket.socket
address: tuple[str, int]
connection_id: int
recv_buffer: bytearray = field(default_factory=bytearray)
raw_writes: deque[memoryview] = field(default_factory=deque)
queued_responses: deque[OutboundResponse] = field(default_factory=deque)
current_response: OutboundResponse | None = None
requests_served: int = 0
request_seq: int = 0
last_activity: float = field(default_factory=time.monotonic)
closing: bool = False
continue_sent_headers: set[int] = field(default_factory=set)
@dataclass(slots=True)
class TLSConfig:
enabled: bool
cert_file: str
key_file: str
https_port: int
redirect_http_to_https: bool
@dataclass(slots=True)
class IncidentProfile:
active: bool = False
mode: str = "none"
probability: float = INCIDENT_DEFAULT_PROBABILITY
latency_ms: int = INCIDENT_DEFAULT_LATENCY_MS
seed: int = 1337
started_at: float = 0.0
affected_requests: int = 0
class HTTPServer:
def __init__(
self,
host: str = HOST,
port: int = PORT,
router: Router | None = None,
worker_count: int = WORKER_COUNT,
request_queue_size: int = REQUEST_QUEUE_SIZE,
*,
engine: str = SERVER_ENGINE,
max_active_connections: int = MAX_ACTIVE_CONNECTIONS,
keepalive_timeout_secs: int = KEEPALIVE_TIMEOUT_SECS,
enable_tls: bool = ENABLE_TLS,
tls_cert_file: str = TLS_CERT_FILE,
tls_key_file: str = TLS_KEY_FILE,
https_port: int = HTTPS_PORT,
redirect_http_to_https: bool = REDIRECT_HTTP_TO_HTTPS,
drain_timeout_secs: float = DRAIN_TIMEOUT_SECS,
log_format: str = LOG_FORMAT,
enable_playground: bool = ENABLE_PLAYGROUND,
state_file: str = STATE_FILE,
history_limit: int = HISTORY_LIMIT,
max_mock_body_bytes: int = MAX_MOCK_BODY_BYTES,
max_mock_routes: int = MAX_MOCK_ROUTES,
enable_scenarios: bool = ENABLE_SCENARIOS,
scenario_state_file: str = SCENARIO_STATE_FILE,
max_scenarios: int = MAX_SCENARIOS,
max_steps_per_scenario: int = MAX_STEPS_PER_SCENARIO,
max_assertions_per_step: int = MAX_ASSERTIONS_PER_STEP,
default_chaos_seed: int = DEFAULT_CHAOS_SEED,
enable_live_events: bool = ENABLE_LIVE_EVENTS,
event_buffer_size: int = EVENT_BUFFER_SIZE,
event_heartbeat_secs: int = EVENT_HEARTBEAT_SECS,
live_events_require_selectors: bool = LIVE_EVENTS_REQUIRE_SELECTORS,
cli_refresh_ms_default: int = CLI_REFRESH_MS_DEFAULT,
enable_target_proxy: bool = ENABLE_TARGET_PROXY,
target_state_file: str = TARGET_STATE_FILE,
max_targets: int = MAX_TARGETS,
demo_token: str = DEMO_TOKEN,
require_demo_token: bool = REQUIRE_DEMO_TOKEN,
public_base_url: str = PUBLIC_BASE_URL,
metrics_backend: str = METRICS_BACKEND,
metrics_sqlite_file: str = METRICS_SQLITE_FILE,
metrics_retention_days: int = METRICS_RETENTION_DAYS,
metrics_flush_interval_secs: int = METRICS_FLUSH_INTERVAL_SECS,
auth_users_file: str = AUTH_USERS_FILE,
session_ttl_minutes: int = SESSION_TTL_MINUTES,
codecrafters_mode: bool = False,
files_directory: str | None = None,
) -> None:
self.host = host
self.port = port
self.http_port = port
self.https_port = https_port
self.router = router or self._build_default_router()
self.worker_count = worker_count
self.request_queue_size = request_queue_size
self.engine = engine
self.max_active_connections = max_active_connections
self.keepalive_timeout_secs = keepalive_timeout_secs
self.drain_timeout_secs = drain_timeout_secs
self.log_format = log_format
self.enable_playground = enable_playground
self.state_file = state_file
self.history_limit = history_limit
self.max_mock_body_bytes = max_mock_body_bytes
self.max_mock_routes = max_mock_routes
self.enable_scenarios = enable_scenarios
self.scenario_state_file = scenario_state_file
self.max_scenarios = max_scenarios
self.max_steps_per_scenario = max_steps_per_scenario
self.max_assertions_per_step = max_assertions_per_step
self.default_chaos_seed = default_chaos_seed
self.enable_live_events = enable_live_events
self.event_heartbeat_secs = event_heartbeat_secs
self.live_events_require_selectors = live_events_require_selectors
self.cli_refresh_ms_default = cli_refresh_ms_default
self.enable_target_proxy = enable_target_proxy
self.target_state_file = target_state_file
self.max_targets = max_targets
self.demo_token = demo_token
self.require_demo_token = require_demo_token
self.public_base_url = public_base_url
self.metrics_retention_days = max(1, int(metrics_retention_days))
self.metrics_flush_interval_secs = max(1, int(metrics_flush_interval_secs))
self.auth_users_file = auth_users_file
self.session_ttl_minutes = max(1, int(session_ttl_minutes))
self.codecrafters_mode = codecrafters_mode
self.files_directory = (
Path(files_directory).resolve() if files_directory is not None else None
)
self.enable_incident_mode = ENABLE_INCIDENT_MODE
self._metrics_worker_thread: threading.Thread | None = None
self._auth_store = AuthStore(users_file=self.auth_users_file)
self._session_store = SessionStore(ttl_minutes=self.session_ttl_minutes)
self._metrics_store = create_metrics_store(
backend=metrics_backend,
sqlite_file=metrics_sqlite_file,
)
self.tls_config = TLSConfig(
enabled=enable_tls,
cert_file=tls_cert_file,
key_file=tls_key_file,
https_port=https_port,
redirect_http_to_https=redirect_http_to_https,
)
self._ssl_context: ssl.SSLContext | None = None
self._server_socket: socket.socket | None = None
self._redirect_socket: socket.socket | None = None
self._redirect_thread: threading.Thread | None = None
self._pool: ThreadPool | None = None
self._selector: selectors.BaseSelector | None = None
self._selector_connections: dict[int, ConnectionState] = {}
self._next_connection_id = 0
self._running = False
self._accepting = False
self._lifecycle_state = "stopped"
self._drain_started_at = 0.0
self._drain_elapsed_ms = 0.0
self._state_lock = threading.Lock()
self._incident_lock = threading.Lock()
self._incident_profile = IncidentProfile()
self._incident_request_seq = 0
self.metrics = MetricsRegistry(trend_store=self._metrics_store)
self.metrics.set_incident_state(state="inactive", profile="none")
self.event_hub: EventHub | None = (
EventHub(buffer_size=event_buffer_size) if self.enable_live_events else None
)
self.playground_store: PlaygroundStore | None = None
self.playground_api: PlaygroundAPI | None = None
self.scenario_store: ScenarioStore | None = None
self.scenario_engine: ScenarioEngine | None = None
self.scenario_api: ScenarioAPI | None = None
self.target_store: TargetStore | None = None
if self.enable_playground:
self.playground_store = PlaygroundStore(
state_file=self.state_file,
history_limit=self.history_limit,
max_mock_routes=self.max_mock_routes,
)
self.playground_api = PlaygroundAPI(
store=self.playground_store,
max_mock_body_bytes=self.max_mock_body_bytes,
dispatch_request=self._dispatch_internal_request,
)
snapshot = self.playground_store.snapshot()
self.metrics.set_playground_counts(
mock_count=len(snapshot.get("mocks", [])),
history_count=len(snapshot.get("history", [])),
)
if self.enable_scenarios:
self.scenario_store = ScenarioStore(
state_file=self.scenario_state_file,
max_scenarios=self.max_scenarios,
)
self.scenario_engine = ScenarioEngine(
dispatch_request=self._dispatch_internal_request,
max_steps_per_scenario=self.max_steps_per_scenario,
max_assertions_per_step=self.max_assertions_per_step,
default_seed=self.default_chaos_seed,
)
self.scenario_api = ScenarioAPI(
store=self.scenario_store,
engine=self.scenario_engine,
emit_event=self._emit_event,
)
if self.enable_target_proxy:
self.target_store = TargetStore(
state_file=self.target_state_file,
max_targets=self.max_targets,
)
self._emit_event(
"system.health",
"",
{
"state": "server_initialized",
"engine": self.engine,
"live_events": self.enable_live_events,
},
)
def _build_default_router(self) -> Router:
router = Router()
router.add_route("GET", "/", home)
router.add_route("GET", "/stream", stream_demo)
router.add_route("POST", "/submit", submit)
return router
def _build_ssl_context(self) -> ssl.SSLContext:
if not self.tls_config.enabled:
raise RuntimeError("TLS is disabled")
cert_file = self.tls_config.cert_file
key_file = self.tls_config.key_file
if not os.path.exists(cert_file):
raise FileNotFoundError(f"TLS certificate file not found: {cert_file}")
if not os.path.exists(key_file):
raise FileNotFoundError(f"TLS private key file not found: {key_file}")
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.minimum_version = ssl.TLSVersion.TLSv1_2
context.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20")
context.load_cert_chain(certfile=cert_file, keyfile=key_file)
return context
def _set_lifecycle_state(self, state: str) -> None:
with self._state_lock:
self._lifecycle_state = state
self.metrics.set_drain_state(
state=state,
inflight_remaining=self._inflight_remaining(),
elapsed_ms=self._drain_elapsed_ms,
)
def _inflight_remaining(self) -> int:
snapshot = self.metrics.snapshot()
inflight = int(snapshot.get("inflight_requests", 0))
if self.engine == "selectors":
inflight += len(self._selector_connections)
return inflight
def _is_draining(self) -> bool:
return self._lifecycle_state == "draining"
def _start_redirect_listener(self) -> None:
if not self.tls_config.enabled or not self.tls_config.redirect_http_to_https:
return
redirect_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
redirect_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
redirect_socket.bind((self.host, self.http_port))
redirect_socket.listen(128)
redirect_socket.settimeout(0.2)
self._redirect_socket = redirect_socket
self.http_port = redirect_socket.getsockname()[1]
thread = threading.Thread(target=self._redirect_loop, daemon=True)
thread.start()
self._redirect_thread = thread
def _redirect_loop(self) -> None:
assert self._redirect_socket is not None
while self._running and self._accepting:
try:
client_socket, _address = self._redirect_socket.accept()
except socket.timeout:
continue
except OSError:
break
with client_socket:
try:
client_socket.settimeout(1.0)
data = bytearray()
while b"\r\n\r\n" not in data and len(data) < 8192:
chunk = client_socket.recv(1024)
if not chunk:
break
data.extend(chunk)
location = self._redirect_location(bytes(data))
response = HTTPResponse(
status_code=308,
reason_phrase="Permanent Redirect",
headers={
"Location": location,
"Connection": "close",
"Cache-Control": "no-store",
},
body="Use HTTPS",
)
write_http_response_message(client_socket, response)
except OSError:
continue
def _redirect_location(self, raw_request: bytes) -> str:
host = self.host
target = "/"
if raw_request:
try:
head = raw_request.split(b"\r\n\r\n", 1)[0].decode("iso-8859-1")
lines = head.split("\r\n")
if lines and lines[0]:
parts = lines[0].split(" ")
if len(parts) >= 2 and parts[1]:
target = parts[1]
for line in lines[1:]:
if ":" not in line:
continue
name, value = line.split(":", 1)
if name.strip().lower() == "host":
host = value.strip().split(":")[0]
break
except Exception:
pass
return f"https://{host}:{self.https_port}{target}"
def _start_metrics_worker(self) -> None:
if self._metrics_worker_thread is not None and self._metrics_worker_thread.is_alive():
return
def _run() -> None:
while self._running:
time.sleep(self.metrics_flush_interval_secs)
self._session_store.prune_expired()
self.metrics.flush_trends()
self.metrics.prune_trends(retention_days=self.metrics_retention_days)
self.metrics.flush_trends()
self._metrics_worker_thread = threading.Thread(
target=_run,
daemon=True,
name="metrics-trends-worker",
)
self._metrics_worker_thread.start()
def _stop_metrics_worker(self) -> None:
thread = self._metrics_worker_thread
if thread is None:
return
self._running = False
if thread.is_alive():
thread.join(timeout=self.metrics_flush_interval_secs + 0.5)
self._metrics_worker_thread = None
def start(self) -> None:
"""Start listening and process clients according to selected engine."""
self._running = True
self._accepting = True
self._drain_elapsed_ms = 0.0
self._set_lifecycle_state("running")
self._start_metrics_worker()
if self.tls_config.enabled:
self._ssl_context = self._build_ssl_context()
self.https_port = self.tls_config.https_port
self._start_redirect_listener()
if self.engine == "threadpool":
self._start_threadpool()
return
if self.engine == "selectors":
self._start_selectors()
return
raise ValueError(f"Unsupported engine: {self.engine}")
def _start_threadpool(self) -> None:
bind_port = self.https_port if self.tls_config.enabled else self.port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
self._server_socket = server_socket
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((self.host, bind_port))
server_socket.listen(128)
server_socket.settimeout(0.2)
if self.tls_config.enabled:
self.https_port = server_socket.getsockname()[1]
self.port = self.https_port
else:
self.port = server_socket.getsockname()[1]
self._pool = ThreadPool(
worker_count=self.worker_count,
queue_size=self.request_queue_size,
handler=self._handle_client,
)
self._pool.start()
try:
while self._running:
try:
client_socket, address = server_socket.accept()
except socket.timeout:
continue
except OSError:
break
if self._is_draining():
self._send_drain_reject_response(client_socket)
continue
if self.tls_config.enabled:
wrapped = self._wrap_server_socket(client_socket)
if wrapped is None:
continue
client_socket = wrapped
if self._pool is None or not self._pool.submit(client_socket, address):
self._send_queue_full_response(client_socket)
finally:
if self._pool is not None:
self._pool.shutdown(graceful=True, timeout=self.drain_timeout_secs)
self._pool = None
self._stop_redirect_listener()
self._stop_metrics_worker()
self.metrics.close()
self._set_lifecycle_state("stopped")
def _start_selectors(self) -> None:
bind_port = self.https_port if self.tls_config.enabled else self.port
with (
socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket,
selectors.DefaultSelector() as selector,
):
self._server_socket = server_socket
self._selector = selector
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((self.host, bind_port))
server_socket.listen(128)
server_socket.setblocking(False)
selector.register(server_socket, selectors.EVENT_READ, data=None)
if self.tls_config.enabled:
self.https_port = server_socket.getsockname()[1]
self.port = self.https_port
else:
self.port = server_socket.getsockname()[1]
last_idle_sweep = time.monotonic()
try:
while self._running:
try:
events = selector.select(timeout=SELECT_TIMEOUT_SECS)
except OSError:
if not self._running:
break
raise
for key, mask in events:
if key.data is None:
if self._accepting:
self._accept_selector_clients(server_socket, selector)
continue
state: ConnectionState = key.data
if mask & selectors.EVENT_READ:
self._handle_selector_read(state, selector)
if mask & selectors.EVENT_WRITE:
self._handle_selector_write(state, selector)
now = time.monotonic()
if now - last_idle_sweep >= IDLE_SWEEP_INTERVAL_SECS:
self._sweep_idle_connections(selector, now)
last_idle_sweep = now
if self._is_draining():
self._update_drain_metrics()
if now - self._drain_started_at >= self.drain_timeout_secs:
self._running = False
break
if not self._selector_connections and self.metrics.snapshot().get(
"inflight_requests", 0
) == 0:
self._running = False
break
finally:
for state in list(self._selector_connections.values()):
self._close_selector_connection(state, selector)
self._selector_connections.clear()
self._selector = None
self._stop_redirect_listener()
self._stop_metrics_worker()
self.metrics.close()
self._set_lifecycle_state("stopped")
def stop(self) -> None:
if not self._running:
return
self._accepting = False
self._set_lifecycle_state("draining")
self._drain_started_at = time.monotonic()
self._update_drain_metrics()
if self._server_socket is not None:
self._server_socket.close()
self._server_socket = None
self._stop_redirect_listener()
deadline = time.monotonic() + self.drain_timeout_secs
while time.monotonic() < deadline:
inflight_remaining = self._inflight_remaining()
self._update_drain_metrics()
if inflight_remaining == 0:
break
time.sleep(SHUTDOWN_POLL_INTERVAL_SECS)
self._running = False
self._drain_elapsed_ms = max(0.0, (time.monotonic() - self._drain_started_at) * 1000)
self._update_drain_metrics()
if self._pool is not None:
self._pool.shutdown(graceful=True, timeout=self.drain_timeout_secs)
self._pool = None
if self._selector is not None:
for state in list(self._selector_connections.values()):
self._close_selector_connection(state, self._selector)
self._selector_connections.clear()
self._stop_metrics_worker()
self.metrics.flush_trends()
def _update_drain_metrics(self) -> None:
if self._lifecycle_state != "draining":
return
self._drain_elapsed_ms = max(0.0, (time.monotonic() - self._drain_started_at) * 1000)
self.metrics.set_drain_state(
state="draining",
inflight_remaining=self._inflight_remaining(),
elapsed_ms=self._drain_elapsed_ms,
)
def _stop_redirect_listener(self) -> None:
if self._redirect_socket is not None:
try:
self._redirect_socket.close()
except OSError:
pass
self._redirect_socket = None
if self._redirect_thread is not None:
self._redirect_thread.join(timeout=1.0)
self._redirect_thread = None
def _wrap_server_socket(self, client_socket: socket.socket) -> ssl.SSLSocket | None:
if self._ssl_context is None:
return None
try:
client_socket.settimeout(SOCKET_TIMEOUT_SECS)
wrapped = self._ssl_context.wrap_socket(client_socket, server_side=True)
wrapped.settimeout(SOCKET_TIMEOUT_SECS)
return wrapped
except ssl.SSLError as exc:
self.metrics.record_error_class("tls_handshake")
logger.warning("tls_handshake_failed error=%s", exc)
try:
client_socket.close()
except OSError:
pass
return None
def _send_drain_reject_response(self, client_socket: socket.socket) -> None:
with client_socket:
started_at = time.perf_counter()
response = HTTPResponse(
status_code=503,
reason_phrase="Service Unavailable",
headers={
"Connection": "close",
"Retry-After": "2",
},
body="Server Draining",
)
bytes_sent = write_http_response_message(client_socket, response)
trace_id = self._new_trace_id()
self._record_and_log(
address=("-", 0),
method="-",
path="-",
response=response,
payload_size=bytes_sent,
bytes_in=0,
started_at=started_at,
connection_reused=False,
connection_id=0,
request_id=0,
route_key="drain/reject",
trace_id=trace_id,
shutdown_phase="draining",
)
def _send_queue_full_response(self, client_socket: socket.socket) -> None:
with client_socket:
started_at = time.perf_counter()
response = HTTPResponse(
status_code=503,
reason_phrase="Service Unavailable",
headers={"Connection": "close"},
body="Service Unavailable",
)
bytes_sent = write_http_response_message(client_socket, response)
trace_id = self._new_trace_id()
self._record_and_log(
address=("-", 0),
method="-",
path="-",
response=response,
payload_size=bytes_sent,
bytes_in=0,
started_at=started_at,
connection_reused=False,
connection_id=0,
request_id=0,
route_key="queue/full",
trace_id=trace_id,
shutdown_phase=self._lifecycle_state,
)
def _new_trace_id(self) -> str:
return uuid.uuid4().hex[:16]
def _emit_event(self, event_type: str, trace_id: str, payload: dict[str, object]) -> None:
if self.event_hub is None:
return
self.event_hub.publish(
event_type=event_type,
source="server",
trace_id=trace_id,
payload=payload,
)
def _is_protected_path(self, path: str) -> bool:
protected_prefixes = (
"/api/mocks",
"/api/history",
"/api/replay",
"/api/scenarios",
"/api/targets",
"/api/proxy/request",
"/api/events",
"/api/incidents",
"/api/playground",
"/api/metrics/trends",
"/api/auth/me",
"/api/auth/logout",
)
return any(path.startswith(prefix) for prefix in protected_prefixes)
def _auth_enabled(self) -> bool:
if self.require_demo_token or bool(self.demo_token):
return True
return self._auth_store.has_users
def _extract_bearer_token(self, request: HTTPRequest) -> str:
auth_header = request.headers.get("authorization", "")
if auth_header.startswith("Bearer "):
return auth_header.removeprefix("Bearer ").strip()
query_token = request.query_params.get("token", [])
if query_token:
return str(query_token[0]).strip()
return ""
def _required_role(self, request: HTTPRequest) -> str | None:
path = request.path
method = request.method
if path == "/api/auth/login":
return None
if path in {"/api/auth/me", "/api/auth/logout"}:
return "viewer"
if path == "/api/metrics/trends":
return "viewer"
if path.startswith("/api/events/"):
return "viewer"
if path == "/api/playground/state":
return "viewer"
if path == "/api/history":
return "viewer"
if path == "/api/incidents/state":
return "viewer"
if path in {"/api/incidents/start", "/api/incidents/stop"}:
return "operator"
if path.startswith("/api/replay/"):
return "operator"
if path == "/api/playground/request":
return "operator"
if path == "/api/proxy/request":
return "operator"
if path == "/api/targets" or path.startswith("/api/targets/"):
if method in {"GET", "HEAD"}:
return "viewer"
return "admin"
if path == "/api/mocks" or path.startswith("/api/mocks/"):
if method in {"GET", "HEAD"}:
return "viewer"
return "admin"
if path == "/api/scenarios":
if method in {"GET", "HEAD"}:
return "viewer"
return "admin"
if path.startswith("/api/scenarios/"):
if path.endswith("/run"):
return "operator"
if path.endswith("/runs"):
return "viewer"
if path.startswith("/api/scenarios/runs/"):
return "viewer"
if method in {"GET", "HEAD"}:
return "viewer"
return "admin"
if self._is_protected_path(path):
if method in WRITE_METHODS:
return "admin"
return "viewer"
return None
def _authorized_role(self, request: HTTPRequest) -> tuple[str, str]:
token = self._extract_bearer_token(request)
if token and self.demo_token and token == self.demo_token:
return "admin", "demo_token"
session = self._session_store.get(token) if token else None
if session is not None:
role = str(session.get("role", "viewer")).strip().lower()
username = str(session.get("username", ""))
if role not in ROLE_RANK:
role = "viewer"
return role, username
if not self._auth_enabled():
return "admin", "open_mode"
return "", ""
def _authorize_request(self, request: HTTPRequest) -> HTTPResponse | None:
required_role = self._required_role(request)
if required_role is None:
return None
role, _principal = self._authorized_role(request)
if not role:
return self._unauthorized_response()
if ROLE_RANK.get(role, 0) < ROLE_RANK.get(required_role, 0):
return self._forbidden_response()
return None
def _unauthorized_response(self) -> HTTPResponse:
return HTTPResponse(
status_code=401,
headers={"Content-Type": "application/json"},
body=json.dumps({"error": {"code": "unauthorized", "message": "unauthorized"}}),
)
def _forbidden_response(self) -> HTTPResponse:
return HTTPResponse(
status_code=403,
headers={"Content-Type": "application/json"},
body=json.dumps({"error": {"code": "forbidden", "message": "forbidden"}}),
)
def _handle_auth_request(self, request: HTTPRequest) -> HTTPResponse:
if request.path == "/api/auth/login":
if request.method != "POST":
return HTTPResponse(
status_code=405,
headers={"Allow": "POST", "Content-Type": "application/json"},
body=json.dumps(
{
"error": {
"code": "method_not_allowed",
"message": "method not allowed",
}
}
),
)
if not self._auth_store.has_users:
return HTTPResponse(
status_code=503,
headers={"Content-Type": "application/json"},
body=json.dumps(
{
"error": {
"code": "auth_unavailable",
"message": "no auth users configured",
}
}
),
)
payload, error = self._read_json_payload(request)
if error is not None:
return error
username = str(payload.get("username", "")).strip()
password = str(payload.get("password", ""))
if not username or not password:
return self._targets_response(
400,
{
"error": {