Debian Codegraph @

python/proton/_message.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 from __future__ import absolute_import
21
22 from cproton import PN_DEFAULT_PRIORITY, PN_STRING, PN_UUID, PN_OVERFLOW, pn_error_text, pn_message, \
23 pn_message_annotations, pn_message_body, pn_message_clear, pn_message_decode, \
24 pn_message_encode, pn_message_error, pn_message_free, pn_message_get_address, pn_message_get_content_encoding, \
25 pn_message_get_content_type, pn_message_get_correlation_id, pn_message_get_creation_time, pn_message_get_delivery_count, \
26 pn_message_get_expiry_time, pn_message_get_group_id, pn_message_get_group_sequence, pn_message_get_id, pn_message_get_priority, \
27 pn_message_get_reply_to, pn_message_get_reply_to_group_id, pn_message_get_subject, pn_message_get_ttl, \
28 pn_message_get_user_id, pn_message_instructions, pn_message_is_durable, \
29 pn_message_is_first_acquirer, pn_message_is_inferred, pn_message_properties, pn_message_set_address, \
30 pn_message_set_content_encoding, pn_message_set_content_type, pn_message_set_correlation_id, pn_message_set_creation_time, \
31 pn_message_set_delivery_count, pn_message_set_durable, pn_message_set_expiry_time, pn_message_set_first_acquirer, \
32 pn_message_set_group_id, pn_message_set_group_sequence, pn_message_set_id, pn_message_set_inferred, pn_message_set_priority, \
33 pn_message_set_reply_to, pn_message_set_reply_to_group_id, pn_message_set_subject, \
34 pn_message_set_ttl, pn_message_set_user_id
35
36 from ._common import isinteger, millis2secs, secs2millis, unicode2utf8, utf82unicode
37 from ._data import char, Data, symbol, ulong, AnnotationDict
38 from ._endpoints import Link
39 from ._exceptions import EXCEPTIONS, MessageException
40 from uuid import UUID
41 from typing import Dict, Optional, Union, TYPE_CHECKING, overload
42
43 if TYPE_CHECKING:
44 from proton._delivery import Delivery
45 from proton._endpoints import Sender, Receiver
46 from proton._data import Described, PythonAMQPData
47
48
49 class Message(object):
50 """The :py:class:`Message` class is a mutable holder of message content.
51
52 :ivar instructions: delivery instructions for the message ("Delivery Annotations" in the AMQP 1.0 spec)
53 :vartype instructions: ``dict``
54 :ivar ~.annotations: infrastructure defined message annotations ("Message Annotations" in the AMQP 1.0 spec)
55 :vartype ~.annotations: ``dict``
56 :ivar ~.properties: application defined message properties
57 :vartype ~.properties: ``dict``
58 :ivar body: message body
59
60 :param kwargs: Message property name/value pairs to initialize the Message
61 """
62
63 DEFAULT_PRIORITY = PN_DEFAULT_PRIORITY
64 """ Default AMQP message priority"""
65
66 def __init__(
67 self,
68 body: Union[bytes, str, dict, list, int, float, 'UUID', 'Described', None] = None,
69 **kwargs
70 ) -> None:
71 self._msg = pn_message()
72 self.instructions = None
73 self.annotations = None
74 self.properties = None
75 self.body = body
76 for k, v in kwargs.items():
77 getattr(self, k) # Raise exception if it's not a valid attribute.
78 setattr(self, k, v)
79
80 def __del__(self) -> None:
81 if hasattr(self, "_msg"):
82 pn_message_free(self._msg)
83 del self._msg
84
85 def _check(self, err: int) -> int:
86 if err < 0:
87 exc = EXCEPTIONS.get(err, MessageException)
88 raise exc("[%s]: %s" % (err, pn_error_text(pn_message_error(self._msg))))
89 else:
90 return err
91
92 def _check_property_keys(self) -> None:
93 """
94 AMQP allows only string keys for properties. This function checks that this requirement is met
95 and raises a MessageException if not. However, in certain cases, conversions to string are
96 automatically performed:
97
98 1. When a key is a user-defined (non-AMQP) subclass of str.
99 AMQP types symbol and char, although derived from str, are not converted,
100 and result in an exception.
101 """
102 # We cannot make changes to the dict while iterating, so we
103 # must save and make the changes afterwards
104 changed_keys = []
105 for k in self.properties.keys():
106 if isinstance(k, str):
107 # strings and their subclasses
108 if type(k) is symbol or type(k) is char:
109 # Exclude symbol and char
110 raise MessageException('Application property key is not string type: key=%s %s' % (str(k), type(k)))
111 if type(k) is not str:
112 # Only for string subclasses, convert to string
113 changed_keys.append((k, str(k)))
114 else:
115 # Anything else: raise exception
116 raise MessageException('Application property key is not string type: key=%s %s' % (str(k), type(k)))
117 # Make the key changes
118 for old_key, new_key in changed_keys:
119 self.properties[new_key] = self.properties.pop(old_key)
120
121 def _pre_encode(self) -> None:
122 inst = Data(pn_message_instructions(self._msg))
123 ann = Data(pn_message_annotations(self._msg))
124 props = Data(pn_message_properties(self._msg))
125 body = Data(pn_message_body(self._msg))
126
127 inst.clear()
128 if self.instructions is not None:
129 inst.put_object(self.instructions)
130 ann.clear()
131 if self.annotations is not None:
132 ann.put_object(self.annotations)
133 props.clear()
134 if self.properties is not None:
135 self._check_property_keys()
136 props.put_object(self.properties)
137 body.clear()
138 if self.body is not None:
139 body.put_object(self.body)
140
141 def _post_decode(self) -> None:
142 inst = Data(pn_message_instructions(self._msg))
143 ann = Data(pn_message_annotations(self._msg))
144 props = Data(pn_message_properties(self._msg))
145 body = Data(pn_message_body(self._msg))
146
147 if inst.next():
148 self.instructions = inst.get_object()
149 else:
150 self.instructions = None
151 if ann.next():
152 self.annotations = ann.get_object()
153 else:
154 self.annotations = None
155 if props.next():
156 self.properties = props.get_object()
157 else:
158 self.properties = None
159 if body.next():
160 self.body = body.get_object()
161 else:
162 self.body = None
163
164 def clear(self) -> None:
165 """
166 Clears the contents of the :class:`Message`. All fields will be reset to
167 their default values.
168 """
169 pn_message_clear(self._msg)
170 self.instructions = None
171 self.annotations = None
172 self.properties = None
173 self.body = None
174
175 @property
176 def inferred(self) -> bool:
177 """The inferred flag for a message indicates how the message content
178 is encoded into AMQP sections. If inferred is true then binary and
179 list values in the body of the message will be encoded as AMQP DATA
180 and AMQP SEQUENCE sections, respectively. If inferred is false,
181 then all values in the body of the message will be encoded as AMQP
182 VALUE sections regardless of their type.
183
184 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
185 """
186 return pn_message_is_inferred(self._msg)
187
188 @inferred.setter
189 def inferred(self, value: bool) -> None:
190 self._check(pn_message_set_inferred(self._msg, bool(value)))
191
192 @property
193 def durable(self) -> bool:
194 """The durable property indicates that the message should be held durably
195 by any intermediaries taking responsibility for the message.
196
197 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
198 """
199 return pn_message_is_durable(self._msg)
200
201 @durable.setter
202 def durable(self, value: bool) -> None:
203 self._check(pn_message_set_durable(self._msg, bool(value)))
204
205 @property
206 def priority(self) -> int:
207 """The relative priority of the message, with higher numbers indicating
208 higher priority. The number of available priorities depends
209 on the implementation, but AMQP defines the default priority as
210 the value ``4``. See the
211 `OASIS AMQP 1.0 standard
212 <http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#type-header>`_
213 for more details on message priority.
214
215 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
216 """
217 return pn_message_get_priority(self._msg)
218
219 @priority.setter
220 def priority(self, value: int) -> None:
221 self._check(pn_message_set_priority(self._msg, value))
222
223 @property
224 def ttl(self) -> float:
225 """The time to live of the message measured in seconds. Expired messages
226 may be dropped.
227
228 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
229 """
230 return millis2secs(pn_message_get_ttl(self._msg))
231
232 @ttl.setter
233 def ttl(self, value: Union[float, int]) -> None:
234 self._check(pn_message_set_ttl(self._msg, secs2millis(value)))
235
236 @property
237 def first_acquirer(self) -> bool:
238 """``True`` iff the recipient is the first to acquire the message,
239 ``False`` otherwise.
240
241 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
242 """
243 return pn_message_is_first_acquirer(self._msg)
244
245 @first_acquirer.setter
246 def first_acquirer(self, value: bool) -> None:
247 self._check(pn_message_set_first_acquirer(self._msg, bool(value)))
248
249 @property
250 def delivery_count(self) -> int:
251 """The number of delivery attempts made for this message.
252
253 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
254 """
255 return pn_message_get_delivery_count(self._msg)
256
257 @delivery_count.setter
258 def delivery_count(self, value: int) -> None:
259 self._check(pn_message_set_delivery_count(self._msg, value))
260
261 @property
262 def id(self) -> Optional[Union[str, bytes, 'UUID', ulong]]:
263 """The globally unique id of the message, and can be used
264 to determine if a received message is a duplicate. The allowed
265 types to set the id are:
266
267 :type: The valid AMQP types for an id are one of:
268
269 * ``int`` (unsigned)
270 * ``uuid.UUID``
271 * ``bytes``
272 * ``str``
273 """
274 value = pn_message_get_id(self._msg)
275 if isinstance(value, tuple):
276 if value[0] == PN_UUID:
277 value = UUID(bytes=value[1])
278 return value
279
280 @id.setter
281 def id(self, value: Optional[Union[str, bytes, 'UUID', int]]) -> None:
282 if isinteger(value):
283 value = ulong(value)
284 elif isinstance(value, UUID):
285 value = (PN_UUID, value.bytes)
286 pn_message_set_id(self._msg, value)
287
288 @property
289 def user_id(self) -> bytes:
290 """The user id of the message creator.
291
292 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
293 """
294 return pn_message_get_user_id(self._msg)
295
296 @user_id.setter
297 def user_id(self, value: bytes) -> None:
298 self._check(pn_message_set_user_id(self._msg, value))
299
300 @property
301 def address(self) -> Optional[str]:
302 """The address of the message.
303
304 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
305 """
306 return utf82unicode(pn_message_get_address(self._msg))
307
308 @address.setter
309 def address(self, value: str) -> None:
310 self._check(pn_message_set_address(self._msg, unicode2utf8(value)))
311
312 @property
313 def subject(self) -> Optional[str]:
314 """The subject of the message.
315
316 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
317 """
318 return utf82unicode(pn_message_get_subject(self._msg))
319
320 @subject.setter
321 def subject(self, value: str) -> None:
322 self._check(pn_message_set_subject(self._msg, unicode2utf8(value)))
323
324 @property
325 def reply_to(self) -> Optional[str]:
326 """The reply-to address for the message.
327
328 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
329 """
330 return utf82unicode(pn_message_get_reply_to(self._msg))
331
332 @reply_to.setter
333 def reply_to(self, value: str) -> None:
334 self._check(pn_message_set_reply_to(self._msg, unicode2utf8(value)))
335
336 @property
337 def correlation_id(self) -> Optional[Union['UUID', ulong, str, bytes]]:
338 """The correlation-id for the message.
339
340 :type: The valid AMQP types for a correlation-id are one of:
341
342 * ``int`` (unsigned)
343 * ``uuid.UUID``
344 * ``bytes``
345 * ``str``
346 """
347 value = pn_message_get_correlation_id(self._msg)
348 if isinstance(value, tuple):
349 if value[0] == PN_UUID:
350 value = UUID(bytes=value[1])
351 return value
352
353 @correlation_id.setter
354 def correlation_id(self, value: Optional[Union[str, bytes, 'UUID', int]]) -> None:
355 if isinteger(value):
356 value = ulong(value)
357 elif isinstance(value, UUID):
358 value = (PN_UUID, value.bytes)
359 pn_message_set_correlation_id(self._msg, value)
360
361 @property
362 def content_type(self) -> symbol:
363 """The RFC-2046 [RFC2046] MIME type for the message body.
364
365 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
366 """
367 return symbol(utf82unicode(pn_message_get_content_type(self._msg)))
368
369 @content_type.setter
370 def content_type(self, value: str) -> None:
371 self._check(pn_message_set_content_type(self._msg, unicode2utf8(value)))
372
373 @property
374 def content_encoding(self) -> symbol:
375 """The content-encoding of the message.
376
377 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
378 """
379 return symbol(utf82unicode(pn_message_get_content_encoding(self._msg)))
380
381 @content_encoding.setter
382 def content_encoding(self, value: str) -> None:
383 self._check(pn_message_set_content_encoding(self._msg, unicode2utf8(value)))
384
385 @property
386 def expiry_time(self) -> float: # TODO doc said int
387 """The absolute expiry time of the message in seconds using the Unix time_t [IEEE1003] encoding.
388
389 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
390 """
391 return millis2secs(pn_message_get_expiry_time(self._msg))
392
393 @expiry_time.setter
394 def expiry_time(self, value: Union[float, int]) -> None:
395 self._check(pn_message_set_expiry_time(self._msg, secs2millis(value)))
396
397 @property
398 def creation_time(self) -> float:
399 """The creation time of the message in seconds using the Unix time_t [IEEE1003] encoding.
400
401 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
402 """
403 return millis2secs(pn_message_get_creation_time(self._msg))
404
405 @creation_time.setter
406 def creation_time(self, value: Union[float, int]) -> None:
407 self._check(pn_message_set_creation_time(self._msg, secs2millis(value)))
408
409 @property
410 def group_id(self) -> Optional[str]:
411 """The group id of the message.
412
413 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
414 """
415 return utf82unicode(pn_message_get_group_id(self._msg))
416
417 @group_id.setter
418 def group_id(self, value: str) -> None:
419 self._check(pn_message_set_group_id(self._msg, unicode2utf8(value)))
420
421 @property
422 def group_sequence(self) -> int:
423 """The sequence of the message within its group.
424
425 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
426 """
427 return pn_message_get_group_sequence(self._msg)
428
429 @group_sequence.setter
430 def group_sequence(self, value: int) -> None:
431 self._check(pn_message_set_group_sequence(self._msg, value))
432
433 @property
434 def reply_to_group_id(self) -> Optional[str]:
435 """The group-id for any replies.
436
437 :raise: :exc:`MessageException` if there is any Proton error when using the setter.
438 """
439 return utf82unicode(pn_message_get_reply_to_group_id(self._msg))
440
441 @reply_to_group_id.setter
442 def reply_to_group_id(self, value: str) -> None:
443 self._check(pn_message_set_reply_to_group_id(self._msg, unicode2utf8(value)))
444
445 @property
446 def instructions(self) -> Optional[AnnotationDict]:
447 """Delivery annotations as a dictionary of key/values. The AMQP 1.0
448 specification restricts this dictionary to have keys that are either
449 :class:`symbol` or :class:`ulong` types. It is possible to use
450 the special ``dict`` subclass :class:`AnnotationDict` which
451 will by default enforce these restrictions on construction. In addition,
452 if string types are used, this class will be silently convert them into
453 symbols.
454
455 :type: :class:`AnnotationDict`. Any ``dict`` with :class:`ulong` or :class:`symbol` keys.
456 """
457 return self.instruction_dict
458
459 @instructions.setter
460 def instructions(self, instructions: Optional[Dict[Union[str, int], 'PythonAMQPData']]) -> None:
461 if isinstance(instructions, dict):
462 self.instruction_dict = AnnotationDict(instructions, raise_on_error=False)
463 else:
464 self.instruction_dict = instructions
465
466 @property
467 def annotations(self) -> Optional[AnnotationDict]:
468 """Message annotations as a dictionary of key/values. The AMQP 1.0
469 specification restricts this dictionary to have keys that are either
470 :class:`symbol` or :class:`ulong` types. It is possible to use
471 the special ``dict`` subclass :class:`AnnotationDict` which
472 will by default enforce these restrictions on construction. In addition,
473 if a string types are used, this class will silently convert them into
474 symbols.
475
476 :type: :class:`AnnotationDict`. Any ``dict`` with :class:`ulong` or :class:`symbol` keys.
477 """
478 return self.annotation_dict
479
480 @annotations.setter
481 def annotations(self, annotations: Optional[Dict[Union[str, int], 'PythonAMQPData']]) -> None:
482 if isinstance(annotations, dict):
483 self.annotation_dict = AnnotationDict(annotations, raise_on_error=False)
484 else:
485 self.annotation_dict = annotations
486
487 def encode(self) -> bytes:
488 self._pre_encode()
489 sz = 16
490 while True:
491 err, data = pn_message_encode(self._msg, sz)
492 if err == PN_OVERFLOW:
493 sz *= 2
494 continue
495 else:
496 self._check(err)
497 return data
498
499 def decode(self, data: bytes) -> None:
500 self._check(pn_message_decode(self._msg, data))
501 self._post_decode()
502
503 def send(self, sender: 'Sender', tag: Optional[str] = None) -> 'Delivery':
504 """
505 Encodes and sends the message content using the specified sender,
506 and, if present, using the specified tag. Upon success, will
507 return the :class:`Delivery` object for the sent message.
508
509 :param sender: The sender to send the message
510 :param tag: The delivery tag for the sent message
511 :return: The delivery associated with the sent message
512 """
513 dlv = sender.delivery(tag or sender.delivery_tag())
514 encoded = self.encode()
515 sender.stream(encoded)
516 sender.advance()
517 if sender.snd_settle_mode == Link.SND_SETTLED:
518 dlv.settle()
519 return dlv
520
521 @overload
522 def recv(self, link: 'Sender') -> None:
523 ...
524
525 def recv(self, link: 'Receiver') -> Optional['Delivery']:
526 """
527 Receives and decodes the message content for the current :class:`Delivery`
528 from the link. Upon success it will return the current delivery
529 for the link. If there is no current delivery, or if the current
530 delivery is incomplete, or if the link is not a receiver, it will
531 return ``None``.
532
533 :param link: The link to receive a message from
534 :return: the delivery associated with the decoded message (or None)
535
536 """
537 if link.is_sender:
538 return None
539 dlv = link.current
540 if not dlv or dlv.partial:
541 return None
542 dlv.encoded = link.recv(dlv.pending)
543 link.advance()
544 # the sender has already forgotten about the delivery, so we might
545 # as well too
546 if link.remote_snd_settle_mode == Link.SND_SETTLED:
547 dlv.settle()
548 self.decode(dlv.encoded)
549 return dlv
550
551 def __repr__(self) -> str:
552 props = []
553 for attr in ("inferred", "address", "reply_to", "durable", "ttl",
554 "priority", "first_acquirer", "delivery_count", "id",
555 "correlation_id", "user_id", "group_id", "group_sequence",
556 "reply_to_group_id", "instructions", "annotations",
557 "properties", "body"):
558 value = getattr(self, attr)
559 if value:
560 props.append("%s=%r" % (attr, value))
561 return "Message(%s)" % ", ".join(props)