Skip to content

Commit

Permalink
h2/h3 trailing header support. Fixes #147
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffsawatzky committed Dec 7, 2023
1 parent 19dfb96 commit 3d991b4
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 4 deletions.
5 changes: 5 additions & 0 deletions src/hypercorn/protocol/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ class EndBody(Event):
pass


@dataclass(frozen=True)
class Trailers(Event):
headers: List[Tuple[bytes, bytes]]


@dataclass(frozen=True)
class Data(Event):
data: bytes
Expand Down
4 changes: 4 additions & 0 deletions src/hypercorn/protocol/h2.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
Request,
Response,
StreamClosed,
Trailers,
)
from .http_stream import HTTPStream
from .ws_stream import WSStream
Expand Down Expand Up @@ -212,6 +213,9 @@ async def stream_send(self, event: StreamEvent) -> None:
self.priority.unblock(event.stream_id)
await self.has_data.set()
await self.stream_buffers[event.stream_id].drain()
elif isinstance(event, Trailers):
self.connection.send_headers(event.stream_id, event.headers)
await self._flush()
elif isinstance(event, StreamClosed):
await self._close_stream(event.stream_id)
idle = len(self.streams) == 0 or all(
Expand Down
4 changes: 4 additions & 0 deletions src/hypercorn/protocol/h3.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
Request,
Response,
StreamClosed,
Trailers,
)
from .http_stream import HTTPStream
from .ws_stream import WSStream
Expand Down Expand Up @@ -79,6 +80,9 @@ async def stream_send(self, event: StreamEvent) -> None:
elif isinstance(event, (EndBody, EndData)):
self.connection.send_data(event.stream_id, b"", True)
await self.send()
elif isinstance(event, Trailers):
self.connection.send_headers(event.stream_id, event.headers)
await self.send()
elif isinstance(event, StreamClosed):
pass # ??
elif isinstance(event, Request):
Expand Down
50 changes: 47 additions & 3 deletions src/hypercorn/protocol/http_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,16 @@
from typing import Awaitable, Callable, Optional, Tuple
from urllib.parse import unquote

from .events import Body, EndBody, Event, InformationalResponse, Request, Response, StreamClosed
from .events import (
Body,
EndBody,
Event,
InformationalResponse,
Request,
Response,
StreamClosed,
Trailers,
)
from ..config import Config
from ..typing import (
AppWrapper,
Expand All @@ -22,6 +31,7 @@
valid_server_name,
)

TRAILERS_VERSIONS = {"2", "3"}
PUSH_VERSIONS = {"2", "3"}
EARLY_HINTS_VERSIONS = {"2", "3"}

Expand Down Expand Up @@ -88,6 +98,10 @@ async def handle(self, event: Event) -> None:
"server": self.server,
"extensions": {},
}

if event.http_version in TRAILERS_VERSIONS:
self.scope["extensions"]["http.response.trailers"] = {}

if event.http_version in PUSH_VERSIONS:
self.scope["extensions"]["http.response.push"] = {}

Expand Down Expand Up @@ -181,13 +195,43 @@ async def app_send(self, message: Optional[ASGISendEvent]) -> None:
)

if not message.get("more_body", False):
if self.state != ASGIHTTPState.CLOSED:
await self.send(EndBody(stream_id=self.stream_id))

if not self.response.get("trailers", False):
self.state = ASGIHTTPState.CLOSED
await self.config.log.access(
self.scope, self.response, time() - self.start_time
)
await self.send(EndBody(stream_id=self.stream_id))
await self.send(StreamClosed(stream_id=self.stream_id))
elif (
message["type"] == "http.response.trailers"
and self.scope["http_version"] in TRAILERS_VERSIONS
and self.state
in {
ASGIHTTPState.REQUEST,
ASGIHTTPState.RESPONSE,
}
):
if self.state == ASGIHTTPState.REQUEST:
headers = build_and_validate_headers(self.response.get("headers", []))
await self.send(
Response(
stream_id=self.stream_id,
headers=headers,
status_code=int(self.response["status"]),
)
)
self.state = ASGIHTTPState.RESPONSE

headers = build_and_validate_headers(message["headers"])
await self.send(Trailers(stream_id=self.stream_id, headers=headers))

if not message.get("more_trailers", False):
self.state = ASGIHTTPState.CLOSED
await self.config.log.access(
self.scope, self.response, time() - self.start_time
)
await self.send(StreamClosed(stream_id=self.stream_id))
else:
raise UnexpectedMessageError(self.state, message["type"])

Expand Down
8 changes: 8 additions & 0 deletions src/hypercorn/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ class HTTPResponseStartEvent(TypedDict):
type: Literal["http.response.start"]
status: int
headers: Iterable[Tuple[bytes, bytes]]
trailers: Optional[bool]


class HTTPResponseBodyEvent(TypedDict):
Expand All @@ -91,6 +92,12 @@ class HTTPResponseBodyEvent(TypedDict):
more_body: bool


class HTTPResponseTrailersEvent(TypedDict):
type: Literal["http.response.trailers"]
headers: Iterable[Tuple[bytes, bytes]]
more_trailers: bool


class HTTPServerPushEvent(TypedDict):
type: Literal["http.response.push"]
path: str
Expand Down Expand Up @@ -191,6 +198,7 @@ class LifespanShutdownFailedEvent(TypedDict):
ASGISendEvent = Union[
HTTPResponseStartEvent,
HTTPResponseBodyEvent,
HTTPResponseTrailersEvent,
HTTPServerPushEvent,
HTTPEarlyHintEvent,
HTTPDisconnectEvent,
Expand Down
6 changes: 5 additions & 1 deletion tests/protocol/test_http_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,11 @@ async def test_handle_request_http_2(stream: HTTPStream) -> None:
"headers": [],
"client": None,
"server": None,
"extensions": {"http.response.early_hint": {}, "http.response.push": {}},
"extensions": {
"http.response.trailers": {},
"http.response.early_hint": {},
"http.response.push": {},
},
}


Expand Down

0 comments on commit 3d991b4

Please sign in to comment.