Debian Codegraph @

python/proton/_utils.py

raw
1 #
2 # Licensed to the Apache Software Foundation (ASF) under one
3 # or more contributor license agreements. See the NOTICE file
4 # distributed with this work for additional information
5 # regarding copyright ownership. The ASF licenses this file
6 # to you under the Apache License, Version 2.0 (the
7 # "License"); you may not use this file except in compliance
8 # with the License. You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing,
13 # software distributed under the License is distributed on an
14 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 # KIND, either express or implied. See the License for the
16 # specific language governing permissions and limitations
17 # under the License.
18 #
19
20 import collections
21 import time
22 import threading
23
24 from ._exceptions import ProtonException, ConnectionException, LinkException, Timeout
25 from ._delivery import Delivery
26 from ._endpoints import Endpoint, Link
27 from ._events import Handler
28 from ._url import Url
29
30 from ._reactor import Container
31 from ._handlers import MessagingHandler, IncomingMessageHandler
32
33 from typing import Callable, Optional, Union, TYPE_CHECKING, List, Any
34
35 try:
36 from typing import Literal
37 except ImportError:
38 # https://www.python.org/dev/peps/pep-0560/#class-getitem
39 class GenericMeta(type):
40 def __getitem__(self, item):
41 pass
42
43 class Literal(metaclass=GenericMeta):
44 pass
45
46 if TYPE_CHECKING:
47 from ._delivery import DispositionType
48 from ._transport import SSLDomain
49 from ._reactor import SenderOption, ReceiverOption, Connection, LinkOption, Backoff
50 from ._endpoints import Receiver, Sender
51 from ._events import Event
52 from ._message import Message
53
54
55 class BlockingLink:
56 def __init__(self, connection: 'BlockingConnection', link: Union['Sender', 'Receiver']) -> None:
57 self.connection = connection
58 self.link = link
59 self.connection.wait(lambda: not (self.link.state & Endpoint.REMOTE_UNINIT),
60 msg="Opening link %s" % link.name)
61 self._checkClosed()
62
63 def _waitForClose(self, timeout=1):
64 try:
65 self.connection.wait(lambda: self.link.state & Endpoint.REMOTE_CLOSED,
66 timeout=timeout,
67 msg="Opening link %s" % self.link.name)
68 except Timeout as e:
69 pass
70 self._checkClosed()
71
72 def _checkClosed(self) -> None:
73 if self.link.state & Endpoint.REMOTE_CLOSED:
74 self.link.close()
75 if not self.connection.closing:
76 raise LinkDetached(self.link)
77
78 def close(self):
79 """
80 Close the link.
81 """
82 self.link.close()
83 self.connection.wait(lambda: not (self.link.state & Endpoint.REMOTE_ACTIVE),
84 msg="Closing link %s" % self.link.name)
85
86 # Access to other link attributes.
87 def __getattr__(self, name: str) -> Any:
88 return getattr(self.link, name)
89
90
91 class SendException(ProtonException):
92 """
93 Exception used to indicate an exceptional state/condition on a send request.
94
95 :param state: The delivery state which caused the exception.
96 """
97
98 def __init__(self, state: int) -> None:
99 self.state = state
100
101
102 def _is_settled(delivery: Delivery) -> bool:
103 return delivery.settled or delivery.link.snd_settle_mode == Link.SND_SETTLED
104
105
106 class BlockingSender(BlockingLink):
107 """
108 A synchronous sender wrapper. This is typically created by calling
109 :meth:`BlockingConnection.create_sender`.
110 """
111
112 def __init__(self, connection: 'BlockingConnection', sender: 'Sender') -> None:
113 super(BlockingSender, self).__init__(connection, sender)
114 if self.link.target and self.link.target.address and self.link.target.address != self.link.remote_target.address:
115 # this may be followed by a detach, which may contain an error condition, so wait a little...
116 self._waitForClose()
117 # ...but close ourselves if peer does not
118 self.link.close()
119 raise LinkException("Failed to open sender %s, target does not match" % self.link.name)
120
121 def send(
122 self,
123 msg: 'Message',
124 timeout: Union[None, Literal[False], float] = False,
125 error_states: Optional[List['DispositionType']] = None,
126 ) -> Delivery:
127 """
128 Blocking send which will return only when the send is complete
129 and the message settled.
130
131 :param timeout: Timeout in seconds. If ``False``, the value of ``timeout`` used in the
132 constructor of the :class:`BlockingConnection` object used in the constructor will be used.
133 If ``None``, there is no timeout. Any other value is treated as a timeout in seconds.
134 :param error_states: List of delivery flags which when present in Delivery object
135 will cause a :class:`SendException` exception to be raised. If ``None``, these
136 will default to a list containing :const:`proton.Delivery.REJECTED` and :const:`proton.Delivery.RELEASED`.
137 :return: Delivery object for this message.
138 """
139 delivery = self.link.send(msg)
140 self.connection.wait(lambda: _is_settled(delivery), msg="Sending on sender %s" % self.link.name,
141 timeout=timeout)
142 if delivery.link.snd_settle_mode != Link.SND_SETTLED:
143 delivery.settle()
144 bad = error_states
145 if bad is None:
146 bad = [Delivery.REJECTED, Delivery.RELEASED]
147 if delivery.remote_state in bad:
148 raise SendException(delivery.remote_state)
149 return delivery
150
151
152 class Fetcher(MessagingHandler):
153 """
154 A message handler for blocking receivers.
155 """
156
157 def __init__(self, connection: 'Connection', prefetch: int):
158 super(Fetcher, self).__init__(prefetch=prefetch, auto_accept=False)
159 self.connection = connection
160 self.incoming = collections.deque([])
161 self.unsettled = collections.deque([])
162
163 def on_message(self, event: 'Event') -> None:
164 self.incoming.append((event.message, event.delivery))
165 self.connection.container.yield_() # Wake up the wait() loop to handle the message.
166
167 def on_link_error(self, event: 'Event') -> None:
168 if event.link.state & Endpoint.LOCAL_ACTIVE:
169 event.link.close()
170 if not self.connection.closing:
171 raise LinkDetached(event.link)
172
173 def on_connection_error(self, event: 'Event') -> None:
174 if not self.connection.closing:
175 raise ConnectionClosed(event.connection)
176
177 @property
178 def has_message(self) -> int:
179 """
180 The number of messages that have been received and are waiting to be
181 retrieved with :meth:`pop`.
182 """
183 return len(self.incoming)
184
185 def pop(self) -> 'Message':
186 """
187 Get the next available incoming message. If the message is unsettled, its
188 delivery object is moved onto the unsettled queue, and can be settled with
189 a call to :meth:`settle`.
190 """
191 message, delivery = self.incoming.popleft()
192 if not delivery.settled:
193 self.unsettled.append(delivery)
194 return message
195
196 def settle(self, state: Optional[int] = None) -> None:
197 """
198 Settle the next message previously taken with :meth:`pop`.
199
200 :param state:
201 :type state:
202 """
203 delivery = self.unsettled.popleft()
204 if state:
205 delivery.update(state)
206 delivery.settle()
207
208
209 class BlockingReceiver(BlockingLink):
210 """
211 A synchronous receiver wrapper. This is typically created by calling
212 :meth:`BlockingConnection.create_receiver`.
213 """
214
215 def __init__(
216 self,
217 connection: 'BlockingConnection',
218 receiver: 'Receiver',
219 fetcher: Optional[Fetcher],
220 credit: int = 1
221 ) -> None:
222 super(BlockingReceiver, self).__init__(connection, receiver)
223 if self.link.source and self.link.source.address and self.link.source.address != self.link.remote_source.address:
224 # this may be followed by a detach, which may contain an error condition, so wait a little...
225 self._waitForClose()
226 # ...but close ourselves if peer does not
227 self.link.close()
228 raise LinkException("Failed to open receiver %s, source does not match" % self.link.name)
229 if credit:
230 receiver.flow(credit)
231 self.fetcher = fetcher
232 self.container = connection.container
233
234 def __del__(self):
235 self.fetcher = None
236 # The next line causes a core dump if the Proton-C reactor finalizes
237 # first. The self.container reference prevents out of order reactor
238 # finalization. It may not be set if exception in BlockingLink.__init__
239 if hasattr(self, "container"):
240 self.link.handler = None # implicit call to reactor
241
242 def receive(
243 self,
244 timeout: Union[None, Literal[False], float] = False
245 ) -> 'Message':
246 """
247 Blocking receive call which will return only when a message is received or
248 a timeout (if supplied) occurs.
249
250 :param timeout: Timeout in seconds. If ``False``, the value of ``timeout`` used in the
251 constructor of the :class:`BlockingConnection` object used in the constructor will be used.
252 If ``None``, there is no timeout. Any other value is treated as a timeout in seconds.
253 """
254 if not self.fetcher:
255 raise Exception("Can't call receive on this receiver as a handler was not provided")
256 if not self.link.credit:
257 self.link.flow(1)
258 self.connection.wait(lambda: self.fetcher.has_message, msg="Receiving on receiver %s" % self.link.name,
259 timeout=timeout)
260 return self.fetcher.pop()
261
262 def accept(self) -> None:
263 """
264 Accept and settle the received message. The delivery is set to
265 :const:`proton.Delivery.ACCEPTED`.
266 """
267 self.settle(Delivery.ACCEPTED)
268
269 def reject(self) -> None:
270 """
271 Reject the received message. The delivery is set to
272 :const:`proton.Delivery.REJECTED`.
273 """
274 self.settle(Delivery.REJECTED)
275
276 def release(self, delivered: bool = True) -> None:
277 """
278 Release the received message.
279
280 :param delivered: If ``True``, the message delivery is being set to
281 :const:`proton.Delivery.MODIFIED`, ie being returned to the sender
282 and annotated. If ``False``, the message is returned without
283 annotations and the delivery set to :const:`proton.Delivery.RELEASED`.
284 """
285 if delivered:
286 self.settle(Delivery.MODIFIED)
287 else:
288 self.settle(Delivery.RELEASED)
289
290 def settle(self, state: Optional['DispositionType'] = None):
291 """
292 Settle any received messages.
293
294 :param state: Update the delivery of all unsettled messages with the
295 supplied state, then settle them.
296 :type state: ``None`` or a valid delivery state (see
297 :class:`proton.Delivery`.
298 """
299 if not self.fetcher:
300 raise Exception("Can't call accept/reject etc on this receiver as a handler was not provided")
301 self.fetcher.settle(state)
302
303
304 class LinkDetached(LinkException):
305 """
306 The exception raised when the remote peer unexpectedly closes a link in a blocking
307 context, or an unexpected link error occurs.
308
309 :param link: The link which closed unexpectedly.
310 """
311
312 def __init__(self, link: Link) -> None:
313 self.link = link
314 if link.is_sender:
315 txt = "sender %s to %s closed" % (link.name, link.target.address)
316 else:
317 txt = "receiver %s from %s closed" % (link.name, link.source.address)
318 if link.remote_condition:
319 txt += " due to: %s" % link.remote_condition
320 self.condition = link.remote_condition.name
321 else:
322 txt += " by peer"
323 self.condition = None
324 super(LinkDetached, self).__init__(txt)
325
326
327 class ConnectionClosed(ConnectionException):
328 """
329 The exception raised when the remote peer unexpectedly closes a connection in a blocking
330 context, or an unexpected connection error occurs.
331
332 :param connection: The connection which closed unexpectedly.
333 """
334
335 def __init__(self, connection: 'Connection') -> None:
336 self.connection = connection
337 txt = "Connection %s closed" % connection.hostname
338 if connection.remote_condition:
339 txt += " due to: %s" % connection.remote_condition
340 self.condition = connection.remote_condition.name
341 else:
342 txt += " by peer"
343 self.condition = None
344 super(ConnectionClosed, self).__init__(txt)
345
346
347 class BlockingConnection(Handler):
348 """
349 A synchronous style connection wrapper.
350
351 This object's implementation uses OS resources. To ensure they
352 are released when the object is no longer in use, make sure that
353 object operations are enclosed in a try block and that close() is
354 always executed on exit.
355
356 :param url: The connection URL.
357 :param timeout: Connection timeout in seconds. If ``None``, defaults to 60 seconds.
358 :param container: Container to process the events on the connection. If ``None``,
359 a new :class:`proton.Container` will be created.
360 :param ssl_domain:
361 :param heartbeat: A value in seconds indicating the desired frequency of
362 heartbeats used to test the underlying socket is alive.
363 :param urls: A list of connection URLs to try to connect to.
364 :param kwargs: Container keyword arguments. See :class:`proton.reactor.Container`
365 for a list of the valid kwargs.
366 """
367
368 def __init__(
369 self,
370 url: Optional[Union[str, Url]] = None,
371 timeout: Optional[float] = None,
372 container: Optional[Container] = None,
373 ssl_domain: Optional['SSLDomain'] = None,
374 heartbeat: Optional[float] = None,
375 urls: Optional[List[str]] = None,
376 reconnect: Union[None, Literal[False], 'Backoff'] = None,
377 **kwargs
378 ) -> None:
379 self.disconnected = False
380 self.timeout = timeout or 60
381 self.container = container or Container()
382 self.container.timeout = self.timeout
383 self.container.start()
384 self.conn = None
385 self.closing = False
386 # Preserve previous behaviour if neither reconnect nor urls are supplied
387 if url is not None and urls is None and reconnect is None:
388 reconnect = False
389 url = Url(url).defaults()
390 failed = True
391 try:
392 self.conn = self.container.connect(url=url, handler=self, ssl_domain=ssl_domain, reconnect=reconnect,
393 heartbeat=heartbeat, urls=urls, **kwargs)
394 self.wait(lambda: not (self.conn.state & Endpoint.REMOTE_UNINIT),
395 msg="Opening connection")
396 failed = False
397 finally:
398 if failed and self.conn:
399 self.close()
400
401 def create_sender(
402 self,
403 address: Optional[str],
404 handler: Optional[Handler] = None,
405 name: Optional[str] = None,
406 options: Optional[Union['SenderOption', List['SenderOption'], 'LinkOption', List['LinkOption']]] = None
407 ) -> BlockingSender:
408 """
409 Create a blocking sender.
410
411 :param address: Address of target node.
412 :param handler: Event handler for this sender.
413 :param name: Sender name.
414 :param options: A single option, or a list of sender options
415 :return: New blocking sender instance.
416 """
417 return BlockingSender(self, self.container.create_sender(self.conn, address, name=name, handler=handler,
418 options=options))
419
420 def create_receiver(
421 self,
422 address: Optional[str] = None,
423 credit: Optional[int] = None,
424 dynamic: bool = False,
425 handler: Optional[Handler] = None,
426 name: Optional[str] = None,
427 options: Optional[Union['ReceiverOption', List['ReceiverOption'], 'LinkOption', List['LinkOption']]] = None
428 ) -> BlockingReceiver:
429 """
430 Create a blocking receiver.
431
432 :param address: Address of source node.
433 :param credit: Initial link flow credit. If not set, will default to 1.
434 :param dynamic: If ``True``, indicates dynamic creation of the receiver.
435 :param handler: Event handler for this receiver.
436 :param name: Receiver name.
437 :param options: A single option, or a list of receiver options
438 :return: New blocking receiver instance.
439 """
440 prefetch = credit
441 if handler:
442 fetcher = None
443 if prefetch is None:
444 prefetch = 1
445 else:
446 fetcher = Fetcher(self, credit)
447 return BlockingReceiver(
448 self,
449 self.container.create_receiver(self.conn, address, name=name, dynamic=dynamic, handler=handler or fetcher,
450 options=options), fetcher, credit=prefetch)
451
452 def close(self) -> None:
453 """
454 Close the connection.
455 """
456 # TODO: provide stronger interrupt protection on cleanup. See PEP 419
457 if self.closing:
458 return
459 self.closing = True
460 self.container.errors = []
461 try:
462 if self.conn:
463 self.conn.close()
464 self.wait(lambda: not (self.conn.state & Endpoint.REMOTE_ACTIVE),
465 msg="Closing connection")
466 if self.conn.transport:
467 # Close tail to force transport cleanup without waiting/hanging for peer close frame.
468 self.conn.transport.close_tail()
469 finally:
470 self.conn.free()
471 # Nothing left to block on. Allow reactor to clean up.
472 self.run()
473 if self.conn:
474 self.conn.handler = None # break cyclical reference
475 self.conn = None
476 self.container.stop_events()
477 self.container = None
478
479 @property
480 def url(self) -> str:
481 """
482 The address for this connection.
483 """
484 return self.conn and self.conn.connected_address
485
486 def _is_closed(self) -> int:
487 return self.conn.state & (Endpoint.LOCAL_CLOSED | Endpoint.REMOTE_CLOSED)
488
489 def run(self) -> None:
490 """
491 Hand control over to the event loop (e.g. if waiting indefinitely for incoming messages)
492 """
493 while self.container.process():
494 pass
495 self.container.stop()
496 self.container.process()
497
498 def wait(
499 self,
500 condition: Callable[[], bool],
501 timeout: Union[None, Literal[False], float] = False,
502 msg: Optional[str] = None
503 ) -> None:
504 """
505 Process events until ``condition()`` returns ``True``.
506
507 :param condition: Condition which determines when the wait will end.
508 :param timeout: Timeout in seconds. If ``False``, the value of ``timeout`` used in the
509 constructor of this object will be used. If ``None``, there is no timeout. Any other
510 value is treated as a timeout in seconds.
511 :param msg: Context message for :class:`proton.Timeout` exception
512 """
513 if timeout is False:
514 timeout = self.timeout
515 if timeout is None:
516 while not condition() and not self.disconnected:
517 self.container.process()
518 else:
519 container_timeout = self.container.timeout
520 self.container.timeout = timeout
521 try:
522 deadline = time.time() + timeout
523 while not condition() and not self.disconnected:
524 self.container.process()
525 if deadline < time.time():
526 txt = "Connection %s timed out" % self.url
527 if msg:
528 txt += ": " + msg
529 raise Timeout(txt)
530 finally:
531 self.container.timeout = container_timeout
532 if self.disconnected and not self._is_closed():
533 raise ConnectionException(
534 "Connection %s disconnected: %s" % (self.url, self.disconnected))
535
536 def on_link_remote_close(self, event: 'Event') -> None:
537 """
538 Event callback for when the remote terminus closes.
539 """
540 if event.link.state & Endpoint.LOCAL_ACTIVE:
541 event.link.close()
542 if not self.closing:
543 raise LinkDetached(event.link)
544
545 def on_connection_remote_close(self, event: 'Event') -> None:
546 """
547 Event callback for when the link peer closes the connection.
548 """
549 if event.connection.state & Endpoint.LOCAL_ACTIVE:
550 event.connection.close()
551 if not self.closing:
552 raise ConnectionClosed(event.connection)
553
554 def on_transport_tail_closed(self, event: 'Event') -> None:
555 self.on_transport_closed(event)
556
557 def on_transport_head_closed(self, event: 'Event') -> None:
558 self.on_transport_closed(event)
559
560 def on_transport_closed(self, event: 'Event') -> None:
561 if not self.closing:
562 self.disconnected = event.transport.condition or "unknown"
563
564
565 class AtomicCount:
566 def __init__(self, start: int = 0, step: int = 1) -> None:
567 """Thread-safe atomic counter. Start at start, increment by step."""
568 self.count, self.step = start, step
569 self.lock = threading.Lock()
570
571 def next(self) -> int:
572 """Get the next value"""
573 self.lock.acquire()
574 self.count += self.step
575 result = self.count
576 self.lock.release()
577 return result
578
579
580 class SyncRequestResponse(IncomingMessageHandler):
581 """
582 Implementation of the synchronous request-response (aka RPC) pattern.
583 A single instance can send many requests to the same or different
584 addresses.
585
586 :param connection: Connection for requests and responses.
587 :param address: Address for all requests. If not specified, each request
588 must have the address property set. Successive messages may have
589 different addresses.
590 """
591
592 correlation_id = AtomicCount()
593
594 def __init__(self, connection: BlockingConnection, address: Optional[str] = None) -> None:
595 super(SyncRequestResponse, self).__init__()
596 self.connection = connection
597 self.address = address
598 self.sender = self.connection.create_sender(self.address)
599 # dynamic=true generates a unique address dynamically for this receiver.
600 # credit=1 because we want to receive 1 response message initially.
601 self.receiver = self.connection.create_receiver(None, dynamic=True, credit=1, handler=self)
602 self.response = None
603
604 def call(self, request: 'Message') -> 'Message':
605 """
606 Send a request message, wait for and return the response message.
607
608 :param request: Request message. If ``self.address`` is not set the
609 request message address must be set and will be used.
610 """
611 if not self.address and not request.address:
612 raise ValueError("Request message has no address: %s" % request)
613 request.reply_to = self.reply_to
614 request.correlation_id = correlation_id = str(self.correlation_id.next())
615 self.sender.send(request)
616
617 def wakeup():
618 return self.response and (self.response.correlation_id == correlation_id)
619
620 self.connection.wait(wakeup, msg="Waiting for response")
621 response = self.response
622 self.response = None # Ready for next response.
623 self.receiver.flow(1) # Set up credit for the next response.
624 return response
625
626 @property
627 def reply_to(self) -> str:
628 """
629 The dynamic address of our receiver.
630 """
631 return self.receiver.remote_source.address
632
633 def on_message(self, event: 'Event') -> None:
634 """
635 Called when we receive a message for our receiver.
636
637 :param event: The event which occurs when a message is received.
638 """
639 self.response = event.message
640 self.connection.container.yield_() # Wake up the wait() loop to handle the message.