|
| 1 | +from __future__ import annotations |
| 2 | +from logging import Logger |
| 3 | +from typing import Callable, Iterator, Optional, Union |
| 4 | +from urllib3 import PoolManager |
| 5 | + |
| 6 | +from ld_eventsource.http import _HttpClientImpl, _HttpConnectParams |
| 7 | + |
| 8 | + |
| 9 | +class ConnectStrategy: |
| 10 | + """ |
| 11 | + An abstraction for how :class:`.SSEClient` should obtain an input stream. |
| 12 | + |
| 13 | + The default implementation is :meth:`http()`, which makes HTTP requests with ``urllib3``. |
| 14 | + Or, if you want to consume an input stream from some other source, you can create your own |
| 15 | + subclass of :class:`ConnectStrategy`. |
| 16 | +
|
| 17 | + Instances of this class should be immutable and should not contain any state that is specific |
| 18 | + to one active stream. The :class:`ConnectionClient` that they produce is stateful and belongs |
| 19 | + to a single :class:`.SSEClient`. |
| 20 | + """ |
| 21 | + |
| 22 | + def create_client(self, logger: Logger) -> ConnectionClient: |
| 23 | + """ |
| 24 | + Creates a client instance. |
| 25 | +
|
| 26 | + This is called once when an :class:`.SSEClient` is created. The SSEClient returns the |
| 27 | + returned :class:`ConnectionClient` and uses it to perform all subsequent connection attempts. |
| 28 | +
|
| 29 | + :param logger: the logger being used by the SSEClient |
| 30 | + """ |
| 31 | + raise NotImplementedError("ConnectStrategy base class cannot be used by itself") |
| 32 | + |
| 33 | + @staticmethod |
| 34 | + def http( |
| 35 | + url: str, |
| 36 | + headers: Optional[dict]=None, |
| 37 | + pool: Optional[PoolManager]=None, |
| 38 | + urllib3_request_options: Optional[dict]=None |
| 39 | + ) -> ConnectStrategy: |
| 40 | + """ |
| 41 | + Creates the default HTTP implementation, specifying request parameters. |
| 42 | +
|
| 43 | + :param url: the stream URL |
| 44 | + :param headers: optional HTTP headers to add to the request |
| 45 | + :param pool: optional urllib3 ``PoolManager`` to provide an HTTP client |
| 46 | + :param urllib3_request_options: optional ``kwargs`` to add to the ``request`` call; these |
| 47 | + can include any parameters supported by ``urllib3``, such as ``timeout`` |
| 48 | + """ |
| 49 | + return _HttpConnectStrategy(_HttpConnectParams(url, headers, pool, urllib3_request_options)) |
| 50 | + |
| 51 | + |
| 52 | +class ConnectionClient: |
| 53 | + """ |
| 54 | + An object provided by :class:`.ConnectStrategy` that is retained by a single |
| 55 | + :class:`.SSEClient` to perform all connection attempts by that instance. |
| 56 | +
|
| 57 | + For the default HTTP implementation, this represents an HTTP connection pool. |
| 58 | + """ |
| 59 | + |
| 60 | + def connect(self, last_event_id: Optional[str]) -> ConnectionResult: |
| 61 | + """ |
| 62 | + Attempts to connect to a stream. Raises an exception if unsuccessful. |
| 63 | +
|
| 64 | + :param last_event_id: the current value of :attr:`SSEClient.last_event_id` |
| 65 | + (should be sent to the server to support resuming an interrupted stream) |
| 66 | + :return: a :class:`ConnectionResult` representing the stream |
| 67 | + """ |
| 68 | + raise NotImplementedError("ConnectionClient base class cannot be used by itself") |
| 69 | + |
| 70 | + def close(self): |
| 71 | + """ |
| 72 | + Does whatever is necessary to release resources when the SSEClient is closed. |
| 73 | + """ |
| 74 | + pass |
| 75 | + |
| 76 | + def __enter__(self): |
| 77 | + return self |
| 78 | + |
| 79 | + def __exit__(self, type, value, traceback): |
| 80 | + self.close() |
| 81 | + |
| 82 | + |
| 83 | + |
| 84 | +class ConnectionResult: |
| 85 | + """ |
| 86 | + The return type of :meth:`ConnectionClient.connect()`. |
| 87 | + """ |
| 88 | + def __init__( |
| 89 | + self, |
| 90 | + stream: Iterator[bytes], |
| 91 | + closer: Optional[Callable] |
| 92 | + ): |
| 93 | + self.__stream = stream |
| 94 | + self.__closer = closer |
| 95 | + |
| 96 | + @property |
| 97 | + def stream(self) -> Iterator[bytes]: |
| 98 | + """ |
| 99 | + An iterator that returns chunks of data. |
| 100 | + """ |
| 101 | + return self.__stream |
| 102 | + |
| 103 | + def close(self): |
| 104 | + """ |
| 105 | + Does whatever is necessary to release the connection. |
| 106 | + """ |
| 107 | + if self.__closer: |
| 108 | + self.__closer() |
| 109 | + self.__closer = None |
| 110 | + |
| 111 | + def __enter__(self): |
| 112 | + return self |
| 113 | + |
| 114 | + def __exit__(self, type, value, traceback): |
| 115 | + self.close() |
| 116 | + |
| 117 | + |
| 118 | +# _HttpConnectStrategy and _HttpConnectionClient are defined here rather than in http.py to avoid |
| 119 | +# a circular module reference. |
| 120 | + |
| 121 | +class _HttpConnectStrategy(ConnectStrategy): |
| 122 | + def __init__(self, params: _HttpConnectParams): |
| 123 | + self.__params = params |
| 124 | + |
| 125 | + def create_client(self, logger: Logger) -> ConnectionClient: |
| 126 | + return _HttpConnectionClient(self.__params, logger) |
| 127 | + |
| 128 | + |
| 129 | +class _HttpConnectionClient(ConnectionClient): |
| 130 | + def __init__(self, params: _HttpConnectParams, logger: Logger): |
| 131 | + self.__impl = _HttpClientImpl(params, logger) |
| 132 | + |
| 133 | + def connect(self, last_event_id: Optional[str]) -> ConnectionResult: |
| 134 | + stream, closer = self.__impl.connect(last_event_id) |
| 135 | + return ConnectionResult(stream, closer) |
| 136 | + |
| 137 | + def close(self): |
| 138 | + self.__impl.close() |
| 139 | + |
| 140 | + |
| 141 | +__all__ = ['ConnectStrategy', 'ConnectionClient', 'ConnectionResult'] |
0 commit comments