Debian Codegraph @

pamqp/frame.py

raw
1 """Manage the marshaling and unmarshaling of AMQP frames
2
3 unmarshal will turn a raw AMQP byte stream into the appropriate AMQP objects
4 from the specification file.
5
6 marshal will take an object created from the specification file and turn it
7 into a raw byte stream.
8
9 """
10
11 import logging
12 import struct
13
14 from pamqp import (
15 base,
16 body,
17 commands,
18 common,
19 constants,
20 decode,
21 exceptions,
22 header,
23 heartbeat,
24 )
25
26 LOGGER = logging.getLogger(__name__)
27 UNMARSHAL_FAILURE = 0, 0, None
28
29 FrameTypes = (
30 base.Frame
31 | body.ContentBody
32 | header.ContentHeader
33 | header.ProtocolHeader
34 | heartbeat.Heartbeat
35 )
36
37
38 def marshal(frame_value: FrameTypes, channel_id: int) -> bytes:
39 """Marshal a frame to be sent over the wire.
40
41 :raises: ValueError
42
43 """
44 if isinstance(frame_value, header.ProtocolHeader):
45 return frame_value.marshal()
46 elif isinstance(frame_value, base.Frame):
47 return _marshal_method_frame(frame_value, channel_id)
48 elif isinstance(frame_value, header.ContentHeader):
49 return _marshal_content_header_frame(frame_value, channel_id)
50 elif isinstance(frame_value, body.ContentBody):
51 return _marshal_content_body_frame(frame_value, channel_id)
52 elif isinstance(frame_value, heartbeat.Heartbeat):
53 return frame_value.marshal()
54 raise ValueError(f'Could not determine frame type: {frame_value}')
55
56
57 def unmarshal(data_in: bytes) -> tuple[int, int, FrameTypes]:
58 """Takes in binary data and maps builds the appropriate frame type,
59 returning a frame object.
60
61 :returns: tuple of bytes consumed, channel, and a frame object
62 :raises: exceptions.UnmarshalingException
63
64 """
65 try: # Look to see if it's a protocol header frame
66 value = _unmarshal_protocol_header_frame(data_in)
67 except ValueError as error:
68 raise exceptions.UnmarshalingException(
69 header.ProtocolHeader, error
70 ) from error
71 else:
72 if value:
73 return 8, 0, value
74
75 frame_type, channel_id, frame_size = frame_parts(data_in)
76
77 # Heartbeats do not have frame length indicators
78 if frame_type == constants.FRAME_HEARTBEAT and frame_size == 0:
79 return 8, channel_id, heartbeat.Heartbeat()
80
81 if not frame_size:
82 raise exceptions.UnmarshalingException('Unknown', 'No frame size')
83
84 byte_count = constants.FRAME_HEADER_SIZE + frame_size + 1
85 if byte_count > len(data_in):
86 raise exceptions.UnmarshalingException(
87 'Unknown', 'Not all data received'
88 )
89
90 if data_in[byte_count - 1] != constants.FRAME_END:
91 raise exceptions.UnmarshalingException('Unknown', 'Last byte error')
92 frame_data = data_in[constants.FRAME_HEADER_SIZE : byte_count - 1]
93 if frame_type == constants.FRAME_METHOD:
94 return byte_count, channel_id, _unmarshal_method_frame(frame_data)
95 elif frame_type == constants.FRAME_HEADER:
96 return byte_count, channel_id, _unmarshal_header_frame(frame_data)
97 elif frame_type == constants.FRAME_BODY:
98 return byte_count, channel_id, _unmarshal_body_frame(frame_data)
99 raise exceptions.UnmarshalingException(
100 'Unknown', f'Unknown frame type: {frame_type}'
101 )
102
103
104 def frame_parts(data: bytes) -> tuple[int, int, int | None]:
105 """Attempt to decode a low-level frame, returning frame parts"""
106 try: # Get the Frame Type, Channel Number and Frame Size
107 return struct.unpack('>BHI', data[0 : constants.FRAME_HEADER_SIZE])
108 except struct.error: # Did not receive a full frame
109 return UNMARSHAL_FAILURE
110
111
112 def _marshal(frame_type: int, channel_id: int, payload: bytes) -> bytes:
113 """Marshal the low-level AMQ frame"""
114 return b''.join(
115 [
116 struct.pack('>BHI', frame_type, channel_id, len(payload)),
117 payload,
118 constants.FRAME_END_CHAR,
119 ]
120 )
121
122
123 def _marshal_content_body_frame(
124 value: body.ContentBody, channel_id: int
125 ) -> bytes:
126 """Marshal as many content body frames as needed to transmit the content"""
127 return _marshal(constants.FRAME_BODY, channel_id, value.marshal())
128
129
130 def _marshal_content_header_frame(
131 value: header.ContentHeader, channel_id: int
132 ) -> bytes:
133 """Marshal a content header frame"""
134 return _marshal(constants.FRAME_HEADER, channel_id, value.marshal())
135
136
137 def _marshal_method_frame(value: base.Frame, channel_id: int) -> bytes:
138 """Marshal a method frame"""
139 return _marshal(
140 constants.FRAME_METHOD,
141 channel_id,
142 common.Struct.integer.pack(value.index) + value.marshal(),
143 )
144
145
146 def _unmarshal_protocol_header_frame(
147 data_in: bytes,
148 ) -> header.ProtocolHeader | None:
149 """Attempt to unmarshal a protocol header frame
150
151 The ProtocolHeader is abbreviated in size and functionality compared to
152 the rest of the frame types, so return UNMARSHAL_ERROR doesn't apply
153 as cleanly since we don't have all of the attributes to return even
154 regardless of success or failure.
155
156 :raises: ValueError
157
158 """
159 if data_in[0:4] == constants.AMQP: # Do the first four bytes match?
160 frame = header.ProtocolHeader()
161 frame.unmarshal(data_in)
162 return frame
163 return None
164
165
166 def _unmarshal_method_frame(frame_data: bytes) -> base.Frame:
167 """Attempt to unmarshal a method frame
168
169 :raises: pamqp.exceptions.UnmarshalingException
170
171 """
172 bytes_used, method_index = decode.long_int(frame_data[0:4])
173 try:
174 method: base.Frame = commands.INDEX_MAPPING[method_index]()
175 except KeyError as err:
176 raise exceptions.UnmarshalingException(
177 'Unknown', f'Unknown method index: {method_index!s}'
178 ) from err
179 try:
180 method.unmarshal(frame_data[bytes_used:])
181 except struct.error as error:
182 raise exceptions.UnmarshalingException(method, error) from error
183 return method
184
185
186 def _unmarshal_header_frame(frame_data: bytes) -> header.ContentHeader:
187 """Attempt to unmarshal a header frame
188
189 :raises: pamqp.exceptions.UnmarshalingException
190
191 """
192 content_header = header.ContentHeader()
193 try:
194 content_header.unmarshal(frame_data)
195 except struct.error as error:
196 raise exceptions.UnmarshalingException(
197 'ContentHeader', error
198 ) from error
199 return content_header
200
201
202 def _unmarshal_body_frame(frame_data: bytes) -> body.ContentBody:
203 """Attempt to unmarshal a body frame"""
204 content_body = body.ContentBody(b'')
205 content_body.unmarshal(frame_data)
206 return content_body