|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import hashlib |
| 4 | +import os |
| 5 | +import tempfile |
| 6 | +from dataclasses import dataclass, field |
| 7 | + |
| 8 | +from tigrcorn_asgi.errors import ASGIProtocolError |
| 9 | + |
| 10 | +from .helpers import format_strong_etag |
| 11 | +from .materialize import materialize_response_body_segments |
| 12 | +from .segments import BodySegment, FileBodySegment |
| 13 | +from .validation import normalize_response_file_segments, normalize_response_pathsend_segment |
| 14 | + |
| 15 | + |
| 16 | +def _default_spool_threshold() -> int: |
| 17 | + from tigrcorn_asgi import send |
| 18 | + |
| 19 | + return int(send.DEFAULT_RESPONSE_BODY_SPOOL_THRESHOLD) |
| 20 | + |
| 21 | + |
| 22 | +@dataclass(slots=True) |
| 23 | +class HTTPResponseCollector: |
| 24 | + status: int | None = None |
| 25 | + headers: list[tuple[bytes, bytes]] = field(default_factory=list) |
| 26 | + body_parts: list[bytes] = field(default_factory=list) |
| 27 | + trailers: list[tuple[bytes, bytes]] = field(default_factory=list) |
| 28 | + complete: bool = False |
| 29 | + informational_responses: list[tuple[int, list[tuple[bytes, bytes]]]] = field(default_factory=list) |
| 30 | + body_segments: list[BodySegment] = field(default_factory=list) |
| 31 | + uses_streamed_body: bool = False |
| 32 | + spool_threshold: int = field(default_factory=_default_spool_threshold) |
| 33 | + body_length: int = 0 |
| 34 | + _body_digest: object = field(default_factory=lambda: hashlib.blake2s(digest_size=16), repr=False) |
| 35 | + _spool_path: str | None = field(default=None, init=False, repr=False) |
| 36 | + _spool_handle: object | None = field(default=None, init=False, repr=False) |
| 37 | + _body_channel: str | None = field(default=None, init=False, repr=False) |
| 38 | + |
| 39 | + def _record_body_chunk(self, chunk: bytes) -> None: |
| 40 | + if not chunk: |
| 41 | + return |
| 42 | + self.body_length += len(chunk) |
| 43 | + self._body_digest.update(chunk) |
| 44 | + |
| 45 | + def has_spooled_body(self) -> bool: |
| 46 | + return self._spool_path is not None |
| 47 | + |
| 48 | + def generated_entity_tag(self) -> bytes: |
| 49 | + return format_strong_etag(self._body_digest.hexdigest().encode("ascii")) |
| 50 | + |
| 51 | + def _ensure_spool_file(self) -> None: |
| 52 | + if self._spool_handle is not None and self._spool_path is not None: |
| 53 | + return |
| 54 | + handle = tempfile.NamedTemporaryFile(prefix="tigrcorn-response-", suffix=".bin", delete=False) |
| 55 | + self._spool_handle = handle |
| 56 | + self._spool_path = handle.name |
| 57 | + if self.body_parts: |
| 58 | + for part in self.body_parts: |
| 59 | + if part: |
| 60 | + handle.write(part) |
| 61 | + handle.flush() |
| 62 | + self.body_parts.clear() |
| 63 | + |
| 64 | + def _flush_spool(self) -> None: |
| 65 | + handle = self._spool_handle |
| 66 | + if handle is not None: |
| 67 | + handle.flush() |
| 68 | + |
| 69 | + def spooled_body_segments(self) -> list[BodySegment]: |
| 70 | + if self._spool_path is None: |
| 71 | + return [] |
| 72 | + self._flush_spool() |
| 73 | + return [FileBodySegment(self._spool_path, 0, self.body_length)] |
| 74 | + |
| 75 | + async def materialize_body(self) -> bytes: |
| 76 | + self.finalize() |
| 77 | + if self._spool_path is None: |
| 78 | + return b"".join(self.body_parts) |
| 79 | + return await materialize_response_body_segments(self.spooled_body_segments()) |
| 80 | + |
| 81 | + def cleanup(self) -> None: |
| 82 | + handle = self._spool_handle |
| 83 | + self._spool_handle = None |
| 84 | + if handle is not None: |
| 85 | + try: |
| 86 | + handle.close() |
| 87 | + except Exception: |
| 88 | + pass |
| 89 | + path = self._spool_path |
| 90 | + self._spool_path = None |
| 91 | + if path: |
| 92 | + try: |
| 93 | + os.unlink(path) |
| 94 | + except FileNotFoundError: |
| 95 | + pass |
| 96 | + |
| 97 | + async def __call__(self, message: dict) -> None: |
| 98 | + message_type = message["type"] |
| 99 | + if message_type == "http.response.start": |
| 100 | + self._handle_response_start(message) |
| 101 | + return |
| 102 | + if message_type == "http.response.body": |
| 103 | + self._handle_response_body(message) |
| 104 | + return |
| 105 | + if message_type == "tigrcorn.http.response.file": |
| 106 | + self._handle_response_file(message) |
| 107 | + return |
| 108 | + if message_type == "http.response.pathsend": |
| 109 | + self._handle_response_pathsend(message) |
| 110 | + return |
| 111 | + if message_type == "http.response.trailers": |
| 112 | + self._handle_response_trailers(message) |
| 113 | + return |
| 114 | + raise ASGIProtocolError(f"unexpected HTTP send event: {message_type!r}") |
| 115 | + |
| 116 | + def _handle_response_start(self, message: dict) -> None: |
| 117 | + status = int(message["status"]) |
| 118 | + headers = list(message.get("headers", [])) |
| 119 | + if status < 200: |
| 120 | + if self.status is not None or self.body_parts or self.complete or self.uses_streamed_body or self.has_spooled_body(): |
| 121 | + raise ASGIProtocolError("informational response sent after final response start") |
| 122 | + self.informational_responses.append((status, headers)) |
| 123 | + return |
| 124 | + if self.status is not None: |
| 125 | + raise ASGIProtocolError("http.response.start sent more than once") |
| 126 | + self.status = status |
| 127 | + self.headers = headers |
| 128 | + |
| 129 | + def _handle_response_body(self, message: dict) -> None: |
| 130 | + if self.status is None: |
| 131 | + raise ASGIProtocolError("http.response.body sent before final http.response.start") |
| 132 | + if self._body_channel in {"file", "pathsend"}: |
| 133 | + raise ASGIProtocolError("http.response.body cannot follow streamed file response") |
| 134 | + self._body_channel = "body" |
| 135 | + chunk = bytes(message.get("body", b"")) |
| 136 | + self._record_body_chunk(chunk) |
| 137 | + should_spool = self.has_spooled_body() or (self.spool_threshold > 0 and self.body_length > self.spool_threshold) |
| 138 | + if should_spool: |
| 139 | + self._ensure_spool_file() |
| 140 | + if chunk: |
| 141 | + assert self._spool_handle is not None |
| 142 | + self._spool_handle.write(chunk) |
| 143 | + else: |
| 144 | + self.body_parts.append(chunk) |
| 145 | + self.complete = not bool(message.get("more_body", False)) |
| 146 | + |
| 147 | + def _handle_response_file(self, message: dict) -> None: |
| 148 | + if self.status is None: |
| 149 | + raise ASGIProtocolError("tigrcorn.http.response.file sent before final http.response.start") |
| 150 | + if self.body_parts or self.has_spooled_body() or self._body_channel == "body": |
| 151 | + raise ASGIProtocolError("tigrcorn.http.response.file cannot follow buffered body events") |
| 152 | + if self._body_channel == "pathsend": |
| 153 | + raise ASGIProtocolError("tigrcorn.http.response.file cannot follow http.response.pathsend") |
| 154 | + self._body_channel = "file" |
| 155 | + self.uses_streamed_body = True |
| 156 | + self.body_segments.extend(normalize_response_file_segments(message.get("segments"))) |
| 157 | + self.complete = not bool(message.get("more_body", False)) |
| 158 | + |
| 159 | + def _handle_response_pathsend(self, message: dict) -> None: |
| 160 | + if self.status is None: |
| 161 | + raise ASGIProtocolError("http.response.pathsend sent before final http.response.start") |
| 162 | + if self.body_parts or self.has_spooled_body() or self._body_channel is not None: |
| 163 | + raise ASGIProtocolError("http.response.pathsend cannot be mixed with buffered or streamed body events") |
| 164 | + if bool(message.get("more_body", False)): |
| 165 | + raise ASGIProtocolError("http.response.pathsend does not support more_body") |
| 166 | + self._body_channel = "pathsend" |
| 167 | + self.uses_streamed_body = True |
| 168 | + self.body_segments.append(normalize_response_pathsend_segment(message.get("path"))) |
| 169 | + self.complete = True |
| 170 | + |
| 171 | + def _handle_response_trailers(self, message: dict) -> None: |
| 172 | + if self.status is None: |
| 173 | + raise ASGIProtocolError("http.response.trailers sent before final http.response.start") |
| 174 | + self.trailers.extend(list(message.get("trailers", []))) |
| 175 | + self.complete = not bool(message.get("more_trailers", False)) |
| 176 | + |
| 177 | + def finalize(self) -> None: |
| 178 | + if self.status is None: |
| 179 | + raise ASGIProtocolError("application did not send final http.response.start") |
| 180 | + if not self.complete: |
| 181 | + raise ASGIProtocolError("application returned before completing the response body") |
| 182 | + self._flush_spool() |
| 183 | + |
| 184 | + def response_tuple(self) -> tuple[int, list[tuple[bytes, bytes]], bytes, list[tuple[bytes, bytes]]]: |
| 185 | + self.finalize() |
| 186 | + assert self.status is not None |
| 187 | + if self._spool_path is None: |
| 188 | + body = b"".join(self.body_parts) |
| 189 | + else: |
| 190 | + with open(self._spool_path, "rb") as handle: |
| 191 | + body = handle.read() |
| 192 | + return self.status, self.headers, body, list(self.trailers) |
0 commit comments