Debian Codegraph @

pika/adapters/utils/nbio_interface.py

raw
1 """Non-blocking I/O interface for pika connection adapters.
2
3 I/O interface expected by `pika.adapters.base_connection.BaseConnection`
4
5 NOTE: This API is modeled after asyncio in python3 for a couple of reasons
6 1. It's a sensible API
7 2. To make it easy to implement at least on top of the built-in asyncio
8
9 Furthermore, the API caters to the needs of pika core and lack of generalization
10 is intentional for the sake of reducing complexity of the implementation and
11 testing and lessening the maintenance burden.
12
13 """
14 from __future__ import annotations
15
16 import abc
17 from typing import TYPE_CHECKING, Callable, Optional, Tuple, Union, Any
18
19 import pika.compat
20
21 if TYPE_CHECKING:
22 import ssl
23 import socket
24
25
26 class AbstractIOServices(pika.compat.AbstractBase): # type: ignore
27 """Interface to I/O services required by `pika.adapters.BaseConnection` and
28 related utilities.
29
30 NOTE: This is not a public API. Pika users should rely on the native I/O
31 loop APIs (e.g., asyncio event loop, tornado ioloop, twisted reactor, etc.)
32 that corresponds to the chosen Connection adapter.
33
34 """
35
36 @abc.abstractmethod
37 def get_native_ioloop(self) -> Any:
38 """Returns the native I/O loop instance, such as Twisted reactor,
39 asyncio's or tornado's event loop
40
41 """
42 raise NotImplementedError
43
44 @abc.abstractmethod
45 def close(self) -> None:
46 """Release IOLoop's resources.
47
48 the `close()` method is intended to be called by Pika's own test
49 code only after `start()` returns. After calling `close()`, no other
50 interaction with the closed instance of `IOLoop` should be performed.
51
52 NOTE: This method is provided for Pika's own test scripts that need to
53 be able to run I/O loops generically to test multiple Connection Adapter
54 implementations. Pika users should use the native I/O loop's API
55 instead.
56
57 """
58 raise NotImplementedError
59
60 @abc.abstractmethod
61 def run(self) -> None:
62 """Run the I/O loop. It will loop until requested to exit. See `stop()`.
63
64 NOTE: the outcome or restarting an instance that had been stopped is
65 UNDEFINED!
66
67 NOTE: This method is provided for Pika's own test scripts that need to
68 be able to run I/O loops generically to test multiple Connection Adapter
69 implementations (not all of the supported I/O Loop frameworks have
70 methods named start/stop). Pika users should use the native I/O loop's
71 API instead.
72
73 """
74 raise NotImplementedError
75
76 @abc.abstractmethod
77 def stop(self) -> None:
78 """Request exit from the ioloop. The loop is NOT guaranteed to
79 stop before this method returns.
80
81 NOTE: The outcome of calling `stop()` on a non-running instance is
82 UNDEFINED!
83
84 NOTE: This method is provided for Pika's own test scripts that need to
85 be able to run I/O loops generically to test multiple Connection Adapter
86 implementations (not all of the supported I/O Loop frameworks have
87 methods named start/stop). Pika users should use the native I/O loop's
88 API instead.
89
90 To invoke `stop()` safely from a thread other than this IOLoop's thread,
91 call it via `add_callback_threadsafe`; e.g.,
92
93 `ioloop.add_callback_threadsafe(ioloop.stop)`
94
95 """
96 raise NotImplementedError
97
98 @abc.abstractmethod
99 def add_callback_threadsafe(self, callback: Callable[..., None]) -> None:
100 """Requests a call to the given function as soon as possible. It will be
101 called from this IOLoop's thread.
102
103 NOTE: This is the only thread-safe method offered by the IOLoop adapter.
104 All other manipulations of the IOLoop adapter and objects governed
105 by it must be performed from the IOLoop's thread.
106
107 NOTE: if you know that the requester is running on the same thread as
108 the connection it is more efficient to use the
109 `ioloop.call_later()` method with a delay of 0.
110
111 :param callable callback: The callback method; must be callable.
112 """
113 raise NotImplementedError
114
115 @abc.abstractmethod
116 def call_later(self, delay: float,
117 callback: Callable[..., None]) -> AbstractTimerReference:
118 """Add the callback to the IOLoop timer to be called after delay seconds
119 from the time of call on best-effort basis. Returns a handle to the
120 timeout.
121
122 If two are scheduled for the same time, it's undefined which one will
123 be called first.
124
125 :param float delay: The number of seconds to wait to call callback
126 :param callable callback: The callback method
127 :returns: A handle that can be used to cancel the request.
128 :rtype: AbstractTimerReference
129
130 """
131 raise NotImplementedError
132
133 @abc.abstractmethod
134 def getaddrinfo(self,
135 host: str,
136 port: int,
137 on_done: Callable[..., None],
138 family: int = 0,
139 socktype: int = 0,
140 proto: int = 0,
141 flags: int = 0) -> AbstractIOReference:
142 """Perform the equivalent of `socket.getaddrinfo()` asynchronously.
143
144 See `socket.getaddrinfo()` for the standard args.
145
146 :param callable on_done: user callback that takes the return value of
147 `socket.getaddrinfo()` upon successful completion or exception upon
148 failure (check for `BaseException`) as its only arg. It will not be
149 called if the operation was cancelled.
150 :rtype: AbstractIOReference
151 """
152 raise NotImplementedError
153
154 @abc.abstractmethod
155 def connect_socket(
156 self, sock: socket.socket, resolved_addr: Tuple[str, int],
157 on_done: Callable[[Optional[BaseException]],
158 None]) -> AbstractIOReference:
159 """Perform the equivalent of `socket.connect()` on a previously-resolved
160 address asynchronously.
161
162 IMPLEMENTATION NOTE: Pika's connection logic resolves the addresses
163 prior to making socket connections, so we don't need to burden the
164 implementations of this method with the extra logic of asynchronous
165 DNS resolution. Implementations can use `socket.inet_pton()` to
166 verify the address.
167
168 :param socket.socket sock: non-blocking socket that needs to be
169 connected via `socket.socket.connect()`
170 :param tuple resolved_addr: resolved destination address/port two-tuple
171 as per `socket.socket.connect()`, except that the first element must
172 be an actual IP address that's consistent with the given socket's
173 address family.
174 :param callable on_done: user callback that takes None upon successful
175 completion or exception (check for `BaseException`) upon error as
176 its only arg. It will not be called if the operation was cancelled.
177
178 :rtype: AbstractIOReference
179 :raises ValueError: if host portion of `resolved_addr` is not an IP
180 address or is inconsistent with the socket's address family as
181 validated via `socket.inet_pton()`
182 """
183 raise NotImplementedError
184
185 @abc.abstractmethod
186 def create_streaming_connection(
187 self,
188 protocol_factory: Callable[[], AbstractStreamProtocol],
189 sock: socket.socket,
190 on_done: Callable[[
191 Union[BaseException, Tuple[AbstractStreamTransport,
192 AbstractStreamProtocol]]
193 ], None],
194 ssl_context: Optional[ssl.SSLContext] = None,
195 server_hostname: Optional[str] = None) -> AbstractIOReference:
196 """Perform SSL session establishment, if requested, on the already-
197 connected socket and link the streaming transport/protocol pair.
198
199 NOTE: This method takes ownership of the socket.
200
201 :param callable protocol_factory: called without args, returns an
202 instance with the `AbstractStreamProtocol` interface. The protocol's
203 `connection_made(transport)` method will be called to link it to
204 the transport after remaining connection activity (e.g., SSL session
205 establishment), if any, is completed successfully.
206 :param socket.socket sock: Already-connected, non-blocking
207 `socket.SOCK_STREAM` socket to be used by the transport. We take
208 ownership of this socket.
209 :param callable on_done: User callback
210 `on_done(BaseException | (transport, protocol))` to be notified when
211 the asynchronous operation completes. An exception arg indicates
212 failure (check for `BaseException`); otherwise the two-tuple will
213 contain the linked transport/protocol pair having
214 AbstractStreamTransport and AbstractStreamProtocol interfaces
215 respectively.
216 :param None | ssl.SSLContext ssl_context: if None, this will proceed as
217 a plaintext connection; otherwise, if not None, SSL session
218 establishment will be performed prior to linking the transport and
219 protocol.
220 :param str | None server_hostname: For use during SSL session
221 establishment to match against the target server's certificate. The
222 value `None` disables this check (which is a huge security risk)
223 :rtype: AbstractIOReference
224 """
225 raise NotImplementedError
226
227
228 class AbstractFileDescriptorServices(pika.compat.AbstractBase): # type: ignore
229 """Interface definition of common non-blocking file descriptor services
230 required by some utility implementations.
231
232 NOTE: This is not a public API. Pika users should rely on the native I/O
233 loop APIs (e.g., asyncio event loop, tornado ioloop, twisted reactor, etc.)
234 that corresponds to the chosen Connection adapter.
235
236 """
237
238 @abc.abstractmethod
239 def set_reader(self, fd: int, on_readable: Callable[[], None]):
240 """Call the given callback when the file descriptor is readable.
241 Replace prior reader, if any, for the given file descriptor.
242
243 :param fd: file descriptor
244 :param callable on_readable: a callback taking no args to be notified
245 when fd becomes readable.
246
247 """
248 raise NotImplementedError
249
250 @abc.abstractmethod
251 def remove_reader(self, fd: int) -> bool:
252 """Stop watching the given file descriptor for readability
253
254 :param fd: file descriptor
255 :returns: True if reader was removed; False if none was registered.
256 :rtype: bool
257
258 """
259 raise NotImplementedError
260
261 @abc.abstractmethod
262 def set_writer(self, fd: int, on_writable: Callable[[], None]) -> None:
263 """Call the given callback whenever the file descriptor is writable.
264 Replace prior writer callback, if any, for the given file descriptor.
265
266 IMPLEMENTATION NOTE: For portability, implementations of
267 `set_writable()` should also watch for indication of error on the
268 socket and treat it as equivalent to the writable indication (e.g.,
269 also adding the socket to the `exceptfds` arg of `socket.select()`
270 and calling the `on_writable` callback if `select.select()`
271 indicates that the socket is in error state). Specifically, Windows
272 (unlike POSIX) only indicates error on the socket (but not writable)
273 when connection establishment fails.
274
275 :param fd: file descriptor
276 :param callable on_writable: a callback taking no args to be notified
277 when fd becomes writable.
278
279 """
280 raise NotImplementedError
281
282 @abc.abstractmethod
283 def remove_writer(self, fd: int) -> bool:
284 """Stop watching the given file descriptor for writability
285
286 :param fd: file descriptor
287 :returns: True if reader was removed; False if none was registered.
288 :rtype: bool
289
290 """
291 raise NotImplementedError
292
293
294 class AbstractTimerReference(pika.compat.AbstractBase): # type: ignore
295 """Reference to asynchronous operation"""
296
297 @abc.abstractmethod
298 def cancel(self) -> None:
299 """Cancel callback. If already cancelled, has no affect.
300 """
301 raise NotImplementedError
302
303
304 class AbstractIOReference(pika.compat.AbstractBase): # type: ignore
305 """Reference to asynchronous I/O operation"""
306
307 @abc.abstractmethod
308 def cancel(self) -> bool:
309 """Cancel pending operation
310
311 :returns: False if was already done or cancelled; True otherwise
312 :rtype: bool
313 """
314 raise NotImplementedError
315
316
317 class AbstractStreamProtocol(pika.compat.AbstractBase): # type: ignore
318 """Stream protocol interface. It's compatible with a subset of
319 `asyncio.protocols.Protocol` for compatibility with asyncio-based
320 `AbstractIOServices` implementation.
321
322 """
323
324 @abc.abstractmethod
325 def connection_made(self, transport: AbstractStreamTransport):
326 """Introduces transport to protocol after transport is connected.
327
328 :param AbstractStreamTransport transport:
329 :raises Exception: Exception-based exception on error
330 """
331 raise NotImplementedError
332
333 @abc.abstractmethod
334 def connection_lost(self, error: Optional[BaseException]) -> None:
335 """Called upon loss or closing of connection.
336
337 NOTE: `connection_made()` and `connection_lost()` are each called just
338 once and in that order. All other callbacks are called between them.
339
340 :param BaseException | None error: An exception (check for
341 `BaseException`) indicates connection failure. None indicates that
342 connection was closed on this side, such as when it's aborted or
343 when `AbstractStreamProtocol.eof_received()` returns a result that
344 doesn't evaluate to True.
345 :raises Exception: Exception-based exception on error
346 """
347 raise NotImplementedError
348
349 @abc.abstractmethod
350 def eof_received(self) -> Optional[bool]:
351 """Called after the remote peer shuts its write end of the connection.
352
353 :returns: A falsy value (including None) will cause the transport to
354 close itself, resulting in an eventual `connection_lost()` call
355 from the transport. If a truthy value is returned, it will be the
356 protocol's responsibility to close/abort the transport.
357 :rtype: falsy|truthy
358 :raises Exception: Exception-based exception on error
359 """
360 raise NotImplementedError
361
362 @abc.abstractmethod
363 def data_received(self, data: bytes) -> None:
364 """Called to deliver incoming data to the protocol.
365
366 :param data: Non-empty data bytes.
367 :raises Exception: Exception-based exception on error
368 """
369 raise NotImplementedError
370
371 # pylint: disable=W0511
372 # TODO Undecided whether we need write flow-control yet, although it seems
373 # like a good idea.
374 # @abc.abstractmethod
375 # def pause_writing(self):
376 # """Called when the transport's write buffer size becomes greater than or
377 # equal to the transport's high-water mark. It won't be called again until
378 # the transport's write buffer gets back to its low-water mark and then
379 # returns to/past the hight-water mark again.
380 # """
381 # raise NotImplementedError
382 #
383 # @abc.abstractmethod
384 # def resume_writing(self):
385 # """Called when the transport's write buffer size becomes less than or
386 # equal to the transport's low-water mark.
387 # """
388 # raise NotImplementedError
389
390
391 class AbstractStreamTransport(pika.compat.AbstractBase): # type: ignore
392 """Stream transport interface. It's compatible with a subset of
393 `asyncio.transports.Transport` for compatibility with asyncio-based
394 `AbstractIOServices` implementation.
395
396 """
397
398 @abc.abstractmethod
399 def abort(self) -> None:
400 """Close connection abruptly without waiting for pending I/O to
401 complete. Will invoke the corresponding protocol's `connection_lost()`
402 method asynchronously (not in context of the abort() call).
403
404 :raises Exception: Exception-based exception on error
405 """
406 raise NotImplementedError
407
408 @abc.abstractmethod
409 def get_protocol(self) -> AbstractStreamProtocol:
410 """Return the protocol linked to this transport.
411
412 :rtype: AbstractStreamProtocol
413 :raises Exception: Exception-based exception on error
414 """
415 raise NotImplementedError
416
417 @abc.abstractmethod
418 def write(self, data: bytes) -> None:
419 """Buffer the given data until it can be sent asynchronously.
420
421 :param bytes data:
422 :raises ValueError: if called with empty data
423 :raises Exception: Exception-based exception on error
424 """
425 raise NotImplementedError
426
427 @abc.abstractmethod
428 def get_write_buffer_size(self) -> int:
429 """
430 :returns: Current size of output data buffered by the transport
431 :rtype: int
432 """
433 raise NotImplementedError
434
435 # pylint: disable=W0511
436 # TODO Udecided whether we need write flow-control yet, although it seems
437 # like a good idea.
438 # @abc.abstractmethod
439 # def set_write_buffer_limits(self, high, low):
440 # """Set thresholds for calling the protocol's `pause_writing()`
441 # and `resume_writing()` methods. `low` must be less than or equal to
442 # `high`.
443 #
444 # NOTE The unintuitive order of the args is preserved to match the
445 # corresponding method in `asyncio.WriteTransport`. I would expect `low`
446 # to be the first arg, especially since
447 # `asyncio.WriteTransport.get_write_buffer_limits()` returns them in the
448 # opposite order. This seems error-prone.
449 #
450 # See `asyncio.WriteTransport.get_write_buffer_limits()` for more details
451 # about the args.
452 #
453 # :param int high: non-negative high-water mark.
454 # :param int low: non-negative low-water mark.
455 # """
456 # raise NotImplementedError