|
| 1 | +"""Adapt byte sources for business logic shared by sync and async APIs. |
| 2 | +
|
| 3 | +Shared code consumes the async-shaped ``ReadableByteStream`` and |
| 4 | +``StagingByteFile`` protocols. Callers select the runtime matching their public |
| 5 | +API, then use its factories instead of constructing the private adapters directly. |
| 6 | +The sync runtime never suspends, while the async runtime awaits or offloads I/O as |
| 7 | +appropriate. |
| 8 | +""" |
| 9 | + |
| 10 | +import inspect |
| 11 | +import io |
| 12 | +import tempfile |
| 13 | +from collections.abc import AsyncIterator |
| 14 | +from contextlib import AbstractAsyncContextManager, asynccontextmanager |
| 15 | +from typing import Protocol, TypeAlias, cast |
| 16 | + |
| 17 | +import anyio |
| 18 | +from typing_extensions import Buffer |
| 19 | + |
| 20 | + |
| 21 | +class SyncByteReader(Protocol): |
| 22 | + """Caller-provided byte source with a blocking ``read`` method.""" |
| 23 | + |
| 24 | + def read(self, size: int = -1, /) -> bytes: ... |
| 25 | + |
| 26 | + |
| 27 | +class AsyncByteReader(Protocol): |
| 28 | + """Caller-provided byte source with an asynchronous ``read`` method. |
| 29 | +
|
| 30 | + This is structurally identical to ``ReadableByteStream`` but describes an |
| 31 | + input that has not yet been normalized by a byte-stream runtime. |
| 32 | + """ |
| 33 | + |
| 34 | + async def read(self, size: int = -1, /) -> bytes: ... |
| 35 | + |
| 36 | + |
| 37 | +BytesLike: TypeAlias = bytes | bytearray | memoryview |
| 38 | +SyncByteSource: TypeAlias = BytesLike | SyncByteReader |
| 39 | +AsyncByteSource: TypeAlias = AsyncByteReader |
| 40 | +RawByteSource: TypeAlias = SyncByteSource | AsyncByteSource |
| 41 | + |
| 42 | + |
| 43 | +class ReadableByteStream(Protocol): |
| 44 | + """Normalized readable stream consumed by shared internal workflows. |
| 45 | +
|
| 46 | + Its async shape hides whether a runtime performs the read inline, awaits an |
| 47 | + async source, or moves a blocking read to a worker thread. |
| 48 | + """ |
| 49 | + |
| 50 | + async def read(self, size: int = -1, /) -> bytes: ... |
| 51 | + |
| 52 | + |
| 53 | +class StagingByteFile(ReadableByteStream, Protocol): |
| 54 | + """SDK-owned temporary byte file used by shared staging workflows. |
| 55 | +
|
| 56 | + The runtime's temporary-file context manager owns the lifetime of streams |
| 57 | + implementing this protocol. |
| 58 | + """ |
| 59 | + |
| 60 | + async def write(self, data: bytes, /) -> int: ... |
| 61 | + |
| 62 | + async def readinto(self, buffer: Buffer, /) -> int: |
| 63 | + """Read bytes into a writable buffer. |
| 64 | +
|
| 65 | + ``Buffer`` cannot express mutability, so read-only buffers are rejected |
| 66 | + at runtime. |
| 67 | + """ |
| 68 | + ... |
| 69 | + |
| 70 | + async def flush(self) -> None: ... |
| 71 | + |
| 72 | + async def tell(self) -> int: ... |
| 73 | + |
| 74 | + async def seek(self, offset: int, whence: int = 0, /) -> int: ... |
| 75 | + |
| 76 | + async def truncate(self, size: int | None = None, /) -> int: ... |
| 77 | + |
| 78 | + |
| 79 | +class StagingFileRuntime(Protocol): |
| 80 | + """Runtime-specific temporary-file capability for shared business logic.""" |
| 81 | + |
| 82 | + def temporary_file(self) -> AbstractAsyncContextManager[StagingByteFile]: ... |
| 83 | + |
| 84 | + |
| 85 | +def _bytes_result(value: object) -> bytes: |
| 86 | + if isinstance(value, bytes): |
| 87 | + return value |
| 88 | + raise TypeError(f"byte stream returned {type(value).__name__}, expected bytes") |
| 89 | + |
| 90 | + |
| 91 | +class _SyncReader: |
| 92 | + """Expose a blocking reader through an async-shaped, non-suspending method.""" |
| 93 | + |
| 94 | + def __init__(self, source: SyncByteReader) -> None: |
| 95 | + self._source = source |
| 96 | + |
| 97 | + async def read(self, size: int = -1, /) -> bytes: |
| 98 | + return _bytes_result(self._source.read(size)) |
| 99 | + |
| 100 | + |
| 101 | +class _MemoryReader: |
| 102 | + """Give an immutable bytes snapshot a stateful, non-suspending read cursor.""" |
| 103 | + |
| 104 | + def __init__(self, data: BytesLike) -> None: |
| 105 | + self._data = memoryview(bytes(data)) |
| 106 | + self._offset = 0 |
| 107 | + |
| 108 | + async def read(self, size: int = -1, /) -> bytes: |
| 109 | + remaining = self._data[self._offset :] |
| 110 | + if size < 0: |
| 111 | + self._offset = len(self._data) |
| 112 | + return bytes(remaining) |
| 113 | + chunk = bytes(remaining[:size]) |
| 114 | + self._offset += len(chunk) |
| 115 | + return chunk |
| 116 | + |
| 117 | + |
| 118 | +class _AsyncReader: |
| 119 | + """Normalize a genuinely asynchronous reader and validate its results.""" |
| 120 | + |
| 121 | + def __init__(self, source: AsyncByteReader) -> None: |
| 122 | + self._source = source |
| 123 | + |
| 124 | + async def read(self, size: int = -1, /) -> bytes: |
| 125 | + return _bytes_result(await self._source.read(size)) |
| 126 | + |
| 127 | + |
| 128 | +class _ThreadedSyncReader: |
| 129 | + """Run a blocking reader on a worker thread for use by async workflows.""" |
| 130 | + |
| 131 | + def __init__(self, source: SyncByteReader) -> None: |
| 132 | + self._source = source |
| 133 | + |
| 134 | + async def read(self, size: int = -1, /) -> bytes: |
| 135 | + return _bytes_result(await anyio.to_thread.run_sync(self._source.read, size)) |
| 136 | + |
| 137 | + |
| 138 | +class _SyncTemporaryFile: |
| 139 | + """Expose a blocking temporary file through non-suspending async methods.""" |
| 140 | + |
| 141 | + def __init__(self) -> None: |
| 142 | + self._file = cast(io.BufferedRandom, tempfile.TemporaryFile("w+b")) |
| 143 | + |
| 144 | + def _ensure_open(self) -> None: |
| 145 | + if self._file.closed: |
| 146 | + raise anyio.ClosedResourceError |
| 147 | + |
| 148 | + async def read(self, size: int = -1, /) -> bytes: |
| 149 | + self._ensure_open() |
| 150 | + return self._file.read(size) |
| 151 | + |
| 152 | + async def write(self, data: bytes, /) -> int: |
| 153 | + self._ensure_open() |
| 154 | + return self._file.write(data) |
| 155 | + |
| 156 | + async def readinto(self, buffer: Buffer, /) -> int: |
| 157 | + """Read bytes into a writable buffer. |
| 158 | +
|
| 159 | + ``Buffer`` cannot express mutability, so read-only buffers are rejected |
| 160 | + at runtime. |
| 161 | + """ |
| 162 | + self._ensure_open() |
| 163 | + return self._file.readinto(buffer) |
| 164 | + |
| 165 | + async def flush(self) -> None: |
| 166 | + self._ensure_open() |
| 167 | + self._file.flush() |
| 168 | + |
| 169 | + async def tell(self) -> int: |
| 170 | + self._ensure_open() |
| 171 | + return self._file.tell() |
| 172 | + |
| 173 | + async def seek(self, offset: int, whence: int = 0, /) -> int: |
| 174 | + self._ensure_open() |
| 175 | + return self._file.seek(offset, whence) |
| 176 | + |
| 177 | + async def truncate(self, size: int | None = None, /) -> int: |
| 178 | + self._ensure_open() |
| 179 | + return self._file.truncate(size) |
| 180 | + |
| 181 | + def close(self) -> None: |
| 182 | + self._file.close() |
| 183 | + |
| 184 | + |
| 185 | +@asynccontextmanager |
| 186 | +async def _sync_temporary_file() -> AsyncIterator[StagingByteFile]: |
| 187 | + file = _SyncTemporaryFile() |
| 188 | + try: |
| 189 | + yield file |
| 190 | + finally: |
| 191 | + file.close() |
| 192 | + |
| 193 | + |
| 194 | +class SyncByteStreamRuntime: |
| 195 | + """Adapt blocking byte primitives for shared async-shaped workflows. |
| 196 | +
|
| 197 | + Every operation completes without suspending so sync entry points can drive |
| 198 | + the shared coroutine with ``iter_coroutine`` and no event loop. |
| 199 | + """ |
| 200 | + |
| 201 | + @staticmethod |
| 202 | + def reader(source: SyncByteSource) -> ReadableByteStream: |
| 203 | + if isinstance(source, (bytes, bytearray, memoryview)): |
| 204 | + return _MemoryReader(source) |
| 205 | + read = getattr(source, "read", None) |
| 206 | + if not callable(read): |
| 207 | + raise TypeError("byte source must provide a callable read method") |
| 208 | + if inspect.iscoroutinefunction(read): |
| 209 | + raise TypeError("sync byte stream runtime does not support async readers") |
| 210 | + return _SyncReader(cast(SyncByteReader, source)) |
| 211 | + |
| 212 | + def temporary_file(self) -> AbstractAsyncContextManager[StagingByteFile]: |
| 213 | + return _sync_temporary_file() |
| 214 | + |
| 215 | + |
| 216 | +class AsyncByteStreamRuntime: |
| 217 | + """Adapt byte primitives for execution under AnyIO. |
| 218 | +
|
| 219 | + Async readers are awaited directly, while blocking readers run on a worker |
| 220 | + thread so they do not block the event loop. |
| 221 | + """ |
| 222 | + |
| 223 | + @staticmethod |
| 224 | + def reader(source: RawByteSource) -> ReadableByteStream: |
| 225 | + if isinstance(source, (bytes, bytearray, memoryview)): |
| 226 | + return _MemoryReader(source) |
| 227 | + read = getattr(source, "read", None) |
| 228 | + if not callable(read): |
| 229 | + raise TypeError("byte source must provide a callable read method") |
| 230 | + if inspect.iscoroutinefunction(read): |
| 231 | + return _AsyncReader(cast(AsyncByteReader, source)) |
| 232 | + return _ThreadedSyncReader(cast(SyncByteReader, source)) |
| 233 | + |
| 234 | + def temporary_file(self) -> AbstractAsyncContextManager[StagingByteFile]: |
| 235 | + return cast( |
| 236 | + AbstractAsyncContextManager[StagingByteFile], |
| 237 | + anyio.TemporaryFile("w+b"), |
| 238 | + ) |
| 239 | + |
| 240 | + |
| 241 | +__all__ = [ |
| 242 | + "AsyncByteReader", |
| 243 | + "AsyncByteSource", |
| 244 | + "AsyncByteStreamRuntime", |
| 245 | + "BytesLike", |
| 246 | + "RawByteSource", |
| 247 | + "ReadableByteStream", |
| 248 | + "StagingByteFile", |
| 249 | + "StagingFileRuntime", |
| 250 | + "SyncByteReader", |
| 251 | + "SyncByteSource", |
| 252 | + "SyncByteStreamRuntime", |
| 253 | +] |
0 commit comments