microio 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.
- microio/__init__.py +10 -0
- microio/_actor.py +51 -0
- microio/_channel.py +160 -0
- microio/_registry.py +91 -0
- microio/_scope.py +44 -0
- microio/_task.py +253 -0
- microio/_thread.py +170 -0
- microio-0.1.0.dist-info/METADATA +241 -0
- microio-0.1.0.dist-info/RECORD +12 -0
- microio-0.1.0.dist-info/WHEEL +5 -0
- microio-0.1.0.dist-info/licenses/LICENSE +202 -0
- microio-0.1.0.dist-info/top_level.txt +1 -0
microio/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
2
|
+
|
|
3
|
+
from ._actor import ActorCore, Mailbox
|
|
4
|
+
from ._channel import ChannelStats, ObjectReceiveChannel, ObjectSendChannel, create_channel
|
|
5
|
+
from ._registry import ReplyHandle, RequestRegistry
|
|
6
|
+
from ._scope import BrokenResourceError, ClosedResourceError, CloseScope, EndOfStream
|
|
7
|
+
from ._task import (CancelScope, TaskGroup, TaskStatus, checkpoint, checkpoint_if_cancelled, create_task_group, current_cancel_scope, fail_after, move_on_after,
|
|
8
|
+
sleep)
|
|
9
|
+
from ._thread import LoopServiceThread, ServiceGroup, ServiceThread
|
|
10
|
+
|
microio/_actor.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
|
|
3
|
+
from ._channel import create_channel
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Mailbox:
|
|
7
|
+
"Thread-safe closable mailbox with async receive."
|
|
8
|
+
|
|
9
|
+
def __init__(self, *, late_send: str = "drop"): self.send, self.receive = create_channel(late_send=late_send)
|
|
10
|
+
|
|
11
|
+
def bind(self, loop=None): self.receive.bind(loop)
|
|
12
|
+
|
|
13
|
+
def submit(self, item): return self.send.send_nowait(item)
|
|
14
|
+
|
|
15
|
+
put = submit
|
|
16
|
+
|
|
17
|
+
async def get(self): return await self.receive.receive()
|
|
18
|
+
|
|
19
|
+
def close(self)->bool: return self.send.close()
|
|
20
|
+
|
|
21
|
+
def fail(self, exc: BaseException)->bool: return self.send.fail(exc)
|
|
22
|
+
|
|
23
|
+
def drain_nowait(self)->list: return self.receive.drain_nowait()
|
|
24
|
+
|
|
25
|
+
def __aiter__(self): return self.receive.__aiter__()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ActorCore:
|
|
29
|
+
"Serialized async handler loop over a Mailbox."
|
|
30
|
+
|
|
31
|
+
def __init__(self, handler, *, mailbox: Mailbox | None = None):
|
|
32
|
+
self.handler = handler
|
|
33
|
+
self.mailbox = mailbox or Mailbox()
|
|
34
|
+
|
|
35
|
+
def bind(self, loop=None): self.mailbox.bind(loop)
|
|
36
|
+
|
|
37
|
+
def submit(self, item): return self.mailbox.submit(item)
|
|
38
|
+
|
|
39
|
+
def close(self)->bool: return self.mailbox.close()
|
|
40
|
+
|
|
41
|
+
def fail(self, exc: BaseException)->bool: return self.mailbox.fail(exc)
|
|
42
|
+
|
|
43
|
+
def drain_nowait(self)->list: return self.mailbox.drain_nowait()
|
|
44
|
+
|
|
45
|
+
async def run(self, *, bind: bool = True):
|
|
46
|
+
if bind: self.bind()
|
|
47
|
+
async for item in self.mailbox: await self.handle(item)
|
|
48
|
+
|
|
49
|
+
async def handle(self, item):
|
|
50
|
+
res = self.handler(item)
|
|
51
|
+
if inspect.isawaitable(res): await res
|
microio/_channel.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import asyncio, logging, threading
|
|
2
|
+
from collections import deque
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from ._scope import BrokenResourceError, ClosedResourceError, EndOfStream
|
|
6
|
+
from ._task import checkpoint_if_cancelled
|
|
7
|
+
|
|
8
|
+
log = logging.getLogger("microio")
|
|
9
|
+
_closed = object()
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class ChannelStats:
|
|
14
|
+
sent: int = 0
|
|
15
|
+
received: int = 0
|
|
16
|
+
dropped: int = 0
|
|
17
|
+
queued: int = 0
|
|
18
|
+
closed: bool = False
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class _ChannelState:
|
|
22
|
+
def __init__(self, late_send: str = "raise"):
|
|
23
|
+
if late_send not in {"raise", "drop"}: raise ValueError("late_send must be 'raise' or 'drop'")
|
|
24
|
+
self.late_send = late_send
|
|
25
|
+
self.loop = None
|
|
26
|
+
self.q = None
|
|
27
|
+
self.pending = deque()
|
|
28
|
+
self.lock = threading.Lock()
|
|
29
|
+
self.closed = False
|
|
30
|
+
self.sent = 0
|
|
31
|
+
self.received = 0
|
|
32
|
+
self.dropped = 0
|
|
33
|
+
|
|
34
|
+
def stats(self)->ChannelStats:
|
|
35
|
+
with self.lock:
|
|
36
|
+
queued = (self.q.qsize() if self.q is not None else len(self.pending))
|
|
37
|
+
return ChannelStats(self.sent, self.received, self.dropped, queued, self.closed)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ObjectSendChannel:
|
|
41
|
+
"Thread-safe sender endpoint for an ObjectReceiveChannel."
|
|
42
|
+
|
|
43
|
+
def __init__(self, state: _ChannelState): self._state = state
|
|
44
|
+
|
|
45
|
+
def send_nowait(self, item):
|
|
46
|
+
"Queue `item` from any thread."
|
|
47
|
+
st = self._state
|
|
48
|
+
with st.lock:
|
|
49
|
+
if st.closed:
|
|
50
|
+
st.dropped += 1
|
|
51
|
+
if st.late_send == "drop": return None
|
|
52
|
+
raise ClosedResourceError("send on closed channel")
|
|
53
|
+
st.sent += 1
|
|
54
|
+
loop, q = st.loop, st.q
|
|
55
|
+
if loop is None or q is None:
|
|
56
|
+
st.pending.append(item)
|
|
57
|
+
return st.sent
|
|
58
|
+
try: loop.call_soon_threadsafe(q.put_nowait, item)
|
|
59
|
+
except RuntimeError:
|
|
60
|
+
with st.lock:
|
|
61
|
+
st.dropped += 1
|
|
62
|
+
if st.late_send == "drop": return None
|
|
63
|
+
raise BrokenResourceError("receiver loop is closed")
|
|
64
|
+
return st.sent
|
|
65
|
+
|
|
66
|
+
def close(self):
|
|
67
|
+
"Close the channel and wake the receiver."
|
|
68
|
+
return self._close(_closed)
|
|
69
|
+
|
|
70
|
+
def fail(self, exc: BaseException):
|
|
71
|
+
"Break the channel and wake the receiver with `exc`."
|
|
72
|
+
return self._close(exc)
|
|
73
|
+
|
|
74
|
+
def _close(self, item):
|
|
75
|
+
st = self._state
|
|
76
|
+
with st.lock:
|
|
77
|
+
if st.closed: return False
|
|
78
|
+
st.closed = True
|
|
79
|
+
loop, q = st.loop, st.q
|
|
80
|
+
if loop is None or q is None:
|
|
81
|
+
st.pending.append(item)
|
|
82
|
+
return True
|
|
83
|
+
try: loop.call_soon_threadsafe(q.put_nowait, item)
|
|
84
|
+
except RuntimeError: pass
|
|
85
|
+
return True
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def closed(self)->bool: return self._state.closed
|
|
89
|
+
|
|
90
|
+
def stats(self)->ChannelStats: return self._state.stats()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class ObjectReceiveChannel:
|
|
94
|
+
"Async receiver endpoint for objects sent from other threads/tasks."
|
|
95
|
+
|
|
96
|
+
def __init__(self, state: _ChannelState): self._state = state
|
|
97
|
+
|
|
98
|
+
def bind(self, loop: asyncio.AbstractEventLoop | None = None):
|
|
99
|
+
"Bind to an event loop; pending sends are flushed."
|
|
100
|
+
st = self._state
|
|
101
|
+
if loop is None: loop = asyncio.get_running_loop()
|
|
102
|
+
with st.lock:
|
|
103
|
+
if st.q is not None: return
|
|
104
|
+
st.loop = loop
|
|
105
|
+
st.q = asyncio.Queue()
|
|
106
|
+
for item in st.pending: st.q.put_nowait(item)
|
|
107
|
+
st.pending.clear()
|
|
108
|
+
|
|
109
|
+
async def receive(self):
|
|
110
|
+
"Receive one item, raising EndOfStream when closed."
|
|
111
|
+
st = self._state
|
|
112
|
+
if st.q is None: self.bind()
|
|
113
|
+
checkpoint_if_cancelled()
|
|
114
|
+
item = await st.q.get()
|
|
115
|
+
checkpoint_if_cancelled()
|
|
116
|
+
if item is _closed:
|
|
117
|
+
st.q.put_nowait(_closed)
|
|
118
|
+
raise EndOfStream
|
|
119
|
+
if isinstance(item, BaseException):
|
|
120
|
+
st.q.put_nowait(item)
|
|
121
|
+
raise item
|
|
122
|
+
with st.lock: st.received += 1
|
|
123
|
+
return item
|
|
124
|
+
|
|
125
|
+
def drain_nowait(self)->list:
|
|
126
|
+
"Drain currently queued items without awaiting."
|
|
127
|
+
st = self._state
|
|
128
|
+
if st.q is None: return []
|
|
129
|
+
out = []
|
|
130
|
+
while True:
|
|
131
|
+
try: item = st.q.get_nowait()
|
|
132
|
+
except asyncio.QueueEmpty: return out
|
|
133
|
+
if item is _closed:
|
|
134
|
+
st.q.put_nowait(_closed)
|
|
135
|
+
return out
|
|
136
|
+
if isinstance(item, BaseException):
|
|
137
|
+
st.q.put_nowait(item)
|
|
138
|
+
return out
|
|
139
|
+
out.append(item)
|
|
140
|
+
|
|
141
|
+
def close(self)->bool: return ObjectSendChannel(self._state).close()
|
|
142
|
+
|
|
143
|
+
def fail(self, exc: BaseException)->bool: return ObjectSendChannel(self._state).fail(exc)
|
|
144
|
+
|
|
145
|
+
def __aiter__(self): return self
|
|
146
|
+
|
|
147
|
+
async def __anext__(self):
|
|
148
|
+
try: return await self.receive()
|
|
149
|
+
except EndOfStream: raise StopAsyncIteration
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def closed(self)->bool: return self._state.closed
|
|
153
|
+
|
|
154
|
+
def stats(self)->ChannelStats: return self._state.stats()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def create_channel(*, late_send: str = "raise")->tuple[ObjectSendChannel, ObjectReceiveChannel]:
|
|
158
|
+
"Create thread-safe object channel endpoints."
|
|
159
|
+
state = _ChannelState(late_send=late_send)
|
|
160
|
+
return ObjectSendChannel(state), ObjectReceiveChannel(state)
|
microio/_registry.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import queue, threading
|
|
2
|
+
from collections.abc import Hashable
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class ReplyHandle:
|
|
6
|
+
"Resolve/fail/wait one RequestRegistry entry."
|
|
7
|
+
|
|
8
|
+
def __init__(self, registry: "RequestRegistry", key: Hashable, waiter: queue.Queue):
|
|
9
|
+
self.registry = registry
|
|
10
|
+
self.key = key
|
|
11
|
+
self.waiter = waiter
|
|
12
|
+
|
|
13
|
+
def resolve(self, value)->bool: return self.registry.resolve(self.key, value)
|
|
14
|
+
|
|
15
|
+
def fail(self, exc: BaseException)->bool: return self.registry.fail(self.key, exc)
|
|
16
|
+
|
|
17
|
+
def pop(self): return self.registry.pop(self.key, waiter=self.waiter)
|
|
18
|
+
|
|
19
|
+
def wait(self, timeout: float | None = None): return self.registry.wait(self.key, self.waiter, timeout=timeout)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class RequestRegistry:
|
|
23
|
+
"Track request waiters and fail them reliably on close/crash."
|
|
24
|
+
|
|
25
|
+
def __init__(self):
|
|
26
|
+
self._lock = threading.Lock()
|
|
27
|
+
self._pending = {}
|
|
28
|
+
|
|
29
|
+
def __len__(self)->int:
|
|
30
|
+
with self._lock: return len(self._pending)
|
|
31
|
+
|
|
32
|
+
def __contains__(self, key: Hashable)->bool:
|
|
33
|
+
with self._lock: return key in self._pending
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def pending(self)->dict:
|
|
37
|
+
with self._lock: return dict(self._pending)
|
|
38
|
+
|
|
39
|
+
def register(self, key: Hashable)->queue.Queue:
|
|
40
|
+
"Register `key` and return its waiter queue."
|
|
41
|
+
waiter = queue.Queue(maxsize=1)
|
|
42
|
+
with self._lock:
|
|
43
|
+
if key in self._pending: raise KeyError(f"request already pending: {key!r}")
|
|
44
|
+
self._pending[key] = waiter
|
|
45
|
+
return waiter
|
|
46
|
+
|
|
47
|
+
def reply(self, key: Hashable)->ReplyHandle:
|
|
48
|
+
"Register `key` and return a reply handle."
|
|
49
|
+
return ReplyHandle(self, key, self.register(key))
|
|
50
|
+
|
|
51
|
+
def pop(self, key: Hashable, waiter=None):
|
|
52
|
+
"Remove `key`, optionally only if it still maps to `waiter`."
|
|
53
|
+
with self._lock:
|
|
54
|
+
if waiter is not None and self._pending.get(key) is not waiter: return None
|
|
55
|
+
return self._pending.pop(key, None)
|
|
56
|
+
|
|
57
|
+
def resolve(self, key: Hashable, value)->bool:
|
|
58
|
+
"Resolve one pending request; return False if it is no longer pending."
|
|
59
|
+
waiter = self.pop(key)
|
|
60
|
+
if waiter is None: return False
|
|
61
|
+
waiter.put(value)
|
|
62
|
+
return True
|
|
63
|
+
|
|
64
|
+
def fail(self, key: Hashable, exc: BaseException)->bool: return self.resolve(key, exc)
|
|
65
|
+
|
|
66
|
+
def fail_all(self, exc: BaseException)->int:
|
|
67
|
+
"Fail every pending request and return how many waiters were woken."
|
|
68
|
+
with self._lock:
|
|
69
|
+
waiters = list(self._pending.values())
|
|
70
|
+
self._pending.clear()
|
|
71
|
+
for waiter in waiters: waiter.put(exc)
|
|
72
|
+
return len(waiters)
|
|
73
|
+
|
|
74
|
+
def wait(self, key: Hashable, waiter: queue.Queue, timeout: float | None = None):
|
|
75
|
+
"Wait for `waiter`, removing `key` on timeout/cancel."
|
|
76
|
+
try: result = waiter.get(timeout=timeout)
|
|
77
|
+
except queue.Empty as exc:
|
|
78
|
+
self.pop(key, waiter=waiter)
|
|
79
|
+
raise TimeoutError(f"timed out waiting for request {key!r}") from exc
|
|
80
|
+
self.pop(key, waiter=waiter)
|
|
81
|
+
if isinstance(result, BaseException): raise result
|
|
82
|
+
return result
|
|
83
|
+
|
|
84
|
+
def request(self, key: Hashable, send, timeout: float | None = None):
|
|
85
|
+
"Register `key`, call `send(reply)`, then wait; unregister if sending fails."
|
|
86
|
+
reply = self.reply(key)
|
|
87
|
+
try: send(reply)
|
|
88
|
+
except BaseException:
|
|
89
|
+
reply.pop()
|
|
90
|
+
raise
|
|
91
|
+
return reply.wait(timeout=timeout)
|
microio/_scope.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import threading
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ClosedResourceError(RuntimeError): pass
|
|
5
|
+
|
|
6
|
+
class BrokenResourceError(RuntimeError): pass
|
|
7
|
+
|
|
8
|
+
class EndOfStream(Exception): pass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class CloseScope:
|
|
12
|
+
"Thread-safe cooperative close/failure state."
|
|
13
|
+
|
|
14
|
+
def __init__(self):
|
|
15
|
+
self._event = threading.Event()
|
|
16
|
+
self._lock = threading.Lock()
|
|
17
|
+
self.reason = None
|
|
18
|
+
self.exc = None
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def closed(self)->bool: return self._event.is_set()
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def failed(self)->bool: return self.exc is not None
|
|
25
|
+
|
|
26
|
+
def close(self, reason: str | None = None, exc: BaseException | None = None)->bool:
|
|
27
|
+
"Close once; return True for the first caller."
|
|
28
|
+
with self._lock:
|
|
29
|
+
if self._event.is_set(): return False
|
|
30
|
+
self.reason = reason
|
|
31
|
+
self.exc = exc
|
|
32
|
+
self._event.set()
|
|
33
|
+
return True
|
|
34
|
+
|
|
35
|
+
def fail(self, exc: BaseException, reason: str | None = None)->bool:
|
|
36
|
+
"Close with failure exception."
|
|
37
|
+
return self.close(reason=reason or str(exc), exc=exc)
|
|
38
|
+
|
|
39
|
+
def wait(self, timeout: float | None = None)->bool: return self._event.wait(timeout=timeout)
|
|
40
|
+
|
|
41
|
+
def raise_if_closed(self):
|
|
42
|
+
if not self.closed: return
|
|
43
|
+
if self.exc is not None: raise BrokenResourceError(self.reason or str(self.exc)) from self.exc
|
|
44
|
+
raise ClosedResourceError(self.reason or "closed")
|
microio/_task.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import asyncio, contextvars, inspect, threading
|
|
2
|
+
|
|
3
|
+
_scope_stack = contextvars.ContextVar("microio_cancel_scopes", default=())
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class _TaskGroupCancelled(Exception): pass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def _raise_task_group_cancel(): raise _TaskGroupCancelled
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _current_task():
|
|
13
|
+
try: return asyncio.current_task()
|
|
14
|
+
except RuntimeError: return None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _cancel_task(task):
|
|
18
|
+
if task is None or task.done(): return
|
|
19
|
+
loop = task.get_loop()
|
|
20
|
+
try: running = asyncio.get_running_loop()
|
|
21
|
+
except RuntimeError: running = None
|
|
22
|
+
if running is loop: task.cancel()
|
|
23
|
+
else: loop.call_soon_threadsafe(task.cancel)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _uncancel_task(task):
|
|
27
|
+
if task is not None and hasattr(task, "uncancel") and task.cancelling(): task.uncancel()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class CancelScope:
|
|
31
|
+
"Async task cancellation state with optional deadline."
|
|
32
|
+
|
|
33
|
+
def __init__(self, *, deadline: float | None = None, delay: float | None = None, raise_timeout: bool = False):
|
|
34
|
+
self.deadline = deadline
|
|
35
|
+
self.delay = delay
|
|
36
|
+
self.raise_timeout = raise_timeout
|
|
37
|
+
self.reason = None
|
|
38
|
+
self.cancel_called = False
|
|
39
|
+
self.cancelled_caught = False
|
|
40
|
+
self.timed_out = False
|
|
41
|
+
self._lock = threading.RLock()
|
|
42
|
+
self._tasks = set()
|
|
43
|
+
self._entries = []
|
|
44
|
+
self._callbacks = []
|
|
45
|
+
self._timeout_handle = None
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def cancelled(self)->bool:
|
|
49
|
+
with self._lock: return self.cancel_called
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def active(self)->bool:
|
|
53
|
+
with self._lock: return bool(self._entries)
|
|
54
|
+
|
|
55
|
+
def _add_cancel_callback(self, cb):
|
|
56
|
+
with self._lock:
|
|
57
|
+
if not self.cancel_called:
|
|
58
|
+
self._callbacks.append(cb)
|
|
59
|
+
return
|
|
60
|
+
cb()
|
|
61
|
+
|
|
62
|
+
def cancel(self, reason: str | None = None)->bool:
|
|
63
|
+
caller = _current_task()
|
|
64
|
+
with self._lock:
|
|
65
|
+
if self.cancel_called: return False
|
|
66
|
+
self.cancel_called = True
|
|
67
|
+
self.reason = reason
|
|
68
|
+
timeout_handle = self._timeout_handle
|
|
69
|
+
self._timeout_handle = None
|
|
70
|
+
tasks = list(self._tasks)
|
|
71
|
+
callbacks = list(self._callbacks)
|
|
72
|
+
if timeout_handle is not None: timeout_handle.cancel()
|
|
73
|
+
for task in tasks:
|
|
74
|
+
if task is not caller: _cancel_task(task)
|
|
75
|
+
for cb in callbacks: cb()
|
|
76
|
+
return True
|
|
77
|
+
|
|
78
|
+
def _arm_deadline(self):
|
|
79
|
+
loop = asyncio.get_running_loop()
|
|
80
|
+
def _timeout():
|
|
81
|
+
with self._lock: self.timed_out = True
|
|
82
|
+
self.cancel("deadline")
|
|
83
|
+
with self._lock:
|
|
84
|
+
if self._timeout_handle is not None or (self.deadline is None and self.delay is None): return
|
|
85
|
+
if self.deadline is None: self.deadline = loop.time() + self.delay
|
|
86
|
+
self._timeout_handle = loop.call_soon(_timeout) if self.deadline <= loop.time() else loop.call_at(self.deadline, _timeout)
|
|
87
|
+
|
|
88
|
+
def __enter__(self):
|
|
89
|
+
token = _scope_stack.set(_scope_stack.get() + (self,))
|
|
90
|
+
task = _current_task()
|
|
91
|
+
with self._lock:
|
|
92
|
+
if task is not None: self._tasks.add(task)
|
|
93
|
+
self._entries.append((task, token))
|
|
94
|
+
first = len(self._entries) == 1
|
|
95
|
+
if first: self._arm_deadline()
|
|
96
|
+
return self
|
|
97
|
+
|
|
98
|
+
def _pop_entry(self, task):
|
|
99
|
+
with self._lock:
|
|
100
|
+
for i in range(len(self._entries) - 1, -1, -1):
|
|
101
|
+
if self._entries[i][0] is task:
|
|
102
|
+
_, token = self._entries.pop(i)
|
|
103
|
+
break
|
|
104
|
+
else: raise RuntimeError("CancelScope exited in a different task")
|
|
105
|
+
if task is not None: self._tasks.discard(task)
|
|
106
|
+
timeout_handle = self._timeout_handle if not self._entries else None
|
|
107
|
+
if timeout_handle is not None: self._timeout_handle = None
|
|
108
|
+
return token, timeout_handle
|
|
109
|
+
|
|
110
|
+
def _suppress_cancelled(self, task, exc)->bool:
|
|
111
|
+
with self._lock:
|
|
112
|
+
if not self.cancel_called: return False
|
|
113
|
+
self.cancelled_caught = True
|
|
114
|
+
raise_timeout, timed_out = self.raise_timeout, self.timed_out
|
|
115
|
+
_uncancel_task(task)
|
|
116
|
+
if raise_timeout and timed_out: raise TimeoutError("operation timed out") from exc
|
|
117
|
+
return True
|
|
118
|
+
|
|
119
|
+
def __exit__(self, exc_type, exc, tb):
|
|
120
|
+
task = _current_task()
|
|
121
|
+
token, timeout_handle = self._pop_entry(task)
|
|
122
|
+
_scope_stack.reset(token)
|
|
123
|
+
if timeout_handle is not None: timeout_handle.cancel()
|
|
124
|
+
if exc_type is not None and issubclass(exc_type, asyncio.CancelledError): return self._suppress_cancelled(task, exc)
|
|
125
|
+
return False
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def current_cancel_scope():
|
|
129
|
+
"Return the innermost cancelled active scope, if any."
|
|
130
|
+
for scope in reversed(_scope_stack.get()):
|
|
131
|
+
if scope.cancelled: return scope
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def checkpoint_if_cancelled():
|
|
136
|
+
"Raise CancelledError if an active microio scope is cancelled."
|
|
137
|
+
if current_cancel_scope() is not None: raise asyncio.CancelledError
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
async def checkpoint():
|
|
141
|
+
"Yield once and honor active microio cancellation."
|
|
142
|
+
checkpoint_if_cancelled()
|
|
143
|
+
await asyncio.sleep(0)
|
|
144
|
+
checkpoint_if_cancelled()
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
async def sleep(delay: float, result=None):
|
|
148
|
+
"asyncio.sleep() with microio cancellation checkpoints."
|
|
149
|
+
checkpoint_if_cancelled()
|
|
150
|
+
res = await asyncio.sleep(delay, result)
|
|
151
|
+
checkpoint_if_cancelled()
|
|
152
|
+
return res
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def move_on_after(delay: float)->CancelScope: return CancelScope(delay=delay)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def fail_after(delay: float)->CancelScope: return CancelScope(delay=delay, raise_timeout=True)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class TaskStatus:
|
|
162
|
+
"Readiness handle passed to TaskGroup.start() children."
|
|
163
|
+
|
|
164
|
+
def __init__(self, fut: asyncio.Future):
|
|
165
|
+
self._fut = fut
|
|
166
|
+
self.started_called = False
|
|
167
|
+
|
|
168
|
+
def started(self, value=None):
|
|
169
|
+
if self._fut.done(): raise RuntimeError("task_status.started() called twice")
|
|
170
|
+
self.started_called = True
|
|
171
|
+
self._fut.set_result(value)
|
|
172
|
+
|
|
173
|
+
def _fail(self, exc: BaseException):
|
|
174
|
+
if not self._fut.done(): self._fut.set_exception(exc)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class TaskGroup:
|
|
178
|
+
"Small wrapper around asyncio.TaskGroup with a cancel scope."
|
|
179
|
+
|
|
180
|
+
def __init__(self):
|
|
181
|
+
self.cancel_scope = CancelScope()
|
|
182
|
+
self.cancel_scope._add_cancel_callback(self._cancel_group)
|
|
183
|
+
self._tg = None
|
|
184
|
+
self._loop = None
|
|
185
|
+
self._owner_task = None
|
|
186
|
+
|
|
187
|
+
async def __aenter__(self):
|
|
188
|
+
self._loop = asyncio.get_running_loop()
|
|
189
|
+
self._owner_task = asyncio.current_task()
|
|
190
|
+
self._tg = asyncio.TaskGroup()
|
|
191
|
+
await self._tg.__aenter__()
|
|
192
|
+
if self.cancel_scope.cancelled: self._cancel_group()
|
|
193
|
+
return self
|
|
194
|
+
|
|
195
|
+
async def __aexit__(self, exc_type, exc, tb):
|
|
196
|
+
res = False
|
|
197
|
+
cancelled = False
|
|
198
|
+
try: res = await self._tg.__aexit__(exc_type, exc, tb)
|
|
199
|
+
except* _TaskGroupCancelled: cancelled = True
|
|
200
|
+
finally:
|
|
201
|
+
self._tg = None
|
|
202
|
+
self._loop = None
|
|
203
|
+
self._owner_task = None
|
|
204
|
+
if cancelled: _uncancel_task(_current_task())
|
|
205
|
+
return res
|
|
206
|
+
|
|
207
|
+
def _cancel_group(self):
|
|
208
|
+
if self._tg is None or self._loop is None: return
|
|
209
|
+
if _current_task() is self._owner_task: return
|
|
210
|
+
def _create_cancel_task():
|
|
211
|
+
try: self._tg.create_task(_raise_task_group_cancel())
|
|
212
|
+
except RuntimeError: pass
|
|
213
|
+
try: running = asyncio.get_running_loop()
|
|
214
|
+
except RuntimeError: running = None
|
|
215
|
+
if running is self._loop: _create_cancel_task()
|
|
216
|
+
else: self._loop.call_soon_threadsafe(_create_cancel_task)
|
|
217
|
+
|
|
218
|
+
def cancel(self, reason: str | None = None)->bool: return self.cancel_scope.cancel(reason=reason)
|
|
219
|
+
|
|
220
|
+
async def _run(self, coro):
|
|
221
|
+
with self.cancel_scope:
|
|
222
|
+
checkpoint_if_cancelled()
|
|
223
|
+
return await coro
|
|
224
|
+
|
|
225
|
+
def create_task(self, coro, *, name: str | None = None):
|
|
226
|
+
if self._tg is None: raise RuntimeError("TaskGroup is not active")
|
|
227
|
+
return self._tg.create_task(self._run(coro), name=name)
|
|
228
|
+
|
|
229
|
+
async def _call(self, fn, *args, **kwargs):
|
|
230
|
+
res = fn(*args, **kwargs)
|
|
231
|
+
return await res if inspect.isawaitable(res) else res
|
|
232
|
+
|
|
233
|
+
def start_soon(self, fn, *args, name: str | None = None, **kwargs):
|
|
234
|
+
if self._tg is None: raise RuntimeError("TaskGroup is not active")
|
|
235
|
+
return self.create_task(self._call(fn, *args, **kwargs), name=name)
|
|
236
|
+
|
|
237
|
+
async def _call_started(self, fn, args, kwargs, task_status: TaskStatus):
|
|
238
|
+
try:
|
|
239
|
+
res = fn(*args, task_status=task_status, **kwargs)
|
|
240
|
+
if inspect.isawaitable(res): await res
|
|
241
|
+
if not task_status.started_called: task_status._fail(RuntimeError("task exited without calling task_status.started()"))
|
|
242
|
+
except BaseException as exc:
|
|
243
|
+
task_status._fail(exc)
|
|
244
|
+
raise
|
|
245
|
+
|
|
246
|
+
async def start(self, fn, *args, name: str | None = None, **kwargs):
|
|
247
|
+
if self._loop is None: raise RuntimeError("TaskGroup is not active")
|
|
248
|
+
task_status = TaskStatus(self._loop.create_future())
|
|
249
|
+
self.create_task(self._call_started(fn, args, kwargs, task_status), name=name)
|
|
250
|
+
return await task_status._fut
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def create_task_group()->TaskGroup: return TaskGroup()
|
microio/_thread.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import asyncio, concurrent.futures, logging, threading, time
|
|
2
|
+
from collections.abc import Awaitable, Callable
|
|
3
|
+
|
|
4
|
+
from ._scope import CloseScope
|
|
5
|
+
from ._task import create_task_group, sleep
|
|
6
|
+
|
|
7
|
+
log = logging.getLogger("microio")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ServiceThread(threading.Thread):
|
|
11
|
+
"Supervised thread with ready/failed/stop state."
|
|
12
|
+
|
|
13
|
+
def __init__(self, *, name: str | None = None, target: Callable[["ServiceThread"], None] | None = None,
|
|
14
|
+
daemon: bool = True, reraise: bool = False):
|
|
15
|
+
super().__init__(name=name, daemon=daemon)
|
|
16
|
+
self._target_func = target
|
|
17
|
+
self.reraise = reraise
|
|
18
|
+
self.ready = threading.Event()
|
|
19
|
+
self.failed = threading.Event()
|
|
20
|
+
self.stopped = threading.Event()
|
|
21
|
+
self.scope = CloseScope()
|
|
22
|
+
self.exc = None
|
|
23
|
+
|
|
24
|
+
def started(self):
|
|
25
|
+
"Mark the service ready."
|
|
26
|
+
self.ready.set()
|
|
27
|
+
|
|
28
|
+
def fail(self, exc: BaseException):
|
|
29
|
+
"Mark the service failed and wake waiters."
|
|
30
|
+
self.exc = exc
|
|
31
|
+
self.scope.fail(exc)
|
|
32
|
+
self.failed.set()
|
|
33
|
+
self.ready.set()
|
|
34
|
+
|
|
35
|
+
def wait_started(self, timeout: float | None = None):
|
|
36
|
+
"Wait until started or failed."
|
|
37
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
38
|
+
while True:
|
|
39
|
+
if self.failed.is_set(): raise RuntimeError(f"{self.name} failed") from self.exc
|
|
40
|
+
if self.ready.wait(timeout=0.01): return
|
|
41
|
+
if deadline is not None and time.monotonic() >= deadline: raise TimeoutError(f"{self.name} did not become ready")
|
|
42
|
+
|
|
43
|
+
def stop(self, reason: str | None = "stop")->bool: return self.scope.close(reason=reason)
|
|
44
|
+
|
|
45
|
+
def join_or_log(self, timeout: float | None = None)->bool:
|
|
46
|
+
if self.ident is None and not self.is_alive(): return True
|
|
47
|
+
self.join(timeout=timeout)
|
|
48
|
+
if not self.is_alive(): return True
|
|
49
|
+
log.error("thread did not stop: %s", self.name)
|
|
50
|
+
return False
|
|
51
|
+
|
|
52
|
+
def run_service(self):
|
|
53
|
+
if self._target_func is None: raise NotImplementedError("override run_service() or pass target=")
|
|
54
|
+
self._target_func(self)
|
|
55
|
+
|
|
56
|
+
def run(self):
|
|
57
|
+
try: self.run_service()
|
|
58
|
+
except BaseException as exc:
|
|
59
|
+
self.fail(exc)
|
|
60
|
+
if self.reraise: raise
|
|
61
|
+
finally:
|
|
62
|
+
self.stopped.set()
|
|
63
|
+
self.ready.set()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class LoopServiceThread(ServiceThread):
|
|
67
|
+
"ServiceThread that owns an asyncio.Runner and loop."
|
|
68
|
+
|
|
69
|
+
def __init__(self, *, name: str | None = None, daemon: bool = True, reraise: bool = False):
|
|
70
|
+
super().__init__(name=name, daemon=daemon, reraise=reraise)
|
|
71
|
+
self.loop = None
|
|
72
|
+
self.task_group = None
|
|
73
|
+
self._runner_task = None
|
|
74
|
+
|
|
75
|
+
def run_service(self):
|
|
76
|
+
with asyncio.Runner() as runner:
|
|
77
|
+
self.loop = runner.get_loop()
|
|
78
|
+
try: runner.run(self._run_main())
|
|
79
|
+
except asyncio.CancelledError:
|
|
80
|
+
if not self.scope.closed: raise
|
|
81
|
+
finally: self.loop = None
|
|
82
|
+
|
|
83
|
+
async def _run_main(self):
|
|
84
|
+
self._runner_task = asyncio.current_task()
|
|
85
|
+
try:
|
|
86
|
+
async with create_task_group() as tg:
|
|
87
|
+
self.task_group = tg
|
|
88
|
+
tg.start_soon(self.run_async, name=f"{self.name}-main")
|
|
89
|
+
finally:
|
|
90
|
+
self.task_group = None
|
|
91
|
+
self._runner_task = None
|
|
92
|
+
|
|
93
|
+
async def run_async(self):
|
|
94
|
+
"Override in subclasses."
|
|
95
|
+
self.started()
|
|
96
|
+
while not self.scope.closed: await sleep(0.05)
|
|
97
|
+
|
|
98
|
+
def call_soon(self, fn: Callable, *args):
|
|
99
|
+
loop = self.loop
|
|
100
|
+
if loop is None: raise RuntimeError("loop is not running")
|
|
101
|
+
loop.call_soon_threadsafe(fn, *args)
|
|
102
|
+
|
|
103
|
+
def call_sync(self, fn: Callable, *args, timeout: float | None = None, **kwargs):
|
|
104
|
+
"Run `fn` on the loop thread and return its result."
|
|
105
|
+
loop = self.loop
|
|
106
|
+
if loop is None: raise RuntimeError("loop is not running")
|
|
107
|
+
try: running = asyncio.get_running_loop()
|
|
108
|
+
except RuntimeError: running = None
|
|
109
|
+
if running is loop: return fn(*args, **kwargs)
|
|
110
|
+
fut = concurrent.futures.Future()
|
|
111
|
+
def _run():
|
|
112
|
+
if not fut.set_running_or_notify_cancel(): return
|
|
113
|
+
try: fut.set_result(fn(*args, **kwargs))
|
|
114
|
+
except BaseException as exc: fut.set_exception(exc)
|
|
115
|
+
loop.call_soon_threadsafe(_run)
|
|
116
|
+
return fut.result(timeout=timeout)
|
|
117
|
+
|
|
118
|
+
def submit(self, coro: Awaitable)->concurrent.futures.Future:
|
|
119
|
+
loop = self.loop
|
|
120
|
+
if loop is None: raise RuntimeError("loop is not running")
|
|
121
|
+
return asyncio.run_coroutine_threadsafe(coro, loop)
|
|
122
|
+
|
|
123
|
+
def stop(self, reason: str | None = "stop")->bool:
|
|
124
|
+
first = super().stop(reason=reason)
|
|
125
|
+
if self.task_group is not None:
|
|
126
|
+
self.task_group.cancel(reason)
|
|
127
|
+
return first
|
|
128
|
+
loop, task = self.loop, self._runner_task
|
|
129
|
+
if loop is not None and task is not None and not task.done():
|
|
130
|
+
try:
|
|
131
|
+
try: running = asyncio.get_running_loop()
|
|
132
|
+
except RuntimeError: running = None
|
|
133
|
+
if running is loop and asyncio.current_task() is task: loop.call_soon(task.cancel)
|
|
134
|
+
else: loop.call_soon_threadsafe(task.cancel)
|
|
135
|
+
except RuntimeError: pass
|
|
136
|
+
return first
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class ServiceGroup:
|
|
140
|
+
"Small owner for starting/stopping ServiceThread instances together."
|
|
141
|
+
|
|
142
|
+
def __init__(self, *services): self.services = [svc for svc in services if svc is not None]
|
|
143
|
+
|
|
144
|
+
def add(self, *services):
|
|
145
|
+
self.services.extend(svc for svc in services if svc is not None)
|
|
146
|
+
return self
|
|
147
|
+
|
|
148
|
+
def start(self):
|
|
149
|
+
for svc in self.services: svc.start()
|
|
150
|
+
return self
|
|
151
|
+
|
|
152
|
+
def wait_started(self, timeout: float | None = None):
|
|
153
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
154
|
+
for svc in self.services:
|
|
155
|
+
rem = None if deadline is None else max(0.0, deadline - time.monotonic())
|
|
156
|
+
svc.wait_started(timeout=rem)
|
|
157
|
+
return self
|
|
158
|
+
|
|
159
|
+
def stop(self):
|
|
160
|
+
for svc in self.services: svc.stop()
|
|
161
|
+
return self
|
|
162
|
+
|
|
163
|
+
def join_or_log(self, timeout: float | None = None)->bool:
|
|
164
|
+
ok = True
|
|
165
|
+
for svc in self.services: ok = svc.join_or_log(timeout=timeout) and ok
|
|
166
|
+
return ok
|
|
167
|
+
|
|
168
|
+
def stop_join(self, timeout: float | None = None)->bool:
|
|
169
|
+
self.stop()
|
|
170
|
+
return self.join_or_log(timeout=timeout)
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: microio
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Tiny asyncio-first runtime helpers for service threads, loop ownership, channels, and request waiters
|
|
5
|
+
Author: microio contributors
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/AnswerDotAI/microio
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
|
+
Requires-Python: >=3.11
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: fastship; extra == "dev"
|
|
15
|
+
Requires-Dist: build; extra == "dev"
|
|
16
|
+
Requires-Dist: twine; extra == "dev"
|
|
17
|
+
Requires-Dist: pytest; extra == "dev"
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# microio
|
|
21
|
+
|
|
22
|
+
`microio` is a tiny asyncio-first runtime helper library for services that own
|
|
23
|
+
event loops, sockets, background threads, and request/reply waiters.
|
|
24
|
+
|
|
25
|
+
It is inspired by AnyIO's practical concurrency ideas, especially the problems
|
|
26
|
+
called out in [Why you should be using AnyIO APIs instead of asyncio APIs][anyio-why]:
|
|
27
|
+
|
|
28
|
+
- **task readiness**: a child service should be able to report "ready" or "failed"
|
|
29
|
+
before its parent continues;
|
|
30
|
+
- **cancel scopes**: stopping is a durable state with a reason, not a one-shot flag
|
|
31
|
+
that individual operations may miss;
|
|
32
|
+
- **memory object streams**: producers and consumers should be split into explicit
|
|
33
|
+
sender/receiver endpoints with clear close semantics;
|
|
34
|
+
- **thread bridges**: code outside an event-loop thread needs a safe way to submit
|
|
35
|
+
work into that loop and observe failures.
|
|
36
|
+
|
|
37
|
+
`microio` is not a compatibility layer over asyncio, Trio, and Curio. It is also
|
|
38
|
+
not a reimplementation of AnyIO. It intentionally stays smaller:
|
|
39
|
+
|
|
40
|
+
- asyncio only;
|
|
41
|
+
- stdlib only;
|
|
42
|
+
- no generic networking/file APIs;
|
|
43
|
+
- cooperative level cancellation only where code uses `microio` scopes and checkpoints;
|
|
44
|
+
- no pytest plugin or framework-level dependency injection.
|
|
45
|
+
|
|
46
|
+
The goal is to make the common "small service runtime" patterns reliable and
|
|
47
|
+
testable without pulling a full concurrency abstraction into projects that already
|
|
48
|
+
use asyncio directly.
|
|
49
|
+
|
|
50
|
+
## What It Provides
|
|
51
|
+
|
|
52
|
+
### `TaskGroup` / `CancelScope`
|
|
53
|
+
|
|
54
|
+
`create_task_group()` wraps `asyncio.TaskGroup`. It keeps the stdlib failure
|
|
55
|
+
rules, and adds the missing cancellation/readiness pieces:
|
|
56
|
+
|
|
57
|
+
- `tg.start_soon(fn, *args)` starts a child task;
|
|
58
|
+
- `await tg.start(fn, *args)` starts a child and waits until it calls
|
|
59
|
+
`task_status.started(value)`;
|
|
60
|
+
- `tg.cancel_scope.cancel()` or `tg.cancel()` cancels owned tasks and treats
|
|
61
|
+
that as normal shutdown;
|
|
62
|
+
- `checkpoint()`, `checkpoint_if_cancelled()`, and `sleep()` provide cooperative
|
|
63
|
+
level cancellation for code that uses `microio` primitives;
|
|
64
|
+
- `move_on_after(seconds)` suppresses deadline cancellation;
|
|
65
|
+
- `fail_after(seconds)` turns deadline cancellation into `TimeoutError`.
|
|
66
|
+
|
|
67
|
+
The group-cancel path borrows the small `asyncio_cancel_scope` trick: when a
|
|
68
|
+
child task or another thread asks a group to stop, `microio` injects a private
|
|
69
|
+
task exception into the underlying `asyncio.TaskGroup` and suppresses just that
|
|
70
|
+
private exception on exit.
|
|
71
|
+
|
|
72
|
+
This is still asyncio cancellation. Raw `await something()` follows asyncio's
|
|
73
|
+
edge-cancellation rules. Once code returns to a `microio` checkpoint, cancelled
|
|
74
|
+
scopes keep raising `CancelledError`, even if earlier cancellation was caught.
|
|
75
|
+
|
|
76
|
+
Shielding is not exposed. A partial shield around raw `Task.cancel()` would look
|
|
77
|
+
stronger than it is.
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from microio import create_task_group, sleep
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
async def worker():
|
|
84
|
+
while True: await sleep(1)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
async with create_task_group() as tg:
|
|
88
|
+
tg.start_soon(worker)
|
|
89
|
+
await sleep(0.1)
|
|
90
|
+
tg.cancel()
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### `CloseScope`
|
|
94
|
+
|
|
95
|
+
`CloseScope` is a small, thread-safe stop/failure state object. It records whether
|
|
96
|
+
a service is closing, why it is closing, and whether there is an exception that
|
|
97
|
+
should be propagated to waiters.
|
|
98
|
+
|
|
99
|
+
This is separate from `CancelScope`. `CloseScope` is for thread-safe service
|
|
100
|
+
lifecycle state. It does not cancel asyncio tasks for you.
|
|
101
|
+
|
|
102
|
+
### `ServiceThread` / `ServiceGroup`
|
|
103
|
+
|
|
104
|
+
`ServiceThread` is a supervised `threading.Thread`:
|
|
105
|
+
|
|
106
|
+
- child code calls `started()` after resources are ready;
|
|
107
|
+
- parents call `wait_started()` and get either readiness or the startup exception;
|
|
108
|
+
- `stop()` marks the thread's `CloseScope`;
|
|
109
|
+
- `join_or_log()` checks timeout results instead of ignoring them.
|
|
110
|
+
|
|
111
|
+
Use it for socket threads, protocol readers, and other owned background services.
|
|
112
|
+
|
|
113
|
+
`ServiceGroup` owns the repeated lifecycle boilerplate for a small set of service
|
|
114
|
+
threads:
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
services = ServiceGroup(iopub, stdin, heartbeat).start().wait_started()
|
|
118
|
+
...
|
|
119
|
+
services.stop_join(timeout=1)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### `LoopServiceThread`
|
|
123
|
+
|
|
124
|
+
`LoopServiceThread` owns an `asyncio.Runner` inside a thread and exposes:
|
|
125
|
+
|
|
126
|
+
- `call_soon()` for thread-safe callbacks;
|
|
127
|
+
- `call_sync()` for thread-safe callbacks with a return value;
|
|
128
|
+
- `submit()` for coroutine submission from other threads;
|
|
129
|
+
- `task_group` for async work owned by the service;
|
|
130
|
+
- the same ready/failed/stop/join behavior as `ServiceThread`.
|
|
131
|
+
|
|
132
|
+
This is the small subset of AnyIO's thread-bridge idea that asyncio services often
|
|
133
|
+
need: create one loop in one thread, keep ownership clear, submit coroutine work
|
|
134
|
+
safely, and synchronously run small functions on the loop thread when needed.
|
|
135
|
+
`stop()` cancels the service task group, so owned child tasks shut down with the
|
|
136
|
+
service.
|
|
137
|
+
|
|
138
|
+
### `ObjectChannel`
|
|
139
|
+
|
|
140
|
+
`create_channel()` returns `(send, receive)` endpoints. A sender can be used from
|
|
141
|
+
other threads before or after the receiver has bound to an event loop. The receiver
|
|
142
|
+
is async and supports `async for`.
|
|
143
|
+
|
|
144
|
+
This is inspired by AnyIO memory object streams, but adjusted for service threads:
|
|
145
|
+
|
|
146
|
+
- the default buffer is unbounded because cross-thread producers often cannot
|
|
147
|
+
await backpressure;
|
|
148
|
+
- close is explicit and wakes async receivers;
|
|
149
|
+
- receivers raise `EndOfStream` on direct receive after close;
|
|
150
|
+
- `fail(exc)` is explicit and wakes async receivers with the exception;
|
|
151
|
+
- late sends raise `ClosedResourceError` unless `late_send="drop"` is selected;
|
|
152
|
+
- the implementation is intentionally single-receiver and simple.
|
|
153
|
+
|
|
154
|
+
### `Mailbox` / `ActorCore`
|
|
155
|
+
|
|
156
|
+
`Mailbox` wraps an `ObjectChannel` for the common actor shape: thread-safe
|
|
157
|
+
`submit()`, async receive, `close()`, `fail()`, and `drain_nowait()`.
|
|
158
|
+
|
|
159
|
+
`ActorCore` is the tiny serialized consumer loop:
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
actor = ActorCore(handle)
|
|
163
|
+
actor.submit(item)
|
|
164
|
+
await actor.run()
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
It is deliberately not tied to a thread. A service thread, a main-thread runner,
|
|
168
|
+
or a test can all run the same actor core.
|
|
169
|
+
|
|
170
|
+
### `RequestRegistry`
|
|
171
|
+
|
|
172
|
+
`RequestRegistry` tracks request IDs and waiters:
|
|
173
|
+
|
|
174
|
+
- register a request;
|
|
175
|
+
- resolve it from another thread through a `ReplyHandle`;
|
|
176
|
+
- wait with timeout;
|
|
177
|
+
- wrap the common register-send-wait pattern with `request(key, send)`;
|
|
178
|
+
- fail one or all pending requests on service crash/close.
|
|
179
|
+
|
|
180
|
+
This is useful for debug adapters, stdin routers, RPC clients, and any protocol
|
|
181
|
+
where a reader thread must wake request waiters reliably.
|
|
182
|
+
|
|
183
|
+
## Example
|
|
184
|
+
|
|
185
|
+
```python
|
|
186
|
+
import asyncio
|
|
187
|
+
from microio import LoopServiceThread, create_channel
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class Worker(LoopServiceThread):
|
|
191
|
+
def __init__(self):
|
|
192
|
+
super().__init__(name="worker")
|
|
193
|
+
self.send, self.receive = create_channel()
|
|
194
|
+
|
|
195
|
+
async def run_async(self):
|
|
196
|
+
self.receive.bind(asyncio.get_running_loop())
|
|
197
|
+
self.started()
|
|
198
|
+
async for item in self.receive:
|
|
199
|
+
if item == "stop":
|
|
200
|
+
self.stop()
|
|
201
|
+
break
|
|
202
|
+
print(item)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
worker = Worker()
|
|
206
|
+
worker.start()
|
|
207
|
+
worker.wait_started()
|
|
208
|
+
worker.send.send_nowait("hello")
|
|
209
|
+
worker.send.send_nowait("stop")
|
|
210
|
+
worker.join_or_log(timeout=1)
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
## Design Rules
|
|
214
|
+
|
|
215
|
+
- Prefer explicit state over hidden magic.
|
|
216
|
+
- Make startup failure visible to the parent.
|
|
217
|
+
- Never ignore a join timeout.
|
|
218
|
+
- Waking pending waiters on close/crash is part of the service contract.
|
|
219
|
+
- Keep asyncio ownership clear: a socket or loop belongs to one service thread.
|
|
220
|
+
|
|
221
|
+
## Development
|
|
222
|
+
|
|
223
|
+
```bash
|
|
224
|
+
pip install -e .[dev]
|
|
225
|
+
pytest -q
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## Examples
|
|
229
|
+
|
|
230
|
+
Run the counter service example:
|
|
231
|
+
|
|
232
|
+
```bash
|
|
233
|
+
python examples/counter_server.py
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
It shows `LoopServiceThread`, `ObjectChannel`, `RequestRegistry`, and
|
|
237
|
+
`CloseScope` working together in one small service.
|
|
238
|
+
|
|
239
|
+
Version lives in `microio/__init__.py` as `__version__`.
|
|
240
|
+
|
|
241
|
+
[anyio-why]: https://anyio.readthedocs.io/en/stable/why.html
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
microio/__init__.py,sha256=oYKZSmKgn8xhSYKkSH746RPzo9ayQCPDMbLgZCAW6Og,533
|
|
2
|
+
microio/_actor.py,sha256=3gB0Fb4tRzyJnXVrCJ8miePMHBtonkOq4qBmSCOgnXc,1487
|
|
3
|
+
microio/_channel.py,sha256=lr-bhlKtV-OyBtWS03i9vS2NgZ63F_LHWd2TRl7jLl0,5128
|
|
4
|
+
microio/_registry.py,sha256=9VoV4DKGJbTkACzCx0PjB-Tmw_fFCCwTbaf3c2MgrvA,3356
|
|
5
|
+
microio/_scope.py,sha256=HfaRIdK4E9kvhkZCORyNZyqkkOdxw-723VCCbQu5cyA,1352
|
|
6
|
+
microio/_task.py,sha256=0nwKz2ytH0YVUGI9Or1vOj-XegJKwJwrj8ffyNETsAI,9038
|
|
7
|
+
microio/_thread.py,sha256=ABX0_jmXD_5jCcFIvTuSrgMyF9zOyt4Isi9kMzwlaHA,6329
|
|
8
|
+
microio-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
9
|
+
microio-0.1.0.dist-info/METADATA,sha256=t9ZhLYIIo_wp2qgcyqP2IAjsqiCZ058gm5ajwYPybnQ,8236
|
|
10
|
+
microio-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
11
|
+
microio-0.1.0.dist-info/top_level.txt,sha256=bdfx3oS52_dT23rO70h95oP_xmKSscHQ3fL3i22Z17Q,8
|
|
12
|
+
microio-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
microio
|