fr-async 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fr_async/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ """Cooperative asynchronous programming with generators and yielded messages."""
2
+
3
+ from .classes import File, Task, TaskGroup, Yieldable
4
+ from .loop import ExecutionLoop, getEventLoop
5
+ from .scheduler import EEVDFScheduler
6
+ from . import messages
7
+
8
+ __all__ = [
9
+ 'EEVDFScheduler',
10
+ 'ExecutionLoop',
11
+ 'File',
12
+ 'Task',
13
+ 'TaskGroup',
14
+ 'Yieldable',
15
+ 'getEventLoop',
16
+ 'messages'
17
+ ]
fr_async/__main__.py ADDED
@@ -0,0 +1,30 @@
1
+
2
+
3
+ from typing import Any
4
+
5
+ from .classes import Task, Yieldable
6
+ from .loop import ExecutionLoop
7
+ from .messages import *
8
+ from .scheduler import EEVDFScheduler
9
+
10
+
11
+ def gen():
12
+ yield Sleep(1)
13
+ print('1')
14
+ yield Sleep(1)
15
+ print('2')
16
+ yield Sleep(1)
17
+ print('3')
18
+
19
+ def main() -> Any:
20
+ yield Task(gen(), background=True)
21
+ print('a')
22
+ yield Sleep(1)
23
+ print('b')
24
+ yield Sleep(1)
25
+ print('c')
26
+ yield Sleep(1)
27
+ print('d')
28
+
29
+ loop: ExecutionLoop = ExecutionLoop(EEVDFScheduler)
30
+ loop.run(Yieldable(main))
fr_async/classes.py ADDED
@@ -0,0 +1,330 @@
1
+ import inspect
2
+ import os
3
+ from collections import deque
4
+ from collections.abc import Callable, Generator
5
+ from contextvars import Context, copy_context
6
+ from os import PathLike
7
+ from typing import IO, Any, Final, Literal, Self, TypeIs, overload
8
+
9
+ lazy from .loop import getEventLoop
10
+ lazy from .messages import (
11
+ FileRead,
12
+ FileWrite,
13
+ Message,
14
+ TaskGroupAsCompleted,
15
+ TaskGroupCollect,
16
+ TaskJoin,
17
+ check_resolved,
18
+ )
19
+ lazy from .utils import log
20
+
21
+
22
+ class _Missing:
23
+ """Sentinel type used to distinguish a missing value."""
24
+ __slots__ = ()
25
+
26
+ _MISSING = _Missing()
27
+
28
+ class Assignable:
29
+ 'Store arbitrary data and expose entries as attributes.'
30
+ __slots__ = ('_data',)
31
+
32
+ def __init__(self) -> None:
33
+ 'Create an empty attribute store.'
34
+ self._data: dict[Any, Any] = {}
35
+
36
+ def __setattr__(self, name: str, value: Any) -> None:
37
+ 'Store user attributes in the internal mapping.'
38
+ if name == '_data':
39
+ return super().__setattr__(name, value)
40
+
41
+ self._data[name] = value
42
+ return None
43
+
44
+ def __getattr__(self, name: str):
45
+ 'Look up an attribute in the internal mapping.'
46
+ try:
47
+ return self._data[name]
48
+ except KeyError:
49
+ raise AttributeError(name) from None
50
+
51
+ def update(self, data: dict[Any, Any]):
52
+ 'Merge entries into the attribute store.'
53
+ self._data |= data
54
+
55
+ def _is_generator(x: Any) -> TypeIs[Generator[Any, Any, Any]]:
56
+ 'Return whether a value is a generator object.'
57
+ return inspect.isgenerator(x)
58
+
59
+ # Tasks
60
+ class Task[T=Any]:
61
+ 'Represent a callable or generator managed by the event loop.'
62
+ __slots__ = (
63
+ '_context',
64
+ '_joiners',
65
+ '_return_val',
66
+ '_stop_requested',
67
+ '_throw_val',
68
+ '_timeout_deadline',
69
+ '_timeout_expired',
70
+ '_timeout_started',
71
+ 'args',
72
+ 'background',
73
+ 'data',
74
+ 'done',
75
+ 'exception',
76
+ 'func',
77
+ 'immediate',
78
+ 'kwargs',
79
+ 'parent',
80
+ 'result',
81
+ 'timeout',
82
+ 'wait_for',
83
+ )
84
+
85
+ def __init__(self, func: Generator[Any, Any, T] | Callable[..., T], *args: Any, background=False, immediate=False, parent: Task | None = None, data: dict[Any, Any] | None = None, timeout: float | None = None, **kwargs: Any):
86
+ 'Initialize the task and its optional timeout, measured from its first run.'
87
+ if timeout is not None and timeout < 0:
88
+ raise ValueError('Task timeout must be non-negative.')
89
+
90
+ self.func: Generator[Any, Any, Any] | Callable[..., Any] = func
91
+ self.immediate = immediate
92
+ self.background = background
93
+
94
+ self.args = args
95
+ self.kwargs = kwargs
96
+
97
+ self.parent: Task | None = parent
98
+ self.done = False
99
+ self.result: Any = None
100
+ self.exception: BaseException | None = None
101
+ self.timeout = timeout
102
+ self._timeout_deadline: float | None = None
103
+ self._timeout_started = False
104
+ self._timeout_expired = False
105
+ self._joiners: list[tuple[Message, Task]] = []
106
+
107
+ self.data = Assignable()
108
+ self.data.update(data or {})
109
+
110
+ self._stop_requested = False
111
+ self._return_val: Any = _MISSING
112
+ self._throw_val: Any = _MISSING
113
+
114
+ self.wait_for: deque[Message] = deque()
115
+ self._context: Context = copy_context()
116
+
117
+ def __call__(self) -> T | None:
118
+ 'Advance the generator or invoke the callable and return its yielded value.'
119
+ if self._stop_requested:
120
+ if _is_generator(self.func):
121
+ self.func.close()
122
+
123
+ self.done = True
124
+ self.result = None
125
+ return None
126
+
127
+ if _is_generator(self.func):
128
+ try:
129
+ if isinstance(self._throw_val, BaseException):
130
+ exc = self._throw_val
131
+ self._throw_val = _MISSING
132
+ self._timeout_expired = False
133
+ return self.func.throw(exc)
134
+
135
+ if self._return_val is not _MISSING:
136
+ value = self._return_val
137
+ self._return_val = _MISSING
138
+ return self.func.send(value)
139
+
140
+ return next(self.func)
141
+
142
+ except StopIteration as e:
143
+ self.done = True
144
+ self.result = e.value
145
+ return e.value
146
+
147
+ result = self.func(*self.args, **self.kwargs)
148
+ self.done = True
149
+ self.result = result
150
+ return result
151
+
152
+ def __repr__(self) -> str:
153
+ 'Return a readable representation of the task.'
154
+ name: str = getattr(self.func, '__name__', str(self.func))
155
+ return f"Task({name}, {self.args}, {self.kwargs})"
156
+
157
+ @property
158
+ def is_ready(self):
159
+ 'Return whether all messages blocking this task are resolved.'
160
+ return check_resolved(self.wait_for)
161
+
162
+ def throw_value(self, exc: Any):
163
+ 'Schedule an exception to throw into the task generator.'
164
+ self._throw_val = exc
165
+
166
+ def return_value(self, value: Any):
167
+ 'Schedule a value to send into the task generator.'
168
+ log(f'Task returned {value} to {self}')
169
+ self._return_val = value
170
+
171
+ def stop(self):
172
+ 'Request that the task stop when it next runs.'
173
+ self._stop_requested = True
174
+
175
+ def join(self, *, background: bool = False) -> TaskJoin[T]:
176
+ """Wait for this task to finish and return its result."""
177
+ return TaskJoin(self, background=background)
178
+
179
+ # Task factory function wrapper
180
+ class Yieldable:
181
+ 'Wrap a callable so it can be converted into an event loop task.'
182
+ __slots__ = ('func',)
183
+
184
+ def __init__(self, func: Callable[..., Any]):
185
+ 'Store the callable to wrap.'
186
+ self.func = func
187
+
188
+ def __call__(self, /, *args: Any, background: bool=False, immediate=False, data: dict[Any, Any] | None = None, timeout: float | None = None, **kwargs: Any) -> Task:
189
+ 'Create a task with scheduling options and an optional first-run timeout.'
190
+ if inspect.isgeneratorfunction(self.func):
191
+ return Task(self.func(*args, **kwargs), background=background, immediate=immediate, timeout=timeout)
192
+
193
+ return Task(self.func, background=background, immediate=immediate, data=data, timeout=timeout, *args, **kwargs)
194
+
195
+ def __repr__(self) -> str:
196
+ 'Return a readable representation of the wrapped callable.'
197
+ return f"Yieldable({self.func.__name__})"
198
+
199
+ # File wrapper
200
+ type FilePath = str | PathLike[str]
201
+ type OpenTextMode = Literal['r', 'w', 'a', 'x', 'r+', 'w+', 'a+', 'x+']
202
+ type OpenBinaryMode = Literal['rb', 'wb', 'ab', 'xb', 'rb+', 'wb+', 'ab+', 'xb+']
203
+ type OpenMode = OpenTextMode | OpenBinaryMode
204
+
205
+ class File[T: (str, bytes)]:
206
+ 'Wrap a text or binary file and expose event loop file operations.'
207
+ __slots__ = ('_binary', '_file')
208
+
209
+ @overload
210
+ def __init__(
211
+ self: File[bytes],
212
+ path: FilePath,
213
+ mode: OpenBinaryMode,
214
+ buffering: int = -1,
215
+ encoding: str | None = None,
216
+ errors: str | None = None,
217
+ newline: str | None = None,
218
+ closefd: bool = True,
219
+ opener: Callable[[str, int], int] | None = None
220
+ ) -> None:
221
+ """Typing overload for opening a binary file."""
222
+ @overload
223
+ def __init__(
224
+ self: File[str],
225
+ path: FilePath,
226
+ mode: OpenTextMode,
227
+ buffering: int = -1,
228
+ encoding: str | None = None,
229
+ errors: str | None = None,
230
+ newline: str | None = None,
231
+ closefd: bool = True,
232
+ opener: Callable[[str, int], int] | None = None
233
+ ) -> None:
234
+ """Typing overload for opening a text file."""
235
+ def __init__(
236
+ self,
237
+ path: FilePath,
238
+ mode: OpenMode,
239
+ buffering: int = -1,
240
+ encoding: str | None = None,
241
+ errors: str | None = None,
242
+ newline: str | None = None,
243
+ closefd: bool = True,
244
+ opener: Callable[[str, int], int] | None = None
245
+ ):
246
+ 'Open a file using the requested mode and options.'
247
+ self._file: Final[IO[T]] = open(path, mode, buffering, encoding, errors, newline, closefd, opener)
248
+ self._binary = 'b' in mode
249
+
250
+ def write(self, data: T, *, background: bool = False) -> FileWrite[T]:
251
+ 'Create a message that writes data to the file.'
252
+ return FileWrite[T](self._file, data, background=background)
253
+
254
+ def read(self, n: int = -1, *, background: bool = False) -> FileRead[T]:
255
+ 'Create a message that reads from the current file position.'
256
+ return FileRead[T](self._file, n, background=background)
257
+
258
+ def seek(self, offset: int, whence: int = 0) -> int:
259
+ 'Move the file cursor and return its new position.'
260
+ return self._file.seek(offset, whence)
261
+
262
+ def delete(self):
263
+ 'Remove the file from the filesystem.'
264
+ os.remove(self._file.name)
265
+
266
+ def __enter__(self) -> Self:
267
+ return self
268
+
269
+ def __exit__(self, *_):
270
+ self._file.close()
271
+
272
+ # Task group
273
+ class TaskGroup:
274
+ 'Collect tasks for coordinated scheduling, cancellation, and result handling.'
275
+ __slots__ = ('started', 'tasks')
276
+
277
+ def __init__(self) -> None:
278
+ 'Create an empty task group that has not started.'
279
+ self.tasks: list[Task] = []
280
+ self.started = False
281
+
282
+ def add(self, task: Task, autorun: bool = True) -> Task:
283
+ 'Add a task, scheduling it if a started group autoruns additions.'
284
+ if task in self.tasks:
285
+ return task
286
+
287
+ self.tasks.append(task)
288
+
289
+ if autorun and self.started and not task.done:
290
+ getEventLoop().schedule(task)
291
+
292
+ return task
293
+
294
+ def collect(self, *, background: bool = False) -> TaskGroupCollect[Any]:
295
+ 'Create a message that returns results in group order.'
296
+ return TaskGroupCollect(tuple(self.tasks), background=background)
297
+
298
+ def as_completed(self, *, background: bool = False) -> TaskGroupAsCompleted[Any]:
299
+ 'Create a message that yields results in completion order.'
300
+ return TaskGroupAsCompleted(tuple(self.tasks), background=background)
301
+
302
+ def cancel(self):
303
+ 'Request that every task in the group stop.'
304
+ for task in self.tasks:
305
+ task.stop()
306
+
307
+ def run(self, background: bool = False) -> TaskGroupCollect[Any] | None:
308
+ 'Schedule unfinished tasks and optionally return a collection message.'
309
+ loop = getEventLoop()
310
+ self.started = True
311
+ for task in self.tasks:
312
+ if not task.done:
313
+ loop.schedule(task)
314
+ return None if background else self.collect()
315
+
316
+ def join(self, *, background: bool = False) -> TaskGroupCollect[Any]:
317
+ """Wait for all group tasks; use as ``yield group.join()``."""
318
+ return self.collect(background=background)
319
+
320
+ def __iter__(self):
321
+ 'Iterate over tasks in insertion order.'
322
+ return iter(self.tasks)
323
+
324
+ def __len__(self) -> int:
325
+ 'Return the number of tasks in the group.'
326
+ return len(self.tasks)
327
+
328
+ def __contains__(self, task: object) -> bool:
329
+ 'Return whether a task belongs to this group.'
330
+ return task in self.tasks
fr_async/exceptions.py ADDED
@@ -0,0 +1,10 @@
1
+
2
+ # Exceptions
3
+ class NoEventLoopException(Exception):
4
+ __slots__ = ()
5
+
6
+ class TaskTimeoutError(TimeoutError):
7
+ __slots__ = ()
8
+
9
+ """Raised when a task exceeds its configured timeout."""
10
+