Debian Codegraph @

pamqp/base.py

raw
1 """
2 Base classes for the representation of frames and data structures.
3
4 """
5
6 import collections.abc
7 import logging
8 import struct
9 import typing
10
11 from pamqp import common, decode, encode
12
13 LOGGER = logging.getLogger(__name__)
14
15
16 class _AMQData:
17 """Base class for AMQ methods and properties for encoding and decoding"""
18
19 __slots__: typing.ClassVar[list[str]] = []
20 name: typing.ClassVar[str] = '_AMQData'
21
22 def __contains__(self, item: str) -> bool:
23 """Return if the item is in the attribute list"""
24 return item in self.__slots__
25
26 def __getitem__(self, item: str) -> common.FieldValue:
27 """Return an attribute as if it were a dict
28
29 :param item: The key to use to retrieve the value
30 :rtype: :const:`pamqp.common.FieldValue`
31 :raises: KeyError
32
33 """
34 return getattr(self, item) # type: ignore[no-any-return]
35
36 def __iter__(
37 self,
38 ) -> collections.abc.Generator[tuple[str, common.FieldValue], None, None]:
39 """Iterate the attributes and values as key, value pairs
40
41 :rtype: (:class:`str`, :const:`pamqp.common.FieldValue`)
42
43 """
44 for attribute in self.__slots__:
45 yield attribute, getattr(self, attribute)
46
47 def __len__(self) -> int:
48 """Return the length of the attribute list"""
49 return len(self.__slots__)
50
51 def __repr__(self) -> str:
52 """Return the representation of the frame object"""
53 return f'<{self.name} object at {hex(id(self))}>'
54
55 @classmethod
56 def amqp_type(cls, attr: str) -> str:
57 """Return the AMQP data type for an attribute
58
59 :param attr: The attribute name
60
61 """
62 return getattr(cls, '_' + attr) # type: ignore[no-any-return]
63
64 @classmethod
65 def attributes(cls) -> list[str]:
66 """Return the list of attributes"""
67 return cls.__slots__
68
69
70 class Frame(_AMQData):
71 """Base Class for AMQ Methods for encoding and decoding"""
72
73 frame_id: typing.ClassVar[int] = 0
74 index: typing.ClassVar[int] = 0
75 synchronous: typing.ClassVar[bool] = False
76 valid_responses: typing.ClassVar[list[str]] = []
77
78 def marshal(self) -> bytes:
79 """Dynamically encode the frame by taking the list of attributes and
80 encode them item by item getting the value form the object attribute
81 and the data type from the class attribute.
82
83 """
84 self.validate()
85 byte, offset, output, processing_bitset = -1, 0, [], False
86 for argument in self.__slots__:
87 data_type = self.amqp_type(argument)
88 if not processing_bitset and data_type == 'bit':
89 byte, offset, processing_bitset = 0, 0, True
90 data_value = getattr(self, argument, 0)
91 if processing_bitset:
92 if data_type != 'bit':
93 processing_bitset = False
94 output.append(encode.octet(byte))
95 else:
96 byte = encode.bit(data_value, byte, offset)
97 offset += 1
98 if offset == 8: # pragma: nocover
99 output.append(encode.octet(byte))
100 processing_bitset = False
101 continue # pragma: nocover
102 output.append(encode.by_type(data_value, data_type))
103 if processing_bitset:
104 output.append(encode.octet(byte))
105 return b''.join(output)
106
107 def unmarshal(self, data: bytes) -> None:
108 """Dynamically decode the frame data applying the values to the method
109 object by iterating through the attributes in order and decoding them.
110
111 :param data: The raw AMQP frame data
112
113 """
114 offset, processing_bitset = 0, False
115 for argument in self.__slots__:
116 data_type = self.amqp_type(argument)
117 if offset == 7 and processing_bitset: # pragma: nocover
118 data = data[1:]
119 offset = 0
120 if processing_bitset and data_type != 'bit':
121 offset = 0
122 processing_bitset = False
123 data = data[1:]
124 consumed, value = decode.by_type(data, data_type, offset)
125 if data_type == 'bit':
126 offset += 1
127 processing_bitset = True
128 consumed = 0
129 setattr(self, argument, value)
130 if consumed:
131 data = data[consumed:]
132
133 def validate(self) -> None:
134 """Validate the frame data ensuring all domains or attributes adhere
135 to the protocol specification.
136
137 :raises: ValueError
138
139 """
140
141
142 class BasicProperties(_AMQData):
143 """Provide a base object that marshals and unmarshals the Basic.Properties
144 object values.
145
146 """
147
148 flags: typing.ClassVar[dict[str, int]] = {}
149 name: typing.ClassVar[str] = 'BasicProperties'
150
151 def __eq__(self, other: object) -> bool:
152 if not isinstance(other, BasicProperties):
153 raise NotImplementedError
154 return all(
155 getattr(self, k, None) == getattr(other, k, None)
156 for k in self.__slots__
157 )
158
159 def encode_property(self, name: str, value: common.FieldValue) -> bytes:
160 """Encode a single property value
161
162 :param name: The name of the property to encode
163 :param value: The property to encode
164 :type value: :const:`pamqp.common.FieldValue`
165 :raises: TypeError
166
167 """
168 return encode.by_type(value, self.amqp_type(name))
169
170 def marshal(self) -> bytes:
171 """Take the Basic.Properties data structure and marshal it into the
172 data structure needed for the ContentHeader.
173
174 """
175 flags = 0
176 parts = []
177 for property_name in self.__slots__:
178 property_value = getattr(self, property_name)
179 if property_value is not None and property_value != '':
180 flags = flags | self.flags[property_name]
181 parts.append(
182 self.encode_property(property_name, property_value)
183 )
184 flag_pieces = []
185 while True:
186 remainder = flags >> 16
187 partial_flags = flags & 0xFFFE
188 if remainder != 0: # pragma: nocover
189 partial_flags |= 1
190 flag_pieces.append(struct.pack('>H', partial_flags))
191 flags = remainder
192 if not flags: # pragma: nocover
193 break
194 return b''.join(flag_pieces + parts)
195
196 def unmarshal(self, flags: int, data: bytes) -> None:
197 """Dynamically decode the frame data applying the values to the method
198 object by iterating through the attributes in order and decoding them.
199
200 """
201 for property_name in self.__slots__:
202 if flags & self.flags[property_name]:
203 data_type = getattr(self.__class__, '_' + property_name)
204 consumed, value = decode.by_type(data, data_type)
205 setattr(self, property_name, value)
206 data = data[consumed:]
207
208 def validate(self) -> None:
209 """Validate the frame data ensuring all domains or attributes adhere
210 to the protocol specification.
211
212 :raises: ValueError
213
214 """
215 if getattr(self, 'cluster_id', '') != '':
216 raise ValueError('cluster_id must be empty')
217 delivery_mode = getattr(self, 'delivery_mode', None)
218 if delivery_mode is not None and delivery_mode not in [1, 2]:
219 raise ValueError(f'Invalid delivery_mode value: {delivery_mode}')