|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from typing import ( |
| 5 | + TYPE_CHECKING, |
| 6 | + Concatenate, |
| 7 | + Generic, |
| 8 | + ParamSpec, |
| 9 | + Protocol, |
| 10 | + TypeVar, |
| 11 | + cast, |
| 12 | + final, |
| 13 | +) |
| 14 | + |
| 15 | +from typing_extensions import override |
| 16 | + |
| 17 | +from duron.ops import FnCall, StreamClose, StreamCreate, StreamEmit |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + from collections.abc import AsyncGenerator, Callable |
| 21 | + |
| 22 | + from duron.event_loop import EventLoop |
| 23 | + |
| 24 | + _P = ParamSpec("_P") |
| 25 | + |
| 26 | +_In = TypeVar("_In", contravariant=True) |
| 27 | +_Out = TypeVar("_Out", covariant=True) |
| 28 | + |
| 29 | + |
| 30 | +class Observer(Generic[_In], Protocol): |
| 31 | + def on_next(self, value: _In, /) -> None: ... |
| 32 | + def on_close(self, error: BaseException | None, /) -> None: ... |
| 33 | + |
| 34 | + |
| 35 | +class AmbientRawStream(Protocol[_In]): |
| 36 | + async def send(self, value: _In, /) -> None: ... |
| 37 | + |
| 38 | + async def close(self, error: BaseException | None = None, /) -> None: ... |
| 39 | + |
| 40 | + |
| 41 | +@final |
| 42 | +class RawStream(Generic[_In]): |
| 43 | + def __init__(self, id: str, loop: EventLoop) -> None: |
| 44 | + self._stream_id = id |
| 45 | + self._loop = loop |
| 46 | + self._target_loop: asyncio.AbstractEventLoop | None = None |
| 47 | + self._event = asyncio.Event() |
| 48 | + |
| 49 | + async def send(self, value: _In, /) -> None: |
| 50 | + _ = await self._loop.create_op( |
| 51 | + StreamEmit(stream_id=self._stream_id, value=value), |
| 52 | + loop=self._target_loop, |
| 53 | + ) |
| 54 | + |
| 55 | + async def close(self, error: BaseException | None = None, /) -> None: |
| 56 | + _ = await self._loop.create_op( |
| 57 | + StreamClose(stream_id=self._stream_id, exception=error), |
| 58 | + loop=self._target_loop, |
| 59 | + ) |
| 60 | + self._event.set() |
| 61 | + |
| 62 | + async def wait(self) -> None: |
| 63 | + _ = await self._event.wait() |
| 64 | + |
| 65 | + def to_ambient(self) -> AmbientRawStream[_In]: |
| 66 | + s: RawStream[_In] = RawStream(self._stream_id, self._loop) |
| 67 | + s._target_loop = self._loop.ambient_loop() |
| 68 | + return s |
| 69 | + |
| 70 | + |
| 71 | +@final |
| 72 | +class _StreamObserver(Generic[_In, _Out], Observer[_In]): |
| 73 | + def __init__(self, initial: _Out, reducer: Callable[[_Out, _In], _Out]): |
| 74 | + self.current = initial |
| 75 | + self.enable = True |
| 76 | + self._reducer = reducer |
| 77 | + self.data: list[_Out] = [] |
| 78 | + self.closed: bool | BaseException = False |
| 79 | + |
| 80 | + @override |
| 81 | + def on_next(self, val: _In): |
| 82 | + if self.enable: |
| 83 | + self.current = self._reducer(self.current, val) |
| 84 | + self.data.append(self.current) |
| 85 | + |
| 86 | + @override |
| 87 | + def on_close(self, exc: BaseException | None): |
| 88 | + self.closed = True if exc is None else exc |
| 89 | + |
| 90 | + |
| 91 | +@final |
| 92 | +class StreamTask(Generic[_In, _Out]): |
| 93 | + def __init__( |
| 94 | + self, |
| 95 | + loop: EventLoop, |
| 96 | + initial: _Out, |
| 97 | + reducer: Callable[[_Out, _In], _Out], |
| 98 | + fn: Callable[Concatenate[_Out, _P], AsyncGenerator[_In, _Out]], |
| 99 | + /, |
| 100 | + *args: _P.args, |
| 101 | + **kwargs: _P.kwargs, |
| 102 | + ) -> None: |
| 103 | + self._loop = loop |
| 104 | + self._reducer = reducer |
| 105 | + self._fn = fn |
| 106 | + self._args = args |
| 107 | + self._kwargs = kwargs |
| 108 | + self._obs = _StreamObserver(initial, self._reducer) |
| 109 | + self._op = self._loop.create_op( |
| 110 | + StreamCreate(observer=cast("Observer[object]", self._obs)) |
| 111 | + ) |
| 112 | + self._queue: asyncio.Queue[tuple[_Out] | None | BaseException] = ( |
| 113 | + self._setup_stream() |
| 114 | + ) |
| 115 | + |
| 116 | + def __aiter__(self) -> StreamTask[_In, _Out]: |
| 117 | + return self |
| 118 | + |
| 119 | + async def __anext__(self) -> _Out: |
| 120 | + item = await self._queue.get() |
| 121 | + if item is None: |
| 122 | + raise StopAsyncIteration |
| 123 | + if isinstance(item, BaseException): |
| 124 | + raise item |
| 125 | + return item[0] |
| 126 | + |
| 127 | + async def discard(self) -> None: |
| 128 | + async for _ in self: |
| 129 | + ... |
| 130 | + |
| 131 | + def _setup_stream(self) -> asyncio.Queue[tuple[_Out] | None | BaseException]: |
| 132 | + queue: asyncio.Queue[tuple[_Out] | None | BaseException] = asyncio.Queue() |
| 133 | + |
| 134 | + async def worker(): |
| 135 | + stream = cast("RawStream[_In]", await self._op).to_ambient() |
| 136 | + try: |
| 137 | + state = self._obs.current |
| 138 | + self._obs.enable = False |
| 139 | + |
| 140 | + for d in self._obs.data: |
| 141 | + await queue.put((d,)) |
| 142 | + if self._obs.closed is True: |
| 143 | + return |
| 144 | + elif isinstance(self._obs.closed, BaseException): |
| 145 | + raise self._obs.closed |
| 146 | + |
| 147 | + gen = self._fn(state, *self._args, **self._kwargs) |
| 148 | + state_partial = await gen.__anext__() |
| 149 | + |
| 150 | + while True: |
| 151 | + state = self._reducer(state, state_partial) |
| 152 | + await stream.send(state_partial) |
| 153 | + await queue.put((state,)) |
| 154 | + state_partial = await gen.asend(state) |
| 155 | + except StopAsyncIteration as _e: |
| 156 | + await stream.close() |
| 157 | + except BaseException as e: |
| 158 | + await queue.put(e) |
| 159 | + raise |
| 160 | + finally: |
| 161 | + await queue.put(None) |
| 162 | + |
| 163 | + _ = self._loop.create_op( |
| 164 | + FnCall(callable=worker, args=(), kwargs={}, return_type=None) |
| 165 | + ) |
| 166 | + return queue |
0 commit comments