|
1 | 1 | import datetime as dt |
| 2 | +import logging |
2 | 3 | from collections.abc import Callable |
| 4 | +from os import PathLike |
| 5 | +import pathlib |
3 | 6 | from typing import Generic |
| 7 | +from typing import IO |
4 | 8 | from typing import TypedDict |
5 | 9 | from typing import TypeVar |
| 10 | +import warnings |
6 | 11 |
|
7 | 12 | import databento_dbn |
8 | 13 | import pandas as pd |
9 | 14 |
|
| 15 | +from databento.common.error import BentoWarning |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
10 | 18 |
|
11 | 19 | DBNRecord = ( |
12 | 20 | databento_dbn.BBOMsg |
|
32 | 40 | | databento_dbn.ErrorMsgV1 |
33 | 41 | ) |
34 | 42 |
|
35 | | -RecordCallback = Callable[[DBNRecord], None] |
36 | | -ExceptionCallback = Callable[[Exception], None] |
37 | | -ReconnectCallback = Callable[[pd.Timestamp, pd.Timestamp], None] |
38 | | - |
39 | 43 | _T = TypeVar("_T") |
40 | 44 |
|
41 | 45 |
|
@@ -88,3 +92,196 @@ class MappingIntervalDict(TypedDict): |
88 | 92 | start_date: dt.date |
89 | 93 | end_date: dt.date |
90 | 94 | symbol: str |
| 95 | + |
| 96 | + |
| 97 | +RecordCallback = Callable[[DBNRecord], None] |
| 98 | +ExceptionCallback = Callable[[Exception], None] |
| 99 | +ReconnectCallback = Callable[[pd.Timestamp, pd.Timestamp], None] |
| 100 | + |
| 101 | + |
| 102 | +class ClientStream: |
| 103 | + def __init__( |
| 104 | + self, |
| 105 | + stream: IO[bytes] | PathLike[str] | str, |
| 106 | + exc_fn: ExceptionCallback | None = None, |
| 107 | + max_warnings: int = 10, |
| 108 | + ) -> None: |
| 109 | + is_managed = False |
| 110 | + |
| 111 | + if isinstance(stream, (str, PathLike)): |
| 112 | + stream = pathlib.Path(stream).open("xb") |
| 113 | + is_managed = True |
| 114 | + |
| 115 | + if not hasattr(stream, "write"): |
| 116 | + raise ValueError(f"{type(stream).__name__} does not support write()") |
| 117 | + |
| 118 | + if not hasattr(stream, "writable") or not stream.writable(): |
| 119 | + raise ValueError(f"{type(stream).__name__} is not a writable stream") |
| 120 | + |
| 121 | + if exc_fn is not None and not callable(exc_fn): |
| 122 | + raise ValueError(f"{exc_fn} is not callable") |
| 123 | + |
| 124 | + self._stream = stream |
| 125 | + self._exc_fn = exc_fn |
| 126 | + self._max_warnings = max(0, max_warnings) |
| 127 | + self._warning_count = 0 |
| 128 | + self._is_managed = is_managed |
| 129 | + |
| 130 | + @property |
| 131 | + def stream_name(self) -> str: |
| 132 | + return getattr(self._stream, "__name__", str(self._stream)) |
| 133 | + |
| 134 | + @property |
| 135 | + def is_closed(self) -> bool: |
| 136 | + """ |
| 137 | + Return `True` if the underlying stream is closed. |
| 138 | +
|
| 139 | + Returns |
| 140 | + ------- |
| 141 | + bool |
| 142 | +
|
| 143 | + """ |
| 144 | + return self._stream.closed |
| 145 | + |
| 146 | + @property |
| 147 | + def is_managed(self) -> bool: |
| 148 | + """ |
| 149 | + Return `True` if the underlying stream was opened by the |
| 150 | + `ClientStream`. This can be used to determine if the stream should be |
| 151 | + closed automatically. |
| 152 | +
|
| 153 | + Returns |
| 154 | + ------- |
| 155 | + bool |
| 156 | +
|
| 157 | + """ |
| 158 | + return self._is_managed |
| 159 | + |
| 160 | + @property |
| 161 | + def exc_callback_name(self) -> str: |
| 162 | + return getattr(self._exc_fn, "__name__", str(self._exc_fn)) |
| 163 | + |
| 164 | + def close(self) -> None: |
| 165 | + """ |
| 166 | + Close the underlying stream. |
| 167 | + """ |
| 168 | + self._stream.close() |
| 169 | + |
| 170 | + def flush(self) -> None: |
| 171 | + """ |
| 172 | + Flush the underlying stream. |
| 173 | + """ |
| 174 | + self._stream.flush() |
| 175 | + |
| 176 | + def write(self, data: bytes) -> None: |
| 177 | + """ |
| 178 | + Write data to the underlying stream. Any exceptions encountered will be |
| 179 | + dispatched to the exception callback, if defined. |
| 180 | +
|
| 181 | + Parameters |
| 182 | + ---------- |
| 183 | + data : bytes |
| 184 | +
|
| 185 | + """ |
| 186 | + try: |
| 187 | + self._stream.write(data) |
| 188 | + except Exception as exc: |
| 189 | + if self._exc_fn is None: |
| 190 | + self._warn( |
| 191 | + f"stream '{self.stream_name}' encountered an exception without an exception handler: {repr(exc)}", |
| 192 | + ) |
| 193 | + else: |
| 194 | + try: |
| 195 | + self._exc_fn(exc) |
| 196 | + except Exception as inner_exc: |
| 197 | + self._warn( |
| 198 | + f"exception callback '{self.exc_callback_name}' encountered an exception: {repr(inner_exc)}", |
| 199 | + ) |
| 200 | + raise inner_exc from exc |
| 201 | + raise exc |
| 202 | + |
| 203 | + def _warn(self, msg: str) -> None: |
| 204 | + logger.warning(msg) |
| 205 | + if self._warning_count < self._max_warnings: |
| 206 | + self._warning_count += 1 |
| 207 | + warnings.warn( |
| 208 | + msg, |
| 209 | + BentoWarning, |
| 210 | + stacklevel=3, |
| 211 | + ) |
| 212 | + if self._warning_count == self._max_warnings: |
| 213 | + warnings.warn( |
| 214 | + f"suppressing further warnings for '{self.stream_name}'", |
| 215 | + BentoWarning, |
| 216 | + stacklevel=3, |
| 217 | + ) |
| 218 | + |
| 219 | + |
| 220 | +class ClientRecordCallback: |
| 221 | + def __init__( |
| 222 | + self, |
| 223 | + fn: RecordCallback, |
| 224 | + exc_fn: ExceptionCallback | None = None, |
| 225 | + max_warnings: int = 10, |
| 226 | + ) -> None: |
| 227 | + if not callable(fn): |
| 228 | + raise ValueError(f"{fn} is not callable") |
| 229 | + if exc_fn is not None and not callable(exc_fn): |
| 230 | + raise ValueError(f"{exc_fn} is not callable") |
| 231 | + |
| 232 | + self._fn = fn |
| 233 | + self._exc_fn = exc_fn |
| 234 | + self._max_warnings = max(0, max_warnings) |
| 235 | + self._warning_count = 0 |
| 236 | + |
| 237 | + @property |
| 238 | + def callback_name(self) -> str: |
| 239 | + return getattr(self._fn, "__name__", str(self._fn)) |
| 240 | + |
| 241 | + @property |
| 242 | + def exc_callback_name(self) -> str: |
| 243 | + return getattr(self._exc_fn, "__name__", str(self._exc_fn)) |
| 244 | + |
| 245 | + def call(self, record: DBNRecord) -> None: |
| 246 | + """ |
| 247 | + Execute the callback function, passing `record` in as the first |
| 248 | + argument. Any exceptions encountered will be dispatched to the |
| 249 | + exception callback, if defined. |
| 250 | +
|
| 251 | + Parameters |
| 252 | + ---------- |
| 253 | + record : DBNRecord |
| 254 | +
|
| 255 | + """ |
| 256 | + try: |
| 257 | + self._fn(record) |
| 258 | + except Exception as exc: |
| 259 | + if self._exc_fn is None: |
| 260 | + self._warn( |
| 261 | + f"callback '{self.callback_name}' encountered an exception without an exception callback: {repr(exc)}", |
| 262 | + ) |
| 263 | + else: |
| 264 | + try: |
| 265 | + self._exc_fn(exc) |
| 266 | + except Exception as inner_exc: |
| 267 | + self._warn( |
| 268 | + f"exception callback '{self.exc_callback_name}' encountered an exception: {repr(inner_exc)}", |
| 269 | + ) |
| 270 | + raise inner_exc from exc |
| 271 | + raise exc |
| 272 | + |
| 273 | + def _warn(self, msg: str) -> None: |
| 274 | + logger.warning(msg) |
| 275 | + if self._warning_count < self._max_warnings: |
| 276 | + self._warning_count += 1 |
| 277 | + warnings.warn( |
| 278 | + msg, |
| 279 | + BentoWarning, |
| 280 | + stacklevel=3, |
| 281 | + ) |
| 282 | + if self._warning_count == self._max_warnings: |
| 283 | + warnings.warn( |
| 284 | + f"suppressing further warnings for '{self.callback_name}'", |
| 285 | + BentoWarning, |
| 286 | + stacklevel=3, |
| 287 | + ) |
0 commit comments