Debian Codegraph @

python/proton/_events.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 threading
21
22 from cproton import PN_CONNECTION_BOUND, PN_CONNECTION_FINAL, PN_CONNECTION_INIT, PN_CONNECTION_LOCAL_CLOSE, \
23 PN_CONNECTION_LOCAL_OPEN, PN_CONNECTION_REMOTE_CLOSE, PN_CONNECTION_REMOTE_OPEN, PN_CONNECTION_UNBOUND, PN_DELIVERY, \
24 PN_LINK_FINAL, PN_LINK_FLOW, PN_LINK_INIT, PN_LINK_LOCAL_CLOSE, PN_LINK_LOCAL_DETACH, PN_LINK_LOCAL_OPEN, \
25 PN_LINK_REMOTE_CLOSE, PN_LINK_REMOTE_DETACH, PN_LINK_REMOTE_OPEN, PN_PYREF, PN_SESSION_FINAL, PN_SESSION_INIT, \
26 PN_SESSION_LOCAL_CLOSE, PN_SESSION_LOCAL_OPEN, PN_SESSION_REMOTE_CLOSE, PN_SESSION_REMOTE_OPEN, PN_TIMER_TASK, \
27 PN_TRANSPORT, PN_TRANSPORT_CLOSED, PN_TRANSPORT_ERROR, PN_TRANSPORT_HEAD_CLOSED, PN_TRANSPORT_TAIL_CLOSED, \
28 pn_cast_pn_connection, pn_cast_pn_delivery, pn_cast_pn_link, pn_cast_pn_session, pn_cast_pn_transport, \
29 pn_class_name, pn_collector, pn_collector_free, pn_collector_more, pn_collector_peek, pn_collector_pop, \
30 pn_collector_put, pn_collector_release, pn_event_class, pn_event_connection, pn_event_context, pn_event_delivery, \
31 pn_event_link, pn_event_session, pn_event_transport, pn_event_type, pn_event_type_name, pn_py2void, pn_void2py
32
33 from ._delivery import Delivery
34 from ._endpoints import Connection, Link, Session
35 from ._transport import Transport
36 from typing import Any, List, Optional, Union, TYPE_CHECKING, Callable, Tuple, Type
37
38 if TYPE_CHECKING:
39 from ._reactor import Container
40 from ._endpoints import Receiver, Sender
41 from ._handlers import ConnectSelectable
42 from ._selectable import Selectable
43 from types import TracebackType
44
45
46 class Collector:
47
48 def __init__(self) -> None:
49 self._impl = pn_collector()
50
51 def put(self, obj: 'Selectable', etype: 'EventType') -> None:
52 pn_collector_put(self._impl, PN_PYREF, pn_py2void(obj), etype.number)
53
54 def peek(self) -> Optional['Event']:
55 return Event.wrap(pn_collector_peek(self._impl))
56
57 def more(self) -> bool:
58 return pn_collector_more(self._impl)
59
60 def pop(self) -> None:
61 ev = self.peek()
62 pn_collector_pop(self._impl)
63
64 def release(self) -> None:
65 pn_collector_release(self._impl)
66
67 def __del__(self) -> None:
68 pn_collector_free(self._impl)
69 del self._impl
70
71
72 if "TypeExtender" not in globals():
73 class TypeExtender:
74 def __init__(self, number: int) -> None:
75 self.number = number
76
77 def next(self) -> int:
78 try:
79 return self.number
80 finally:
81 self.number += 1
82
83
84 class EventType(object):
85 """
86 Connects an event number to an event name, and is used
87 internally by :class:`Event` to represent all known
88 event types. A global list of events is maintained. An
89 :class:`EventType` created with a name but no number is
90 treated as an *extended* event, and is assigned an
91 internal event number starting at 10000.
92 """
93 _lock = threading.Lock()
94 _extended = TypeExtender(10000)
95 TYPES = {}
96
97 def __init__(self, name: Optional[str] = None, number: Optional[int] = None, method: Optional[str] = None) -> None:
98 if name is None and number is None:
99 raise TypeError("extended events require a name")
100 try:
101 self._lock.acquire()
102 if name is None:
103 name = pn_event_type_name(number)
104
105 if number is None:
106 number = self._extended.next()
107
108 if method is None:
109 method = "on_%s" % name
110
111 self.name = name
112 self.number = number
113 self.method = method
114
115 self.TYPES[number] = self
116 finally:
117 self._lock.release()
118
119 def __repr__(self):
120 return "EventType(name=%s, number=%d)" % (self.name, self.number)
121
122 def __str__(self):
123 return self.name
124
125
126 def _dispatch(handler: Any, method: str, *args) -> None:
127 m = getattr(handler, method, None)
128 if m:
129 m(*args)
130 elif hasattr(handler, "on_unhandled"):
131 handler.on_unhandled(method, *args)
132
133
134 class EventBase(object):
135
136 def __init__(self, type: EventType) -> None:
137 self._type = type
138
139 @property
140 def type(self) -> EventType:
141 """The type of this event."""
142 return self._type
143
144 @property
145 def handler(self) -> Optional['Handler']:
146 """The handler for this event type. Not implemented, always returns ``None``."""
147 return None
148
149 def dispatch(self, handler: 'Handler', type: Optional[EventType] = None) -> None:
150 """
151 Process this event by sending it to all known handlers that
152 are valid for this event type.
153
154 :param handler: Parent handler to process this event
155 :param type: Event type
156 """
157 type = type or self._type
158 _dispatch(handler, type.method, self)
159 if hasattr(handler, "handlers"):
160 for h in handler.handlers:
161 self.dispatch(h, type)
162
163 def __repr__(self) -> str:
164 return "%s(%r)" % (self._type, self.context)
165
166
167 def _core(number: int, method: str) -> EventType:
168 return EventType(number=number, method=method)
169
170
171 def _internal(name: str) -> EventType:
172 return EventType(name=name)
173
174
175 wrappers = {
176 "pn_void": lambda x: pn_void2py(x),
177 "pn_pyref": lambda x: pn_void2py(x),
178 "pn_connection": lambda x: Connection.wrap(pn_cast_pn_connection(x)),
179 "pn_session": lambda x: Session.wrap(pn_cast_pn_session(x)),
180 "pn_link": lambda x: Link.wrap(pn_cast_pn_link(x)),
181 "pn_delivery": lambda x: Delivery.wrap(pn_cast_pn_delivery(x)),
182 "pn_transport": lambda x: Transport.wrap(pn_cast_pn_transport(x))
183 }
184
185
186 class Event(EventBase):
187 """
188 Notification of a state change in the protocol engine.
189 """
190 TIMER_TASK = _core(PN_TIMER_TASK, "on_timer_task")
191 """A timer event has occurred."""
192
193 CONNECTION_INIT = _core(PN_CONNECTION_INIT, "on_connection_init")
194 """
195 The connection has been created. This is the first event that
196 will ever be issued for a connection. Events of this type point
197 to the relevant connection.
198 """
199
200 CONNECTION_BOUND = _core(PN_CONNECTION_BOUND, "on_connection_bound")
201 """
202 The connection has been bound to a transport. This event is
203 issued when the :meth:`Transport.bind` operation is invoked.
204 """
205
206 CONNECTION_UNBOUND = _core(PN_CONNECTION_UNBOUND, "on_connection_unbound")
207 """
208 The connection has been unbound from its transport. This event is
209 issued when the :meth:`Transport.unbind` operation is invoked.
210 """
211
212 CONNECTION_LOCAL_OPEN = _core(PN_CONNECTION_LOCAL_OPEN, "on_connection_local_open")
213 """
214 The local connection endpoint has been closed. Events of this
215 type point to the relevant connection.
216 """
217
218 CONNECTION_LOCAL_CLOSE = _core(PN_CONNECTION_LOCAL_CLOSE, "on_connection_local_close")
219 """
220 The local connection endpoint has been closed. Events of this
221 type point to the relevant connection.
222 """
223
224 CONNECTION_REMOTE_OPEN = _core(PN_CONNECTION_REMOTE_OPEN, "on_connection_remote_open")
225 """
226 The remote endpoint has opened the connection. Events of this
227 type point to the relevant connection.
228 """
229
230 CONNECTION_REMOTE_CLOSE = _core(PN_CONNECTION_REMOTE_CLOSE, "on_connection_remote_close")
231 """
232 The remote endpoint has closed the connection. Events of this
233 type point to the relevant connection.
234 """
235
236 CONNECTION_FINAL = _core(PN_CONNECTION_FINAL, "on_connection_final")
237 """
238 The connection has been freed and any outstanding processing has
239 been completed. This is the final event that will ever be issued
240 for a connection.
241 """
242
243 SESSION_INIT = _core(PN_SESSION_INIT, "on_session_init")
244 """
245 The session has been created. This is the first event that will
246 ever be issued for a session.
247 """
248
249 SESSION_LOCAL_OPEN = _core(PN_SESSION_LOCAL_OPEN, "on_session_local_open")
250 """
251 The local session endpoint has been opened. Events of this type
252 point to the relevant session.
253 """
254
255 SESSION_LOCAL_CLOSE = _core(PN_SESSION_LOCAL_CLOSE, "on_session_local_close")
256 """
257 The local session endpoint has been closed. Events of this type
258 point ot the relevant session.
259 """
260
261 SESSION_REMOTE_OPEN = _core(PN_SESSION_REMOTE_OPEN, "on_session_remote_open")
262 """
263 The remote endpoint has opened the session. Events of this type
264 point to the relevant session.
265 """
266
267 SESSION_REMOTE_CLOSE = _core(PN_SESSION_REMOTE_CLOSE, "on_session_remote_close")
268 """
269 The remote endpoint has closed the session. Events of this type
270 point to the relevant session.
271 """
272
273 SESSION_FINAL = _core(PN_SESSION_FINAL, "on_session_final")
274 """
275 The session has been freed and any outstanding processing has
276 been completed. This is the final event that will ever be issued
277 for a session.
278 """
279
280 LINK_INIT = _core(PN_LINK_INIT, "on_link_init")
281 """
282 The link has been created. This is the first event that will ever
283 be issued for a link.
284 """
285
286 LINK_LOCAL_OPEN = _core(PN_LINK_LOCAL_OPEN, "on_link_local_open")
287 """
288 The local link endpoint has been opened. Events of this type
289 point ot the relevant link.
290 """
291
292 LINK_LOCAL_CLOSE = _core(PN_LINK_LOCAL_CLOSE, "on_link_local_close")
293 """
294 The local link endpoint has been closed. Events of this type
295 point to the relevant link.
296 """
297
298 LINK_LOCAL_DETACH = _core(PN_LINK_LOCAL_DETACH, "on_link_local_detach")
299 """
300 The local link endpoint has been detached. Events of this type
301 point to the relevant link.
302 """
303
304 LINK_REMOTE_OPEN = _core(PN_LINK_REMOTE_OPEN, "on_link_remote_open")
305 """
306 The remote endpoint has opened the link. Events of this type
307 point to the relevant link.
308 """
309
310 LINK_REMOTE_CLOSE = _core(PN_LINK_REMOTE_CLOSE, "on_link_remote_close")
311 """
312 The remote endpoint has closed the link. Events of this type
313 point to the relevant link.
314 """
315
316 LINK_REMOTE_DETACH = _core(PN_LINK_REMOTE_DETACH, "on_link_remote_detach")
317 """
318 The remote endpoint has detached the link. Events of this type
319 point to the relevant link.
320 """
321
322 LINK_FLOW = _core(PN_LINK_FLOW, "on_link_flow")
323 """
324 The flow control state for a link has changed. Events of this
325 type point to the relevant link.
326 """
327
328 LINK_FINAL = _core(PN_LINK_FINAL, "on_link_final")
329 """
330 The link has been freed and any outstanding processing has been
331 completed. This is the final event that will ever be issued for a
332 link. Events of this type point to the relevant link.
333 """
334
335 DELIVERY = _core(PN_DELIVERY, "on_delivery")
336 """
337 A delivery has been created or updated. Events of this type point
338 to the relevant delivery.
339 """
340
341 TRANSPORT = _core(PN_TRANSPORT, "on_transport")
342 """
343 The transport has new data to read and/or write. Events of this
344 type point to the relevant transport.
345 """
346
347 TRANSPORT_ERROR = _core(PN_TRANSPORT_ERROR, "on_transport_error")
348 """
349 Indicates that a transport error has occurred. Use :attr:`Transport.condition`
350 to access the details of the error from the associated transport.
351 """
352
353 TRANSPORT_HEAD_CLOSED = _core(PN_TRANSPORT_HEAD_CLOSED, "on_transport_head_closed")
354 """
355 Indicates that the "head" or writing end of the transport has been closed. This
356 means the transport will never produce more bytes for output to
357 the network. Events of this type point to the relevant transport.
358 """
359
360 TRANSPORT_TAIL_CLOSED = _core(PN_TRANSPORT_TAIL_CLOSED, "on_transport_tail_closed")
361 """
362 Indicates that the "tail" of the transport has been closed. This
363 means the transport will never be able to process more bytes from
364 the network. Events of this type point to the relevant transport.
365 """
366
367 TRANSPORT_CLOSED = _core(PN_TRANSPORT_CLOSED, "on_transport_closed")
368 """
369 Indicates that the both the "head" and "tail" of the transport are
370 closed. Events of this type point to the relevant transport.
371 """
372
373 # These events are now internal events in the python code
374 REACTOR_INIT = _internal("reactor_init")
375 """
376 A reactor has been started. Events of this type point to the
377 reactor.
378 """
379
380 REACTOR_QUIESCED = _internal("reactor_quiesced")
381 """
382 A reactor has no more events to process. Events of this type
383 point to the reactor.
384 """
385
386 REACTOR_FINAL = _internal("reactor_final")
387 """
388 A reactor has been stopped. Events of this type point to the
389 reactor.
390 """
391
392 SELECTABLE_INIT = _internal("selectable_init")
393 SELECTABLE_UPDATED = _internal("selectable_updated")
394 SELECTABLE_READABLE = _internal("selectable_readable")
395 SELECTABLE_WRITABLE = _internal("selectable_writable")
396 SELECTABLE_EXPIRED = _internal("selectable_expired")
397 SELECTABLE_ERROR = _internal("selectable_error")
398 SELECTABLE_FINAL = _internal("selectable_final")
399
400 @staticmethod
401 def wrap(impl):
402 if impl is None:
403 return None
404
405 number = pn_event_type(impl)
406 cls = pn_event_class(impl)
407
408 if cls:
409 clsname = pn_class_name(cls)
410 context = wrappers[clsname](pn_event_context(impl))
411
412 # check for an application defined ApplicationEvent and return that. This
413 # avoids an expensive wrap operation invoked by event.context
414 if cls == PN_PYREF and isinstance(context, EventBase):
415 return context
416 else:
417 clsname = None
418
419 event = Event(impl, number, clsname, context)
420 return event
421
422 def __init__(self, impl, number, clsname, context):
423 self._type = EventType.TYPES[number]
424 self._clsname = clsname
425 self._context = context
426
427 # Do all this messing around to avoid duplicate wrappers
428 if issubclass(type(context), Delivery):
429 self._delivery = context
430 else:
431 self._delivery = Delivery.wrap(pn_event_delivery(impl))
432 if self._delivery:
433 self._link = self._delivery.link
434 elif issubclass(type(context), Link):
435 self._link = context
436 else:
437 self._link = Link.wrap(pn_event_link(impl))
438 if self._link:
439 self._session = self._link.session
440 elif issubclass(type(context), Session):
441 self._session = context
442 else:
443 self._session = Session.wrap(pn_event_session(impl))
444 if self._session:
445 self._connection = self._session.connection
446 elif issubclass(type(context), Connection):
447 self._connection = context
448 else:
449 self._connection = Connection.wrap(pn_event_connection(impl))
450
451 if issubclass(type(context), Transport):
452 self._transport = context
453 else:
454 self._transport = Transport.wrap(pn_event_transport(impl))
455
456 @property
457 def clazz(self) -> str:
458 """
459 The name of the class associated with the event context.
460 """
461 return self._clsname
462
463 @property
464 def context(self) -> Union[Optional[Any], Connection, Session, Link, Delivery, Transport]:
465 """
466 The context object associated with the event.
467
468 :type: Depends on the type of event, and include the following:
469 - :class:`Connection`
470 - :class:`Session`
471 - :class:`Link`
472 - :class:`Delivery`
473 - :class:`Transport`
474 """
475 return self._context
476
477 @property
478 def handler(self) -> Optional['Handler']:
479 """
480 The handler for this event. The handler is determined by looking
481 at the following in order:
482
483 - The link
484 - The session
485 - The connection
486 - The context object with an attribute "handler"
487
488 If none of these has a handler, then ``None`` is returned.
489 """
490 l = self.link
491 if l:
492 h = l.handler
493 if h:
494 return h
495 s = self.session
496 if s:
497 h = s.handler
498 if h:
499 return h
500 c = self.connection
501 if c:
502 h = c.handler
503 if h:
504 return h
505 c = self.context
506 if not c or not hasattr(c, 'handler'):
507 return None
508 h = c.handler
509 return h
510
511 @property
512 def reactor(self) -> 'Container':
513 """
514 **Deprecated** - The :class:`reactor.Container` (was reactor) associated with the event.
515 """
516 return self.container
517
518 @property
519 def container(self) -> 'Container':
520 """
521 The :class:`reactor.Container` associated with the event.
522 """
523 return self._transport._reactor
524
525 def __getattr__(self, name: str) -> Any:
526 """
527 This will look for a property of the event as an attached context object of the same
528 type as the property (but lowercase)
529 """
530 c = self.context
531 # Direct type or subclass of type
532 if type(c).__name__.lower() == name or name in [x.__name__.lower() for x in type(c).__bases__]:
533 return c
534
535 # If the attached object is the wrong type then see if *it* has a property of that name
536 return getattr(c, name, None)
537
538 @property
539 def transport(self) -> Optional[Transport]:
540 """
541 The transport associated with the event, or ``None`` if none
542 is associated with it.
543 """
544 return self._transport
545
546 @property
547 def connection(self) -> Optional[Connection]:
548 """
549 The connection associated with the event, or ``None`` if none
550 is associated with it.
551 """
552 return self._connection
553
554 @property
555 def session(self) -> Optional[Session]:
556 """
557 The session associated with the event, or ``None`` if none
558 is associated with it.
559 """
560 return self._session
561
562 @property
563 def link(self) -> Optional[Union['Receiver', 'Sender']]:
564 """
565 The link associated with the event, or ``None`` if none
566 is associated with it.
567 """
568 return self._link
569
570 @property
571 def sender(self) -> Optional['Sender']:
572 """
573 The sender link associated with the event, or ``None`` if
574 none is associated with it. This is essentially an alias for
575 ``link`` property, that does an additional check on the type of the
576 link.
577 """
578 l = self.link
579 if l and l.is_sender:
580 return l
581 else:
582 return None
583
584 @property
585 def receiver(self) -> Optional['Receiver']:
586 """
587 The receiver link associated with the event, or ``None`` if
588 none is associated with it. This is essentially an alias for
589 ``link`` property, that does an additional check on the type of the link.
590 """
591 l = self.link
592 if l and l.is_receiver:
593 return l
594 else:
595 return None
596
597 @property
598 def delivery(self) -> Optional[Delivery]:
599 """
600 The delivery associated with the event, or ``None`` if none
601 is associated with it.
602 """
603 return self._delivery
604
605
606 class LazyHandlers(object):
607 def __get__(self, obj: 'Handler', clazz: Any) -> Union['LazyHandlers', List[Any]]:
608 if obj is None:
609 return self
610 ret = []
611 obj.__dict__['handlers'] = ret
612 return ret
613
614
615 class Handler(object):
616 """
617 An abstract handler for events which supports child handlers.
618 """
619 handlers = LazyHandlers()
620
621 # TODO What to do with on_error?
622 def add(
623 self,
624 handler: Any,
625 on_error: Optional[Callable[[Tuple[Type[BaseException], BaseException, 'TracebackType']], None]] = None,
626 ) -> None:
627 """
628 Add a child handler
629
630 :param handler: A child handler
631 :type handler: :class:`Handler` or one of its derivatives.
632 :param on_error: Not used
633 """
634 self.handlers.append(handler)
635
636 def on_unhandled(self, method: str, *args) -> None:
637 """
638 The callback for handling events which are not handled by
639 any other handler.
640
641 :param method: The name of the intended handler method.
642 :param args: Arguments for the intended handler method.
643 """
644 pass