Debian Codegraph @

Lib/test/support/interpreters/channels.py

raw
1 """Cross-interpreter Channels High Level Module."""
2
3 import time
4 import _interpchannels as _channels
5 from . import _crossinterp
6
7 # aliases:
8 from _interpchannels import (
9 ChannelError, ChannelNotFoundError, ChannelClosedError,
10 ChannelEmptyError, ChannelNotEmptyError,
11 )
12 from ._crossinterp import (
13 UNBOUND_ERROR, UNBOUND_REMOVE,
14 )
15
16
17 __all__ = [
18 'UNBOUND', 'UNBOUND_ERROR', 'UNBOUND_REMOVE',
19 'create', 'list_all',
20 'SendChannel', 'RecvChannel',
21 'ChannelError', 'ChannelNotFoundError', 'ChannelEmptyError',
22 'ItemInterpreterDestroyed',
23 ]
24
25
26 class ItemInterpreterDestroyed(ChannelError,
27 _crossinterp.ItemInterpreterDestroyed):
28 """Raised from get() and get_nowait()."""
29
30
31 UNBOUND = _crossinterp.UnboundItem.singleton('queue', __name__)
32
33
34 def _serialize_unbound(unbound):
35 if unbound is UNBOUND:
36 unbound = _crossinterp.UNBOUND
37 return _crossinterp.serialize_unbound(unbound)
38
39
40 def _resolve_unbound(flag):
41 resolved = _crossinterp.resolve_unbound(flag, ItemInterpreterDestroyed)
42 if resolved is _crossinterp.UNBOUND:
43 resolved = UNBOUND
44 return resolved
45
46
47 def create(*, unbounditems=UNBOUND):
48 """Return (recv, send) for a new cross-interpreter channel.
49
50 The channel may be used to pass data safely between interpreters.
51
52 "unbounditems" sets the default for the send end of the channel.
53 See SendChannel.send() for supported values. The default value
54 is UNBOUND, which replaces the unbound item when received.
55 """
56 unbound = _serialize_unbound(unbounditems)
57 unboundop, = unbound
58 cid = _channels.create(unboundop)
59 recv, send = RecvChannel(cid), SendChannel(cid, _unbound=unbound)
60 return recv, send
61
62
63 def list_all():
64 """Return a list of (recv, send) for all open channels."""
65 return [(RecvChannel(cid), SendChannel(cid, _unbound=unbound))
66 for cid, unbound in _channels.list_all()]
67
68
69 class _ChannelEnd:
70 """The base class for RecvChannel and SendChannel."""
71
72 _end = None
73
74 def __new__(cls, cid):
75 self = super().__new__(cls)
76 if self._end == 'send':
77 cid = _channels._channel_id(cid, send=True, force=True)
78 elif self._end == 'recv':
79 cid = _channels._channel_id(cid, recv=True, force=True)
80 else:
81 raise NotImplementedError(self._end)
82 self._id = cid
83 return self
84
85 def __repr__(self):
86 return f'{type(self).__name__}(id={int(self._id)})'
87
88 def __hash__(self):
89 return hash(self._id)
90
91 def __eq__(self, other):
92 if isinstance(self, RecvChannel):
93 if not isinstance(other, RecvChannel):
94 return NotImplemented
95 elif not isinstance(other, SendChannel):
96 return NotImplemented
97 return other._id == self._id
98
99 # for pickling:
100 def __getnewargs__(self):
101 return (int(self._id),)
102
103 # for pickling:
104 def __getstate__(self):
105 return None
106
107 @property
108 def id(self):
109 return self._id
110
111 @property
112 def _info(self):
113 return _channels.get_info(self._id)
114
115 @property
116 def is_closed(self):
117 return self._info.closed
118
119
120 _NOT_SET = object()
121
122
123 class RecvChannel(_ChannelEnd):
124 """The receiving end of a cross-interpreter channel."""
125
126 _end = 'recv'
127
128 def recv(self, timeout=None, *,
129 _sentinel=object(),
130 _delay=10 / 1000, # 10 milliseconds
131 ):
132 """Return the next object from the channel.
133
134 This blocks until an object has been sent, if none have been
135 sent already.
136 """
137 if timeout is not None:
138 timeout = int(timeout)
139 if timeout < 0:
140 raise ValueError(f'timeout value must be non-negative')
141 end = time.time() + timeout
142 obj, unboundop = _channels.recv(self._id, _sentinel)
143 while obj is _sentinel:
144 time.sleep(_delay)
145 if timeout is not None and time.time() >= end:
146 raise TimeoutError
147 obj, unboundop = _channels.recv(self._id, _sentinel)
148 if unboundop is not None:
149 assert obj is None, repr(obj)
150 return _resolve_unbound(unboundop)
151 return obj
152
153 def recv_nowait(self, default=_NOT_SET):
154 """Return the next object from the channel.
155
156 If none have been sent then return the default if one
157 is provided or fail with ChannelEmptyError. Otherwise this
158 is the same as recv().
159 """
160 if default is _NOT_SET:
161 obj, unboundop = _channels.recv(self._id)
162 else:
163 obj, unboundop = _channels.recv(self._id, default)
164 if unboundop is not None:
165 assert obj is None, repr(obj)
166 return _resolve_unbound(unboundop)
167 return obj
168
169 def close(self):
170 _channels.close(self._id, recv=True)
171
172
173 class SendChannel(_ChannelEnd):
174 """The sending end of a cross-interpreter channel."""
175
176 _end = 'send'
177
178 def __new__(cls, cid, *, _unbound=None):
179 if _unbound is None:
180 try:
181 op = _channels.get_channel_defaults(cid)
182 _unbound = (op,)
183 except ChannelNotFoundError:
184 _unbound = _serialize_unbound(UNBOUND)
185 self = super().__new__(cls, cid)
186 self._unbound = _unbound
187 return self
188
189 @property
190 def is_closed(self):
191 info = self._info
192 return info.closed or info.closing
193
194 def send(self, obj, timeout=None, *,
195 unbound=None,
196 ):
197 """Send the object (i.e. its data) to the channel's receiving end.
198
199 This blocks until the object is received.
200 """
201 if unbound is None:
202 unboundop, = self._unbound
203 else:
204 unboundop, = _serialize_unbound(unbound)
205 _channels.send(self._id, obj, unboundop, timeout=timeout, blocking=True)
206
207 def send_nowait(self, obj, *,
208 unbound=None,
209 ):
210 """Send the object to the channel's receiving end.
211
212 If the object is immediately received then return True
213 (else False). Otherwise this is the same as send().
214 """
215 if unbound is None:
216 unboundop, = self._unbound
217 else:
218 unboundop, = _serialize_unbound(unbound)
219 # XXX Note that at the moment channel_send() only ever returns
220 # None. This should be fixed when channel_send_wait() is added.
221 # See bpo-32604 and gh-19829.
222 return _channels.send(self._id, obj, unboundop, blocking=False)
223
224 def send_buffer(self, obj, timeout=None, *,
225 unbound=None,
226 ):
227 """Send the object's buffer to the channel's receiving end.
228
229 This blocks until the object is received.
230 """
231 if unbound is None:
232 unboundop, = self._unbound
233 else:
234 unboundop, = _serialize_unbound(unbound)
235 _channels.send_buffer(self._id, obj, unboundop,
236 timeout=timeout, blocking=True)
237
238 def send_buffer_nowait(self, obj, *,
239 unbound=None,
240 ):
241 """Send the object's buffer to the channel's receiving end.
242
243 If the object is immediately received then return True
244 (else False). Otherwise this is the same as send().
245 """
246 if unbound is None:
247 unboundop, = self._unbound
248 else:
249 unboundop, = _serialize_unbound(unbound)
250 return _channels.send_buffer(self._id, obj, unboundop, blocking=False)
251
252 def close(self):
253 _channels.close(self._id, send=True)
254
255
256 # XXX This is causing leaks (gh-110318):
257 _channels._register_end_types(SendChannel, RecvChannel)