Debian Codegraph @

awscrt/eventstream/rpc.py

raw symbols SCIP
1 """
2 event-stream RPC (remote procedure call) protocol library for `awscrt`.
3 """
4
5 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6 # SPDX-License-Identifier: Apache-2.0.
7
8 import _awscrt
9 from abc import ABC, abstractmethod
10 from awscrt import NativeResource
11 import awscrt.exceptions
12 from awscrt.eventstream import Header
13 from awscrt.io import ClientBootstrap, SocketOptions, TlsConnectionOptions
14 from collections.abc import Callable
15 from concurrent.futures import Future
16 from enum import IntEnum
17 from functools import partial
18 from typing import Optional, Sequence, Union
19
20 __all__ = [
21 'MessageType',
22 'MessageFlag',
23 'ClientConnectionHandler',
24 'ClientConnection',
25 'ClientContinuation',
26 'ClientContinuationHandler',
27 ]
28
29
30 class MessageType(IntEnum):
31 """Types of messages in the event-stream RPC protocol.
32
33 The :attr:`~MessageType.APPLICATION_MESSAGE` and :attr:`~MessageType.APPLICATION_ERROR` types may only be sent
34 on streams, and will never arrive as a protocol message (stream-id 0).
35
36 For all other message types, they may only be sent as protocol messages
37 (stream-id 0), and will never arrive as a stream message.
38
39 Different message types expect specific headers and flags, consult documentation."""
40
41 APPLICATION_MESSAGE = 0
42 """Application message"""
43
44 APPLICATION_ERROR = 1
45 """Application error"""
46
47 PING = 2
48 """Ping"""
49
50 PING_RESPONSE = 3
51 """Ping response"""
52
53 CONNECT = 4
54 """Connect"""
55
56 CONNECT_ACK = 5
57 """Connect acknowledgement
58
59 If the :attr:`MessageFlag.CONNECTION_ACCEPTED` flag is not present, the connection has been rejected."""
60
61 PROTOCOL_ERROR = 6
62 """Protocol error"""
63
64 INTERNAL_ERROR = 7
65 """Internal error"""
66
67 def __format__(self, format_spec):
68 # override so formatted string doesn't simply look like an int
69 return str(self)
70
71
72 class MessageFlag:
73 """Flags for messages in the event-stream RPC protocol.
74
75 Flags may be XORed together.
76 Not all flags can be used with all message types, consult documentation.
77 """
78 # TODO: when python 3.5 is dropped this class should inherit from IntFlag.
79 # When doing this, be sure to update type-hints and callbacks to pass
80 # MessageFlag instead of plain int.
81
82 NONE = 0
83 """No flags"""
84
85 CONNECTION_ACCEPTED = 0x1
86 """Connection accepted
87
88 If this flag is absent from a :attr:`MessageType.CONNECT_ACK`, the connection has been rejected."""
89
90 TERMINATE_STREAM = 0x2
91 """Terminate stream
92
93 This message may be used with any message type.
94 The sender will close their connection after the message is written to the wire.
95 The receiver will close their connection after delivering the message to the user."""
96
97 def __format__(self, format_spec):
98 # override so formatted string doesn't simply look like an int
99 return str(self)
100
101
102 class ClientConnectionHandler(ABC):
103 """Base class for handling connection events.
104
105 Inherit from this class and override methods to handle connection events.
106 All callbacks for this connection will be invoked on the same thread,
107 and :meth:`on_connection_setup()` will always be the first callback invoked.
108 """
109
110 @abstractmethod
111 def on_connection_setup(self, connection, error, **kwargs) -> None:
112 """Invoked upon completion of the setup attempt.
113
114 If setup was successful, the connection is provided to the user.
115
116 Note that the network connection stays alive until it is closed,
117 even if no local references to the connection object remain.
118 The user should store a reference to this connection, and call
119 `connection.close()` when they are done with it to avoid leaking
120 resources.
121
122 Setup will always be the first callback invoked on the handler.
123 If setup failed, no further callbacks will be invoked on this handler.
124
125 Args:
126 connection: The connection, if setup was successful,
127 or None if setup failed.
128
129 error: None, if setup was successful, or an Exception
130 if setup failed.
131
132 `**kwargs`: Forward compatibility kwargs.
133 """
134 pass
135
136 @abstractmethod
137 def on_connection_shutdown(self, reason: Optional[Exception], **kwargs) -> None:
138 """Invoked when the connection finishes shutting down.
139
140 This event will not be invoked if connection setup failed.
141
142 Args:
143 reason: Reason will be None if the user initiated the shutdown,
144 otherwise the reason will be an Exception.
145
146 **kwargs: Forward compatibility kwargs.
147 """
148 pass
149
150 @abstractmethod
151 def on_protocol_message(
152 self,
153 headers: Sequence[Header],
154 payload: bytes,
155 message_type: MessageType,
156 flags: int,
157 **kwargs) -> None:
158 """Invoked when a message for the connection (stream-id 0) is received.
159
160 Args:
161 headers: Message headers.
162
163 payload: Binary message payload.
164
165 message_type: Message type.
166
167 flags: Message flags. Values from :class:`MessageFlag` may be
168 XORed together. Not all flags can be used with all message
169 types, consult documentation.
170
171 **kwargs: Forward compatibility kwargs.
172 """
173
174 pass
175
176
177 def _to_binding_msg_args(headers, payload, message_type, flags):
178 """
179 Transform args that a python send-msg function would take,
180 into args that a native send-msg function would take.
181 """
182 # python functions for sending messages
183 if headers is None:
184 headers = []
185 else:
186 headers = [i._as_binding_tuple() for i in headers]
187 if payload is None:
188 payload = b''
189 if flags is None:
190 flags = MessageFlag.NONE
191 return (headers, payload, message_type, flags)
192
193
194 def _from_binding_msg_args(headers, payload, message_type, flags):
195 """
196 Transform msg-received args that came from native,
197 into msg-received args presented to python users.
198 """
199 headers = [Header._from_binding_tuple(i) for i in headers]
200 if payload is None:
201 payload = b''
202 message_type = MessageType(message_type)
203 return (headers, payload, message_type, flags)
204
205
206 def _on_message_flush(bound_future, bound_callback, error_code):
207 # invoked when a message is flushed (written to wire), or canceled due to connection error.
208 e = awscrt.exceptions.from_code(error_code) if error_code else None
209 try:
210 if bound_callback:
211 bound_callback(error=e)
212 finally:
213 # ensure future completes, even if user callback had unhandled exception
214 if error_code:
215 bound_future.set_exception(e)
216 else:
217 bound_future.set_result(None)
218
219
220 class ClientConnection(NativeResource):
221 """A client connection for the event-stream RPC protocol.
222
223 Use :meth:`ClientConnection.connect()` to establish a new
224 connection.
225
226 Note that the network connection stays alive until it is closed,
227 even if no local references to the connection object remain.
228 The user should store a reference to any connections, and call
229 :meth:`close()` when they are done with them to avoid leaking resources.
230
231 Attributes:
232 host_name (str): Remote host name.
233
234 port (int): Remote port.
235
236 shutdown_future (concurrent.futures.Future[None]): Completes when this
237 connection has finished shutting down. Future will contain a
238 result of None, or an exception indicating why shutdown occurred.
239 """
240
241 __slots__ = ['host_name', 'port', 'shutdown_future', '_connect_future', '_handler']
242
243 def __init__(self, host_name, port, handler):
244 # Do no instantiate directly, use static connect method
245 super().__init__()
246 self.host_name = host_name # type: str
247 self.port = port # type: int
248 self.shutdown_future = Future() # type: Future
249 self.shutdown_future.set_running_or_notify_cancel() # prevent cancel
250 self._connect_future = Future() # type: Future
251 self._connect_future.set_running_or_notify_cancel() # prevent cancel
252 self._handler = handler # type: ClientConnectionHandler
253
254 @classmethod
255 def connect(
256 cls,
257 *,
258 handler: ClientConnectionHandler,
259 host_name: str,
260 port: int,
261 bootstrap: ClientBootstrap = None,
262 socket_options: Optional[SocketOptions] = None,
263 tls_connection_options: Optional[TlsConnectionOptions] = None) -> 'concurrent.futures.Future':
264 """Asynchronously establish a new ClientConnection.
265
266 Args:
267 handler: Handler for connection events.
268
269 host_name: Connect to host.
270
271 port: Connect to port.
272
273 bootstrap: Client bootstrap to use when initiating socket connection.
274 If None is provided, the default singleton is used.
275
276 socket_options: Optional socket options.
277 If None is provided, then default options are used.
278
279 tls_connection_options: Optional TLS
280 connection options. If None is provided, then the connection will
281 be attempted over plain-text.
282
283 Returns:
284 concurrent.futures.Future: A Future which completes when the connection succeeds or fails.
285 If successful, the Future will contain None.
286 Otherwise it will contain an exception.
287 If the connection is successful, it will be made available via
288 the handler's on_connection_setup callback.
289 Note that this network connection stays alive until it is closed,
290 even if no local references to the connection object remain.
291 The user should store a reference to any connections, and call
292 :meth:`close()` when they are done with them to avoid leaking resources.
293 """
294
295 if not socket_options:
296 socket_options = SocketOptions()
297
298 # Connection is not made available to user until setup callback fires
299 connection = cls(host_name, port, handler)
300
301 if not bootstrap:
302 bootstrap = ClientBootstrap.get_or_create_static_default()
303
304 # connection._binding is set within the following call */
305 _awscrt.event_stream_rpc_client_connection_connect(
306 host_name,
307 port,
308 bootstrap,
309 socket_options,
310 tls_connection_options,
311 connection)
312
313 return connection._connect_future
314
315 def _on_connection_setup(self, error_code):
316 if error_code:
317 connection = None
318 error = awscrt.exceptions.from_code(error_code)
319 else:
320 connection = self
321 error = None
322
323 try:
324 self._handler.on_connection_setup(connection=connection, error=error)
325 finally:
326 # ensure future completes, even if user callback had unhandled exception
327 if error:
328 self._connect_future.set_exception(error)
329 else:
330 self._connect_future.set_result(None)
331
332 def _on_connection_shutdown(self, error_code):
333 reason = awscrt.exceptions.from_code(error_code) if error_code else None
334 try:
335 self._handler.on_connection_shutdown(reason=reason)
336 finally:
337 # ensure future completes, even if user callback had unhandled exception
338 if reason:
339 self.shutdown_future.set_exception(reason)
340 else:
341 self.shutdown_future.set_result(None)
342
343 def _on_protocol_message(self, headers, payload, message_type, flags):
344 # transform from simple types to actual classes
345 headers, payload, message_type, flags = _from_binding_msg_args(headers, payload, message_type, flags)
346 self._handler.on_protocol_message(
347 headers=headers,
348 payload=payload,
349 message_type=message_type,
350 flags=flags)
351
352 def close(self):
353 """Close the connection.
354
355 Shutdown is asynchronous. This call has no effect if the connection is
356 already closed or closing.
357
358 Note that, if the network connection hasn't already ended,
359 `close()` MUST be called to avoid leaking resources. The network
360 connection will not terminate simply because there are no references
361 to the connection object.
362
363 Returns:
364 concurrent.futures.Future: This connection's :attr:`shutdown_future`,
365 which completes when shutdown has finished.
366 """
367 # TODO: let user pass their own exception/error-code/reason for closing
368 _awscrt.event_stream_rpc_client_connection_close(self._binding)
369 return self.shutdown_future
370
371 def is_open(self):
372 """
373 Returns:
374 bool: True if this connection is open and usable, False otherwise.
375 Check :attr:`shutdown_future` to know when the connection is completely
376 finished shutting down.
377 """
378 return _awscrt.event_stream_rpc_client_connection_is_open(self._binding)
379
380 def send_protocol_message(
381 self,
382 *,
383 headers: Optional[Sequence[Header]] = None,
384 payload: Optional[Union[bytes, bytearray]] = None,
385 message_type: MessageType,
386 flags: Optional[int] = None,
387 on_flush: Callable = None) -> 'concurrent.futures.Future':
388 """Send a protocol message.
389
390 Protocol messages use stream-id 0.
391
392 Use the returned future, or the `on_flush` callback, to be informed
393 when the message is successfully written to the wire, or fails to send.
394
395 Keyword Args:
396 headers: Message headers.
397
398 payload: Binary message payload.
399
400 message_type: Message type.
401
402 flags: Message flags. Values from :class:`MessageFlag` may be
403 XORed together. Not all flags can be used with all message
404 types, consult documentation.
405
406 on_flush: Callback invoked when the message is successfully written
407 to the wire, or fails to send. The function should take the
408 following arguments and return nothing:
409
410 * `error` (Optional[Exception]): None if the message was
411 successfully written to the wire, or an Exception
412 if it failed to send.
413
414 * `**kwargs` (dict): Forward compatibility kwargs.
415
416 This callback is always invoked on the connection's event-loop
417 thread.
418
419 Returns:
420 A future which completes with a result of None if the
421 message is successfully written to the wire,
422 or an exception if the message fails to send.
423 """
424 future = Future()
425 future.set_running_or_notify_cancel() # prevent cancel
426
427 # native code deals with simplified types
428 headers, payload, message_type, flags = _to_binding_msg_args(headers, payload, message_type, flags)
429
430 _awscrt.event_stream_rpc_client_connection_send_protocol_message(
431 self._binding,
432 headers,
433 payload,
434 message_type,
435 flags,
436 partial(_on_message_flush, future, on_flush))
437 return future
438
439 def new_stream(self, handler: 'ClientContinuationHandler') -> 'ClientContinuation':
440 """
441 Create a new stream.
442
443 The stream will send no data until :meth:`ClientContinuation.activate()`
444 is called. Call activate() when you're ready for callbacks and events to fire.
445
446 Args:
447 handler: Handler to process continuation messages and state changes.
448
449 Returns:
450 The new continuation object.
451 """
452 continuation = ClientContinuation(handler, self)
453 continuation._binding = _awscrt.event_stream_rpc_client_connection_new_stream(self)
454 return continuation
455
456
457 class ClientContinuation(NativeResource):
458 """
459 A continuation of messages on a given stream-id.
460
461 Create with :meth:`ClientConnection.new_stream()`.
462
463 The stream will send no data until :meth:`ClientContinuation.activate()`
464 is called. Call activate() when you're ready for callbacks and events to fire.
465
466 Attributes:
467 connection (ClientConnection): This stream's connection.
468
469 closed_future (concurrent.futures.Future) : Future which completes with a result of None
470 when the continuation has closed.
471 """
472
473 def __init__(self, handler, connection):
474 # Do not instantiate directly, use ClientConnection.new_stream()
475 super().__init__()
476 self._handler = handler
477 self.connection = connection # type: ClientConnection
478 self.closed_future = Future() # type: Future
479 self.closed_future.set_running_or_notify_cancel() # prevent cancel
480
481 def activate(
482 self,
483 *,
484 operation: str,
485 headers: Sequence[Header] = None,
486 payload: Union[bytes, bytearray] = None,
487 message_type: MessageType,
488 flags: int = None,
489 on_flush: Callable = None):
490 """
491 Activate the stream by sending its first message.
492
493 Use the returned future, or the `on_flush` callback, to be informed
494 when the message is successfully written to the wire, or fails to send.
495
496 activate() may only be called once, use send_message() to write further
497 messages on this stream-id.
498
499 Keyword Args:
500 operation: Operation name for this stream.
501
502 headers: Message headers.
503
504 payload: Binary message payload.
505
506 message_type: Message type.
507
508 flags: Message flags. Values from :class:`MessageFlag` may be
509 XORed together. Not all flags can be used with all message
510 types, consult documentation.
511
512 on_flush: Callback invoked when the message is successfully written
513 to the wire, or fails to send. The function should take the
514 following arguments and return nothing:
515
516 * `error` (Optional[Exception]): None if the message was
517 successfully written to the wire, or an Exception
518 if it failed to send.
519
520 * `**kwargs` (dict): Forward compatibility kwargs.
521
522 This callback is always invoked on the connection's event-loop
523 thread.
524
525 Returns:
526 A future which completes with a result of None if the
527 message is successfully written to the wire,
528 or an exception if the message fails to send.
529 """
530
531 flush_future = Future()
532 flush_future.set_running_or_notify_cancel() # prevent cancel
533
534 # native code deals with simplified types
535 headers, payload, message_type, flags = _to_binding_msg_args(headers, payload, message_type, flags)
536
537 _awscrt.event_stream_rpc_client_continuation_activate(
538 self._binding,
539 # don't give binding a reference to self until activate() is called.
540 # this reference is used for invoking callbacks, and its existence
541 # keeps the python object alive until the closed callback fires
542 self,
543 operation,
544 headers,
545 payload,
546 message_type,
547 flags,
548 partial(_on_message_flush, flush_future, on_flush))
549
550 return flush_future
551
552 def send_message(
553 self,
554 *,
555 headers: Sequence[Header] = None,
556 payload: Union[bytes, bytearray] = None,
557 message_type: MessageType,
558 flags: int = None,
559 on_flush: Callable = None) -> 'concurrent.futures.Future':
560 """
561 Send a continuation message.
562
563 Use the returned future, or the `on_flush` callback, to be informed
564 when the message is successfully written to the wire, or fails to send.
565
566 Note that the the first message on a stream-id must be sent with activate(),
567 send_message() is for all messages that follow.
568
569 Keyword Args:
570 operation: Operation name for this stream.
571
572 headers: Message headers.
573
574 payload: Binary message payload.
575
576 message_type: Message type.
577
578 flags: Message flags. Values from :class:`MessageFlag` may be
579 XORed together. Not all flags can be used with all message
580 types, consult documentation.
581
582 on_flush: Callback invoked when the message is successfully written
583 to the wire, or fails to send. The function should take the
584 following arguments and return nothing:
585
586 * `error` (Optional[Exception]): None if the message was
587 successfully written to the wire, or an Exception
588 if it failed to send.
589
590 * `**kwargs` (dict): Forward compatibility kwargs.
591
592 This callback is always invoked on the connection's event-loop
593 thread.
594
595 Returns:
596 A future which completes with a result of None if the
597 message is successfully written to the wire,
598 or an exception if the message fails to send.
599 """
600 future = Future()
601 future.set_running_or_notify_cancel() # prevent cancel
602 # native code deals with simplified types
603 headers, payload, message_type, flags = _to_binding_msg_args(headers, payload, message_type, flags)
604
605 _awscrt.event_stream_rpc_client_continuation_send_message(
606 self._binding,
607 headers,
608 payload,
609 message_type,
610 flags,
611 partial(_on_message_flush, future, on_flush))
612 return future
613
614 def is_closed(self):
615 return _awscrt.event_stream_rpc_client_continuation_is_closed(self._binding)
616
617 def _on_continuation_closed(self):
618 try:
619 self._handler.on_continuation_closed()
620 finally:
621 # ensure future completes, even if user callback had unhandled exception
622 self.closed_future.set_result(None)
623
624 def _on_continuation_message(self, headers, payload, message_type, flags):
625 # transform from simple types to actual classes
626 headers, payload, message_type, flags = _from_binding_msg_args(headers, payload, message_type, flags)
627 self._handler.on_continuation_message(
628 headers=headers,
629 payload=payload,
630 message_type=message_type,
631 flags=flags)
632
633
634 class ClientContinuationHandler(ABC):
635 """Base class for handling stream continuation events.
636
637 Inherit from this class and override methods to handle events.
638 All callbacks will be invoked on the same thread (the same thread used by
639 the connection).
640
641 A common pattern is to store the continuation within its handler.
642 Example::
643
644 continuation_handler.continuation = connection.new_stream(continuation_handler)
645 """
646
647 @abstractmethod
648 def on_continuation_message(
649 self,
650 headers: Sequence[Header],
651 payload: bytes,
652 message_type: MessageType,
653 flags: int,
654 **kwargs) -> None:
655 """Invoked when a message is received on this continuation.
656
657 Args:
658 headers: Message headers.
659
660 payload: Binary message payload.
661
662 message_type: Message type.
663
664 flags: Message flags. Values from :class:`MessageFlag` may be
665 XORed together. Not all flags can be used with all message
666 types, consult documentation.
667
668 **kwargs: Forward compatibility kwargs.
669 """
670 pass
671
672 @abstractmethod
673 def on_continuation_closed(self, **kwargs) -> None:
674 """Invoked when the continuation is closed.
675
676 Once the continuation is closed, no more messages may be sent or received.
677 The continuation is closed when a message is sent or received with
678 the TERMINATE_STREAM flag, or when the connection shuts down.
679
680 Args:
681 **kwargs: Forward compatibility kwargs.
682 """
683 pass