neruton 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
neruton/forwarder.py ADDED
@@ -0,0 +1,810 @@
1
+ """Local HTTP/1.1 & WebSocket stream forwarder matching `crates/neruton-cli/src/forwarder.rs`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import socket
7
+ import ssl
8
+ import time
9
+ from dataclasses import dataclass
10
+ from enum import Enum
11
+ from http import HTTPStatus
12
+ from typing import Any, Callable, List, Optional, Protocol, Tuple
13
+ from urllib.parse import urlsplit
14
+
15
+ from .yamux import YamuxStream
16
+
17
+ HOP_BY_HOP_HEADERS = frozenset(
18
+ {
19
+ "connection",
20
+ "keep-alive",
21
+ "proxy-authenticate",
22
+ "proxy-authorization",
23
+ "te",
24
+ "trailer",
25
+ "transfer-encoding",
26
+ "upgrade",
27
+ "proxy-connection",
28
+ }
29
+ )
30
+
31
+ _MAX_HEADER_BYTES = 128 * 1024
32
+ _IO_CHUNK_SIZE = 32 * 1024
33
+
34
+
35
+ class HostHeaderKind(Enum):
36
+ REWRITE_TO_TARGET = "rewrite"
37
+ PRESERVE = "preserve"
38
+ CUSTOM = "custom"
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class HostHeaderMode:
43
+ kind: HostHeaderKind = HostHeaderKind.REWRITE_TO_TARGET
44
+ custom_value: Optional[str] = None
45
+
46
+ @classmethod
47
+ def from_option(cls, value: Optional[str]) -> HostHeaderMode:
48
+ if value is None:
49
+ return cls(HostHeaderKind.REWRITE_TO_TARGET)
50
+ trimmed = value.strip()
51
+ lower = trimmed.lower()
52
+ if not trimmed or lower == "rewrite":
53
+ return cls(HostHeaderKind.REWRITE_TO_TARGET)
54
+ if lower == "preserve":
55
+ return cls(HostHeaderKind.PRESERVE)
56
+ return cls(HostHeaderKind.CUSTOM, trimmed)
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class RequestEvent:
61
+ """Metadata emitted after forwarding an HTTP or WebSocket request."""
62
+
63
+ method: str
64
+ path: str
65
+ status: int
66
+ duration_ms: int
67
+
68
+
69
+ RequestCallback = Callable[[RequestEvent], None]
70
+
71
+
72
+ @dataclass
73
+ class TargetConfig:
74
+ """Resolved local upstream service configuration."""
75
+
76
+ url: str
77
+ scheme_https: bool
78
+ host: str
79
+ port: int
80
+ default_host_header: str
81
+ base_path: str
82
+ host_header_mode: HostHeaderMode
83
+ no_tls_verify: bool = False
84
+ ssl_context: Optional[ssl.SSLContext] = None
85
+
86
+ @classmethod
87
+ def from_url(
88
+ cls,
89
+ url: str,
90
+ *,
91
+ host_header: Optional[str] = None,
92
+ no_tls_verify: bool = False,
93
+ ) -> TargetConfig:
94
+ parsed = urlsplit(url)
95
+ scheme = parsed.scheme.lower()
96
+ if scheme == "https":
97
+ scheme_https = True
98
+ elif scheme == "http":
99
+ scheme_https = False
100
+ else:
101
+ raise ValueError(f"unsupported target scheme '{scheme}' (expected http or https)")
102
+
103
+ host = parsed.hostname
104
+ if not host:
105
+ raise ValueError("target URL is missing a host")
106
+
107
+ default_port = 443 if scheme_https else 80
108
+ explicit_port = parsed.port
109
+ port = explicit_port if explicit_port is not None else default_port
110
+
111
+ host_display = f"[{host}]" if ":" in host else host
112
+ if explicit_port is not None and explicit_port != default_port:
113
+ default_host_header = f"{host_display}:{explicit_port}"
114
+ else:
115
+ default_host_header = host_display
116
+
117
+ base_path = parsed.path.rstrip("/")
118
+
119
+ ssl_ctx: Optional[ssl.SSLContext] = None
120
+ if scheme_https:
121
+ ssl_ctx = build_ssl_context(no_tls_verify=no_tls_verify)
122
+
123
+ return cls(
124
+ url=url,
125
+ scheme_https=scheme_https,
126
+ host=host,
127
+ port=port,
128
+ default_host_header=default_host_header,
129
+ base_path=base_path,
130
+ host_header_mode=HostHeaderMode.from_option(host_header),
131
+ no_tls_verify=no_tls_verify,
132
+ ssl_context=ssl_ctx,
133
+ )
134
+
135
+
136
+ def build_ssl_context(*, no_tls_verify: bool = False) -> ssl.SSLContext:
137
+ """Build an SSLContext using system CAs or skipping verification if requested."""
138
+ ctx = ssl.create_default_context()
139
+ if no_tls_verify:
140
+ ctx.check_hostname = False
141
+ ctx.verify_mode = ssl.CERT_NONE
142
+ return ctx
143
+
144
+
145
+ class _Readable(Protocol):
146
+ async def read(self, n: int) -> bytes: ...
147
+
148
+
149
+ class _BufferedReader:
150
+ """Buffered async reader preserving unread trailing bytes (critical for 101 upgrades)."""
151
+
152
+ def __init__(self, stream: _Readable) -> None:
153
+ self._stream = stream
154
+ self._buf = bytearray()
155
+ self._eof = False
156
+
157
+ def take_buffer(self) -> bytes:
158
+ if not self._buf:
159
+ return b""
160
+ data = bytes(self._buf)
161
+ self._buf.clear()
162
+ return data
163
+
164
+ async def _fill(self) -> bool:
165
+ if self._eof:
166
+ return False
167
+ chunk = await self._stream.read(_IO_CHUNK_SIZE)
168
+ if not chunk:
169
+ self._eof = True
170
+ return False
171
+ self._buf.extend(chunk)
172
+ return True
173
+
174
+ async def read_until(self, delimiter: bytes, max_bytes: int = _MAX_HEADER_BYTES) -> bytes:
175
+ """Read up to and including `delimiter`. Returns `b''` on clean EOF before any bytes."""
176
+ while True:
177
+ idx = self._buf.find(delimiter)
178
+ if idx != -1:
179
+ end = idx + len(delimiter)
180
+ out = bytes(self._buf[:end])
181
+ del self._buf[:end]
182
+ return out
183
+ if len(self._buf) > max_bytes:
184
+ raise ValueError(f"HTTP header block exceeds {max_bytes} bytes")
185
+ if not await self._fill():
186
+ if not self._buf:
187
+ return b""
188
+ raise EOFError("unexpected EOF while reading HTTP headers")
189
+
190
+ async def read_line(self, max_bytes: int = 16 * 1024) -> bytes:
191
+ line = await self.read_until(b"\r\n", max_bytes=max_bytes)
192
+ if not line:
193
+ raise EOFError("unexpected EOF while reading HTTP chunk line")
194
+ return line
195
+
196
+ async def read_exact(self, n: int) -> bytes:
197
+ if n <= 0:
198
+ return b""
199
+ while len(self._buf) < n:
200
+ if not await self._fill():
201
+ raise EOFError(f"unexpected EOF: needed {n} bytes, got {len(self._buf)}")
202
+ out = bytes(self._buf[:n])
203
+ del self._buf[:n]
204
+ return out
205
+
206
+ async def read_some(self, max_len: int = _IO_CHUNK_SIZE) -> bytes:
207
+ if self._buf:
208
+ out = bytes(self._buf[:max_len])
209
+ del self._buf[:max_len]
210
+ return out
211
+ if self._eof:
212
+ return b""
213
+ chunk = await self._stream.read(max_len)
214
+ if not chunk:
215
+ self._eof = True
216
+ return b""
217
+ return chunk
218
+
219
+
220
+ def is_upgrade_request(headers: List[Tuple[str, str]]) -> bool:
221
+ has_upgrade = False
222
+ has_conn_upgrade = False
223
+ for name, value in headers:
224
+ lower = name.lower()
225
+ if lower == "upgrade":
226
+ has_upgrade = True
227
+ elif lower == "connection":
228
+ if any(part.strip().lower() == "upgrade" for part in value.split(",")):
229
+ has_conn_upgrade = True
230
+ return has_upgrade and has_conn_upgrade
231
+
232
+
233
+ def is_websocket_upgrade(headers: List[Tuple[str, str]]) -> bool:
234
+ if not is_upgrade_request(headers):
235
+ return False
236
+ for name, value in headers:
237
+ if name.lower() == "upgrade" and value.strip().lower() == "websocket":
238
+ return True
239
+ return False
240
+
241
+
242
+ def is_hop_by_hop(name: str, *, preserve_upgrade: bool) -> bool:
243
+ lower = name.lower()
244
+ if preserve_upgrade and lower in ("connection", "upgrade"):
245
+ return False
246
+ return lower in HOP_BY_HOP_HEADERS
247
+
248
+
249
+ def _parse_headers_block(raw: bytes) -> Tuple[str, List[Tuple[str, str]]]:
250
+ text = raw[:-4].decode("latin-1")
251
+ lines = text.split("\r\n")
252
+ if not lines or not lines[0]:
253
+ raise ValueError("empty HTTP start line")
254
+ start_line = lines[0]
255
+ headers: List[Tuple[str, str]] = []
256
+ for line in lines[1:]:
257
+ if not line:
258
+ continue
259
+ if ":" not in line:
260
+ raise ValueError(f"malformed HTTP header line: {line!r}")
261
+ name, value = line.split(":", 1)
262
+ headers.append((name.strip(), value.strip()))
263
+ return start_line, headers
264
+
265
+
266
+ def _has_chunked_encoding(headers: List[Tuple[str, str]]) -> bool:
267
+ for name, value in headers:
268
+ if name.lower() == "transfer-encoding":
269
+ if any(part.strip().lower() == "chunked" for part in value.split(",")):
270
+ return True
271
+ return False
272
+
273
+
274
+ def _get_content_length(headers: List[Tuple[str, str]]) -> Optional[int]:
275
+ for name, value in headers:
276
+ if name.lower() == "content-length":
277
+ try:
278
+ cl = int(value.strip())
279
+ if cl >= 0:
280
+ return cl
281
+ except ValueError:
282
+ return None
283
+ return None
284
+
285
+
286
+ def _should_close_connection(version: str, headers: List[Tuple[str, str]]) -> bool:
287
+ conn_tokens = set()
288
+ for name, value in headers:
289
+ if name.lower() == "connection":
290
+ for part in value.split(","):
291
+ tok = part.strip().lower()
292
+ if tok:
293
+ conn_tokens.add(tok)
294
+ if "close" in conn_tokens:
295
+ return True
296
+ if version.upper() == "HTTP/1.0" and "keep-alive" not in conn_tokens:
297
+ return True
298
+ return False
299
+
300
+
301
+ def _reason_phrase(status: int, raw_reason: str = "") -> str:
302
+ if raw_reason:
303
+ return raw_reason
304
+ try:
305
+ return HTTPStatus(status).phrase
306
+ except ValueError:
307
+ return ""
308
+
309
+
310
+ def _build_plain_error_response(status: int, message: str) -> bytes:
311
+ body = message.encode("utf-8")
312
+ reason = _reason_phrase(status)
313
+ head = (
314
+ f"HTTP/1.1 {status} {reason}\r\n"
315
+ f"Content-Type: text/plain; charset=utf-8\r\n"
316
+ f"Content-Length: {len(body)}\r\n"
317
+ f"Connection: close\r\n"
318
+ f"\r\n"
319
+ ).encode("latin-1")
320
+ return head + body
321
+
322
+
323
+ def _rewrite_forward_path(base_path: str, orig_path: str) -> str:
324
+ if not base_path:
325
+ return orig_path
326
+ if orig_path.startswith("/"):
327
+ return f"{base_path}{orig_path}"
328
+ return f"{base_path}/{orig_path}"
329
+
330
+
331
+ def _build_forwarded_request_headers(
332
+ method: str,
333
+ forward_path: str,
334
+ in_headers: List[Tuple[str, str]],
335
+ target: TargetConfig,
336
+ *,
337
+ is_upgrade: bool,
338
+ body_mode: str,
339
+ ) -> bytes:
340
+ out_headers: List[Tuple[str, str]] = []
341
+ mode = target.host_header_mode
342
+
343
+ for name, value in in_headers:
344
+ if is_hop_by_hop(name, preserve_upgrade=is_upgrade):
345
+ continue
346
+ lower_name = name.lower()
347
+ if body_mode == "chunked" and lower_name == "content-length":
348
+ continue
349
+ if lower_name == "host":
350
+ if mode.kind == HostHeaderKind.PRESERVE:
351
+ out_headers.append((name, value))
352
+ continue
353
+ out_headers.append((name, value))
354
+
355
+ if mode.kind == HostHeaderKind.REWRITE_TO_TARGET:
356
+ out_headers.append(("Host", target.default_host_header))
357
+ elif mode.kind == HostHeaderKind.CUSTOM and mode.custom_value is not None:
358
+ out_headers.append(("Host", mode.custom_value))
359
+
360
+ if body_mode == "chunked":
361
+ out_headers.append(("Transfer-Encoding", "chunked"))
362
+
363
+ if not is_upgrade:
364
+ out_headers.append(("Connection", "close"))
365
+
366
+ lines = [f"{method} {forward_path} HTTP/1.1"]
367
+ for name, value in out_headers:
368
+ lines.append(f"{name}: {value}")
369
+ lines.append("")
370
+ lines.append("")
371
+ return "\r\n".join(lines).encode("latin-1")
372
+
373
+
374
+ async def _connect_target(
375
+ target: TargetConfig,
376
+ ) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]:
377
+ if target.scheme_https:
378
+ reader, writer = await asyncio.open_connection(
379
+ host=target.host,
380
+ port=target.port,
381
+ ssl=target.ssl_context,
382
+ server_hostname=target.host,
383
+ )
384
+ else:
385
+ reader, writer = await asyncio.open_connection(
386
+ host=target.host,
387
+ port=target.port,
388
+ )
389
+
390
+ sock = writer.get_extra_info("socket")
391
+ if sock is not None:
392
+ try:
393
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
394
+ except OSError:
395
+ pass
396
+ return reader, writer
397
+
398
+
399
+ def _parse_chunk_size(size_line: bytes) -> int:
400
+ size_str = size_line[:-2].split(b";", 1)[0].strip()
401
+ if not size_str or not all(
402
+ (48 <= b <= 57) or (65 <= b <= 70) or (97 <= b <= 102) for b in size_str
403
+ ):
404
+ raise ValueError(f"invalid HTTP chunk size: {size_str!r}")
405
+ return int(size_str, 16)
406
+
407
+
408
+ async def _forward_chunked_body_to_writer(
409
+ src: _BufferedReader,
410
+ dst: asyncio.StreamWriter,
411
+ ) -> None:
412
+ while True:
413
+ size_line = await src.read_line()
414
+ chunk_size = _parse_chunk_size(size_line)
415
+ if chunk_size == 0:
416
+ # Consume optional trailers until empty CRLF line.
417
+ while True:
418
+ trailer_line = await src.read_line()
419
+ if trailer_line == b"\r\n":
420
+ break
421
+ dst.write(b"0\r\n\r\n")
422
+ await dst.drain()
423
+ return
424
+ chunk = await src.read_exact(chunk_size)
425
+ crlf = await src.read_exact(2)
426
+ if crlf != b"\r\n":
427
+ raise ValueError("invalid chunk terminator in request body")
428
+ dst.write(f"{chunk_size:x}\r\n".encode("ascii") + chunk + b"\r\n")
429
+ await dst.drain()
430
+
431
+
432
+ async def _forward_fixed_body_to_writer(
433
+ src: _BufferedReader,
434
+ dst: asyncio.StreamWriter,
435
+ remaining: int,
436
+ ) -> None:
437
+ while remaining > 0:
438
+ chunk = await src.read_some(min(remaining, _IO_CHUNK_SIZE))
439
+ if not chunk:
440
+ raise EOFError("unexpected EOF reading request body")
441
+ dst.write(chunk)
442
+ await dst.drain()
443
+ remaining -= len(chunk)
444
+
445
+
446
+ async def _forward_request_body_guarded(
447
+ coro: Any,
448
+ local_writer: asyncio.StreamWriter,
449
+ ) -> None:
450
+ try:
451
+ await coro
452
+ except asyncio.CancelledError:
453
+ raise
454
+ except Exception:
455
+ # Close upstream socket so neither the local service nor our response reader hangs
456
+ # when an incoming request body is malformed or truncated.
457
+ try:
458
+ local_writer.close()
459
+ except Exception:
460
+ pass
461
+ raise
462
+
463
+
464
+ async def _forward_chunked_body_to_yamux(
465
+ src: _BufferedReader,
466
+ dst: YamuxStream,
467
+ ) -> None:
468
+ while True:
469
+ size_line = await src.read_line()
470
+ chunk_size = _parse_chunk_size(size_line)
471
+ if chunk_size == 0:
472
+ while True:
473
+ trailer_line = await src.read_line()
474
+ if trailer_line == b"\r\n":
475
+ break
476
+ await dst.write(b"0\r\n\r\n")
477
+ return
478
+ chunk = await src.read_exact(chunk_size)
479
+ crlf = await src.read_exact(2)
480
+ if crlf != b"\r\n":
481
+ raise ValueError("invalid chunk terminator in response body")
482
+ await dst.write(f"{chunk_size:x}\r\n".encode("ascii") + chunk + b"\r\n")
483
+
484
+
485
+ async def _forward_fixed_body_to_yamux(
486
+ src: _BufferedReader,
487
+ dst: YamuxStream,
488
+ remaining: int,
489
+ ) -> None:
490
+ while remaining > 0:
491
+ chunk = await src.read_some(min(remaining, _IO_CHUNK_SIZE))
492
+ if not chunk:
493
+ raise EOFError("unexpected EOF reading upstream response body")
494
+ await dst.write(chunk)
495
+ remaining -= len(chunk)
496
+
497
+
498
+ async def _forward_eof_body_as_chunked_to_yamux(
499
+ src: _BufferedReader,
500
+ dst: YamuxStream,
501
+ ) -> None:
502
+ while True:
503
+ chunk = await src.read_some(_IO_CHUNK_SIZE)
504
+ if not chunk:
505
+ break
506
+ await dst.write(f"{len(chunk):x}\r\n".encode("ascii") + chunk + b"\r\n")
507
+ await dst.write(b"0\r\n\r\n")
508
+
509
+
510
+ async def _bridge_upgraded_streams(
511
+ yamux_reader: _BufferedReader,
512
+ yamux_stream: YamuxStream,
513
+ local_reader: _BufferedReader,
514
+ local_writer: asyncio.StreamWriter,
515
+ ) -> None:
516
+ async def yamux_to_local() -> None:
517
+ try:
518
+ leftover = yamux_reader.take_buffer()
519
+ if leftover:
520
+ local_writer.write(leftover)
521
+ await local_writer.drain()
522
+ while True:
523
+ data = await yamux_stream.read(_IO_CHUNK_SIZE)
524
+ if not data:
525
+ break
526
+ local_writer.write(data)
527
+ await local_writer.drain()
528
+ if local_writer.can_write_eof():
529
+ local_writer.write_eof()
530
+ except Exception:
531
+ pass
532
+
533
+ async def local_to_yamux() -> None:
534
+ try:
535
+ leftover = local_reader.take_buffer()
536
+ if leftover:
537
+ await yamux_stream.write(leftover)
538
+ while True:
539
+ data = await local_reader.read_some(_IO_CHUNK_SIZE)
540
+ if not data:
541
+ break
542
+ await yamux_stream.write(data)
543
+ await yamux_stream.write_eof()
544
+ except Exception:
545
+ pass
546
+
547
+ t1 = asyncio.create_task(yamux_to_local())
548
+ t2 = asyncio.create_task(local_to_yamux())
549
+ try:
550
+ await asyncio.gather(t1, t2)
551
+ finally:
552
+ for t in (t1, t2):
553
+ if not t.done():
554
+ t.cancel()
555
+
556
+
557
+ def _emit_request_event(
558
+ on_request: Optional[RequestCallback],
559
+ method: str,
560
+ path: str,
561
+ status: int,
562
+ started_at: float,
563
+ ) -> None:
564
+ if on_request is None:
565
+ return
566
+ ms = int((time.monotonic() - started_at) * 1000)
567
+ try:
568
+ on_request(RequestEvent(method=method, path=path, status=status, duration_ms=ms))
569
+ except Exception:
570
+ pass
571
+
572
+
573
+ async def _close_writer(writer: Optional[asyncio.StreamWriter]) -> None:
574
+ if writer is None:
575
+ return
576
+ try:
577
+ writer.close()
578
+ await writer.wait_closed()
579
+ except Exception:
580
+ pass
581
+
582
+
583
+ async def handle_yamux_stream(
584
+ stream: YamuxStream,
585
+ target: TargetConfig,
586
+ *,
587
+ on_request: Optional[RequestCallback] = None,
588
+ ) -> None:
589
+ """Serve an inbound Yamux stream carrying HTTP/1.1 (or upgraded WebSocket) traffic."""
590
+ yamux_reader = _BufferedReader(stream)
591
+
592
+ try:
593
+ while True:
594
+ raw_req_head = await yamux_reader.read_until(b"\r\n\r\n")
595
+ if not raw_req_head:
596
+ # Clean EOF between keep-alive requests.
597
+ break
598
+
599
+ started_at = time.monotonic()
600
+ try:
601
+ start_line, req_headers = _parse_headers_block(raw_req_head)
602
+ parts = start_line.split(" ", 2)
603
+ if len(parts) != 3:
604
+ raise ValueError(f"invalid HTTP request line: {start_line!r}")
605
+ method, orig_path, req_version = parts
606
+ except ValueError as exc:
607
+ await stream.write(_build_plain_error_response(400, f"neruton: bad request: {exc}"))
608
+ break
609
+
610
+ is_upgrade = is_upgrade_request(req_headers)
611
+ is_ws = is_websocket_upgrade(req_headers)
612
+ log_method = "WS" if is_ws else method
613
+ client_wants_close = _should_close_connection(req_version, req_headers)
614
+
615
+ if _has_chunked_encoding(req_headers):
616
+ req_body_mode = "chunked"
617
+ req_content_length = 0
618
+ else:
619
+ cl = _get_content_length(req_headers)
620
+ if cl is not None and cl > 0:
621
+ req_body_mode = "length"
622
+ req_content_length = cl
623
+ else:
624
+ req_body_mode = "none"
625
+ req_content_length = 0
626
+
627
+ local_writer: Optional[asyncio.StreamWriter] = None
628
+ body_task: Optional[asyncio.Task[None]] = None
629
+ headers_sent = False
630
+
631
+ try:
632
+ try:
633
+ local_reader_raw, local_writer = await _connect_target(target)
634
+ except Exception as exc:
635
+ _emit_request_event(on_request, log_method, orig_path, 502, started_at)
636
+ err_resp = _build_plain_error_response(
637
+ 502,
638
+ f"neruton: failed to connect to local service {target.url}: {exc}",
639
+ )
640
+ await stream.write(err_resp)
641
+ break
642
+
643
+ forward_path = _rewrite_forward_path(target.base_path, orig_path)
644
+ req_bytes = _build_forwarded_request_headers(
645
+ method,
646
+ forward_path,
647
+ req_headers,
648
+ target,
649
+ is_upgrade=is_upgrade,
650
+ body_mode=req_body_mode,
651
+ )
652
+ local_writer.write(req_bytes)
653
+ await local_writer.drain()
654
+
655
+ # Forward request body concurrently to prevent bidirectional deadlocks on
656
+ # large streaming uploads or echo endpoints.
657
+ if req_body_mode == "chunked":
658
+ body_task = asyncio.create_task(
659
+ _forward_request_body_guarded(
660
+ _forward_chunked_body_to_writer(yamux_reader, local_writer),
661
+ local_writer,
662
+ )
663
+ )
664
+ elif req_body_mode == "length":
665
+ body_task = asyncio.create_task(
666
+ _forward_request_body_guarded(
667
+ _forward_fixed_body_to_writer(
668
+ yamux_reader, local_writer, req_content_length
669
+ ),
670
+ local_writer,
671
+ )
672
+ )
673
+
674
+ local_buf = _BufferedReader(local_reader_raw)
675
+
676
+ # Read response headers, forwarding any 1xx interim responses (e.g. 100 Continue).
677
+ while True:
678
+ raw_resp_head = await local_buf.read_until(b"\r\n\r\n")
679
+ if not raw_resp_head:
680
+ raise EOFError("local service closed connection before response headers")
681
+ resp_start, resp_headers = _parse_headers_block(raw_resp_head)
682
+ rparts = resp_start.split(" ", 2)
683
+ if len(rparts) < 2:
684
+ raise ValueError(f"invalid upstream HTTP status line: {resp_start!r}")
685
+ status = int(rparts[1])
686
+ reason = rparts[2] if len(rparts) > 2 else _reason_phrase(status)
687
+
688
+ if 100 <= status < 200 and status != 101:
689
+ await stream.write(raw_resp_head)
690
+ continue
691
+ break
692
+
693
+ _emit_request_event(on_request, log_method, orig_path, status, started_at)
694
+
695
+ # 101 Switching Protocols: preserve all headers verbatim and pipe raw bytes.
696
+ if status == 101:
697
+ if body_task is not None:
698
+ await body_task
699
+ body_task = None
700
+ lines = [f"HTTP/1.1 101 {reason}"]
701
+ for name, value in resp_headers:
702
+ lines.append(f"{name}: {value}")
703
+ lines.append("")
704
+ lines.append("")
705
+ await stream.write("\r\n".join(lines).encode("latin-1"))
706
+ headers_sent = True
707
+
708
+ await _bridge_upgraded_streams(
709
+ yamux_reader, stream, local_buf, local_writer
710
+ )
711
+ return
712
+
713
+ # Standard HTTP response (>= 200).
714
+ no_body = method.upper() == "HEAD" or status in (204, 304)
715
+ resp_is_chunked = (not no_body) and _has_chunked_encoding(resp_headers)
716
+ resp_cl = None if (no_body or resp_is_chunked) else _get_content_length(resp_headers)
717
+ resp_eof_delimited = (not no_body) and (not resp_is_chunked) and (resp_cl is None)
718
+
719
+ out_resp_headers: List[Tuple[str, str]] = []
720
+ for name, value in resp_headers:
721
+ if is_hop_by_hop(name, preserve_upgrade=False):
722
+ continue
723
+ if resp_is_chunked and name.lower() == "content-length":
724
+ continue
725
+ out_resp_headers.append((name, value))
726
+
727
+ if resp_is_chunked or resp_eof_delimited:
728
+ out_resp_headers.append(("Transfer-Encoding", "chunked"))
729
+
730
+ resp_lines = [f"HTTP/1.1 {status} {reason}"]
731
+ for name, value in out_resp_headers:
732
+ resp_lines.append(f"{name}: {value}")
733
+ resp_lines.append("")
734
+ resp_lines.append("")
735
+ await stream.write("\r\n".join(resp_lines).encode("latin-1"))
736
+ headers_sent = True
737
+
738
+ if no_body:
739
+ pass
740
+ elif resp_is_chunked:
741
+ await _forward_chunked_body_to_yamux(local_buf, stream)
742
+ elif resp_cl is not None:
743
+ await _forward_fixed_body_to_yamux(local_buf, stream, resp_cl)
744
+ else:
745
+ await _forward_eof_body_as_chunked_to_yamux(local_buf, stream)
746
+
747
+ body_incomplete = False
748
+ if body_task is not None:
749
+ if not body_task.done():
750
+ body_incomplete = True
751
+ body_task.cancel()
752
+ try:
753
+ await body_task
754
+ except (asyncio.CancelledError, Exception):
755
+ body_incomplete = True
756
+ body_task = None
757
+
758
+ if client_wants_close or body_incomplete:
759
+ break
760
+
761
+ except Exception as exc:
762
+ body_exc: Optional[BaseException] = None
763
+ if body_task is not None:
764
+ if not body_task.done():
765
+ body_task.cancel()
766
+ try:
767
+ await body_task
768
+ except asyncio.CancelledError:
769
+ pass
770
+ except Exception as b_exc:
771
+ body_exc = b_exc
772
+ body_task = None
773
+ if not headers_sent:
774
+ if isinstance(body_exc, ValueError):
775
+ _emit_request_event(on_request, log_method, orig_path, 400, started_at)
776
+ try:
777
+ await stream.write(
778
+ _build_plain_error_response(
779
+ 400,
780
+ f"neruton: bad request body: {body_exc}",
781
+ )
782
+ )
783
+ except Exception:
784
+ pass
785
+ else:
786
+ _emit_request_event(on_request, log_method, orig_path, 502, started_at)
787
+ try:
788
+ await stream.write(
789
+ _build_plain_error_response(
790
+ 502,
791
+ f"neruton: local service request failed: {exc}",
792
+ )
793
+ )
794
+ except Exception:
795
+ pass
796
+ else:
797
+ await stream.reset()
798
+ break
799
+ finally:
800
+ if body_task is not None and not body_task.done():
801
+ body_task.cancel()
802
+ try:
803
+ await body_task
804
+ except (asyncio.CancelledError, Exception):
805
+ pass
806
+ await _close_writer(local_writer)
807
+ except Exception:
808
+ await stream.reset()
809
+ finally:
810
+ await stream.write_eof()