|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | | -import asyncio |
4 | | -from typing import TYPE_CHECKING, TypeVar, cast |
| 3 | +from contextvars import ContextVar |
| 4 | +from random import Random |
| 5 | +from typing import TYPE_CHECKING, TypeVar, cast, final |
5 | 6 |
|
6 | 7 | from typing_extensions import overload |
7 | 8 |
|
8 | | -from duron.event_loop import EventLoop |
9 | 9 | from duron.ops import FnCall |
10 | 10 |
|
11 | 11 | if TYPE_CHECKING: |
12 | 12 | from collections.abc import Awaitable, Callable |
| 13 | + from contextvars import Token |
| 14 | + from inspect import Traceback |
| 15 | + |
| 16 | + from duron.event_loop import EventLoop |
13 | 17 |
|
14 | 18 | _T = TypeVar("_T") |
15 | 19 |
|
| 20 | +_context: ContextVar[Context | None] = ContextVar("duron_context", default=None) |
| 21 | + |
16 | 22 |
|
| 23 | +@final |
17 | 24 | class Context: |
18 | | - def __init__(self): |
19 | | - loop = asyncio.get_event_loop() |
20 | | - assert isinstance(loop, EventLoop) |
| 25 | + def __init__(self, loop: EventLoop) -> None: |
21 | 26 | self._loop: EventLoop = loop |
22 | | - pass |
| 27 | + self._token: Token[Context | None] | None = None |
| 28 | + |
| 29 | + def __enter__(self) -> Context: |
| 30 | + token = _context.set(self) |
| 31 | + self._token = token |
| 32 | + return self |
| 33 | + |
| 34 | + def __exit__( |
| 35 | + self, |
| 36 | + exc_type: type[BaseException] | None, |
| 37 | + exc_val: BaseException | None, |
| 38 | + exc_tb: Traceback | None, |
| 39 | + ): |
| 40 | + if self._token: |
| 41 | + _context.reset(self._token) |
| 42 | + |
| 43 | + @classmethod |
| 44 | + def current(cls) -> Context: |
| 45 | + ctx = _context.get() |
| 46 | + if ctx is None: |
| 47 | + raise RuntimeError("No duron context is active") |
| 48 | + return ctx |
23 | 49 |
|
24 | 50 | @overload |
25 | | - async def run(self, fn: Callable[[], Awaitable[_T]]) -> _T: ... |
| 51 | + async def run(self, fn: Callable[[], Awaitable[_T]], /) -> _T: ... |
26 | 52 | @overload |
27 | | - async def run(self, fn: Callable[[], _T]) -> _T: ... |
28 | | - async def run(self, fn: Callable[[], Awaitable[_T] | _T]) -> _T: |
| 53 | + async def run(self, fn: Callable[[], _T], /) -> _T: ... |
| 54 | + async def run( |
| 55 | + self, |
| 56 | + fn: Callable[[], Awaitable[_T] | _T], |
| 57 | + /, |
| 58 | + ) -> _T: |
29 | 59 | return cast("_T", await self._loop.create_op(FnCall(callable=fn))) |
30 | 60 |
|
| 61 | + def time(self) -> float: |
| 62 | + return self._loop.time() |
| 63 | + |
| 64 | + def time_ns(self) -> int: |
| 65 | + return self._loop.time_ns() |
31 | 66 |
|
32 | | -def get_context() -> Context: |
33 | | - """ |
34 | | - Get the current duron execution context. |
35 | | - """ |
36 | | - return Context() |
| 67 | + def random(self) -> Random: |
| 68 | + return Random(self._loop.generate_op_id()) |
0 commit comments