| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import Any, Awaitable, Callable, Optional, Tuple, Union |
| 4 |
|
| 5 |
from .h2 import H2Protocol |
| 6 |
from .h11 import H2CProtocolRequiredError, H2ProtocolAssumedError, H11Protocol |
| 7 |
from ..config import Config |
| 8 |
from ..events import Event, RawData |
| 9 |
from ..typing import AppWrapper, TaskGroup, WorkerContext |
| 10 |
|
| 11 |
|
| 12 |
class ProtocolWrapper: |
| 13 |
def __init__( |
| 14 |
self, |
| 15 |
app: AppWrapper, |
| 16 |
config: Config, |
| 17 |
context: WorkerContext, |
| 18 |
task_group: TaskGroup, |
| 19 |
tls: Optional[dict[str, Any]], |
| 20 |
client: Optional[Tuple[str, int]], |
| 21 |
server: Optional[Tuple[str, int]], |
| 22 |
send: Callable[[Event], Awaitable[None]], |
| 23 |
alpn_protocol: Optional[str] = None, |
| 24 |
transport=None, |
| 25 |
) -> None: |
| 26 |
self.app = app |
| 27 |
self.config = config |
| 28 |
self.context = context |
| 29 |
self.task_group = task_group |
| 30 |
self.tls = tls |
| 31 |
self.client = client |
| 32 |
self.server = server |
| 33 |
self.send = send |
| 34 |
self.protocol: Union[H11Protocol, H2Protocol] |
| 35 |
self.transport = transport |
| 36 |
if alpn_protocol == "h2": |
| 37 |
self.protocol = H2Protocol( |
| 38 |
self.app, |
| 39 |
self.config, |
| 40 |
self.context, |
| 41 |
self.task_group, |
| 42 |
self.tls, |
| 43 |
self.client, |
| 44 |
self.server, |
| 45 |
self.send, |
| 46 |
self.transport, |
| 47 |
) |
| 48 |
else: |
| 49 |
self.protocol = H11Protocol( |
| 50 |
self.app, |
| 51 |
self.config, |
| 52 |
self.context, |
| 53 |
self.task_group, |
| 54 |
self.tls, |
| 55 |
self.client, |
| 56 |
self.server, |
| 57 |
self.send, |
| 58 |
self.transport, |
| 59 |
) |
| 60 |
|
| 61 |
async def initiate(self) -> None: |
| 62 |
return await self.protocol.initiate() |
| 63 |
|
| 64 |
async def handle(self, event: Event) -> None: |
| 65 |
try: |
| 66 |
return await self.protocol.handle(event) |
| 67 |
except H2ProtocolAssumedError as error: |
| 68 |
self.protocol = H2Protocol( |
| 69 |
self.app, |
| 70 |
self.config, |
| 71 |
self.context, |
| 72 |
self.task_group, |
| 73 |
self.tls, |
| 74 |
self.client, |
| 75 |
self.server, |
| 76 |
self.send, |
| 77 |
) |
| 78 |
await self.protocol.initiate() |
| 79 |
if error.data != b"": |
| 80 |
return await self.protocol.handle(RawData(data=error.data)) |
| 81 |
except H2CProtocolRequiredError as error: |
| 82 |
self.protocol = H2Protocol( |
| 83 |
self.app, |
| 84 |
self.config, |
| 85 |
self.context, |
| 86 |
self.task_group, |
| 87 |
self.tls, |
| 88 |
self.client, |
| 89 |
self.server, |
| 90 |
self.send, |
| 91 |
) |
| 92 |
await self.protocol.initiate(error.headers, error.settings) |
| 93 |
if error.data != b"": |
| 94 |
return await self.protocol.handle(RawData(data=error.data)) |