| 1 |
""" |
| 2 |
MQTT Request Response module |
| 3 |
""" |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
from collections.abc import Sequence |
| 9 |
from enum import IntEnum |
| 10 |
from dataclasses import dataclass |
| 11 |
from typing import Callable, Union, Optional |
| 12 |
from awscrt import NativeResource, mqtt5, mqtt, exceptions |
| 13 |
from concurrent.futures import Future |
| 14 |
import _awscrt |
| 15 |
|
| 16 |
|
| 17 |
class SubscriptionStatusEventType(IntEnum): |
| 18 |
""" |
| 19 |
The type of change to the state of a streaming operation subscription |
| 20 |
""" |
| 21 |
|
| 22 |
SUBSCRIPTION_ESTABLISHED = 0 |
| 23 |
""" |
| 24 |
The streaming operation is successfully subscribed to its topic (filter) |
| 25 |
""" |
| 26 |
|
| 27 |
SUBSCRIPTION_LOST = 1 |
| 28 |
""" |
| 29 |
The streaming operation has temporarily lost its subscription to its topic (filter) |
| 30 |
""" |
| 31 |
|
| 32 |
SUBSCRIPTION_HALTED = 2 |
| 33 |
""" |
| 34 |
The streaming operation has entered a terminal state where it has given up trying to subscribe |
| 35 |
to its topic (filter). This is always due to user error (bad topic filter or IoT Core permission policy). |
| 36 |
""" |
| 37 |
|
| 38 |
|
| 39 |
@dataclass |
| 40 |
class SubscriptionStatusEvent: |
| 41 |
""" |
| 42 |
An event that describes a change in subscription status for a streaming operation. |
| 43 |
|
| 44 |
Args: |
| 45 |
type (SubscriptionStatusEventType): The type of status change represented by the event |
| 46 |
error (Optional[Exception]): Describes an underlying reason for the event. Only set for SubscriptionLost and SubscriptionHalted. |
| 47 |
""" |
| 48 |
type: SubscriptionStatusEventType = None |
| 49 |
error: 'Optional[Exception]' = None |
| 50 |
|
| 51 |
|
| 52 |
@dataclass |
| 53 |
class IncomingPublishEvent: |
| 54 |
""" |
| 55 |
An event that describes an incoming message on a streaming operation. |
| 56 |
|
| 57 |
Args: |
| 58 |
topic (str): MQTT Topic that the response was received on. |
| 59 |
payload (Optional[bytes]): The payload of the incoming message. |
| 60 |
""" |
| 61 |
topic: str |
| 62 |
payload: 'Optional[bytes]' = None |
| 63 |
|
| 64 |
|
| 65 |
SubscriptionStatusListener = Callable[[SubscriptionStatusEvent], None] |
| 66 |
""" |
| 67 |
Signature for a handler that listens to subscription status events. |
| 68 |
""" |
| 69 |
|
| 70 |
IncomingPublishListener = Callable[[IncomingPublishEvent], None] |
| 71 |
""" |
| 72 |
Signature for a handler that listens to incoming publish events. |
| 73 |
""" |
| 74 |
|
| 75 |
|
| 76 |
@dataclass |
| 77 |
class StreamingOperationOptions: |
| 78 |
""" |
| 79 |
Configuration options for an MQTT-based streaming operation. |
| 80 |
|
| 81 |
Args: |
| 82 |
subscription_topic_filter (str): Topic filter that the streaming operation should listen on |
| 83 |
subscription_status_listener (SubscriptionStatusListener): function object to invoke when the operation's subscription status changes |
| 84 |
incoming_publish_listener (IncomingPublishListener): function object to invoke when a publish packet arrives that matches the subscription topic filter |
| 85 |
""" |
| 86 |
subscription_topic_filter: str |
| 87 |
subscription_status_listener: 'Optional[SubscriptionStatusListener]' = None |
| 88 |
incoming_publish_listener: 'Optional[IncomingPublishListener]' = None |
| 89 |
|
| 90 |
def validate(self): |
| 91 |
""" |
| 92 |
Stringently type-checks an instance's field values. |
| 93 |
""" |
| 94 |
assert isinstance(self.subscription_topic_filter, str) |
| 95 |
assert callable(self.subscription_status_listener) or self.subscription_status_listener is None |
| 96 |
assert callable(self.incoming_publish_listener) or self.incoming_publish_listener is None |
| 97 |
|
| 98 |
|
| 99 |
@dataclass |
| 100 |
class Response: |
| 101 |
""" |
| 102 |
Encapsulates a response to an AWS IoT Core MQTT-based service request |
| 103 |
|
| 104 |
Args: |
| 105 |
topic (str): MQTT Topic that the response was received on. |
| 106 |
payload (Optional[bytes]): The payload of the response. |
| 107 |
""" |
| 108 |
topic: str |
| 109 |
payload: 'Optional[bytes]' = None |
| 110 |
|
| 111 |
|
| 112 |
@dataclass |
| 113 |
class ResponsePath: |
| 114 |
""" |
| 115 |
A response path is a pair of values - MQTT topic and a JSON path - that describe how a response to |
| 116 |
an MQTT-based request may arrive. For a given request type, there may be multiple response paths and each |
| 117 |
one is associated with a separate JSON schema for the response body. |
| 118 |
|
| 119 |
Args: |
| 120 |
topic (str): MQTT topic that a response may arrive on. |
| 121 |
correlation_token_json_path (Optional[str]): JSON path for finding correlation tokens within payloads that arrive on this path's topic. |
| 122 |
""" |
| 123 |
topic: str |
| 124 |
correlation_token_json_path: 'Optional[str]' = None |
| 125 |
|
| 126 |
def validate(self): |
| 127 |
""" |
| 128 |
Stringently type-checks an instance's field values. |
| 129 |
""" |
| 130 |
assert isinstance(self.topic, str) |
| 131 |
assert isinstance(self.correlation_token_json_path, str) or self.correlation_token_json_path is None |
| 132 |
|
| 133 |
|
| 134 |
@dataclass |
| 135 |
class RequestOptions: |
| 136 |
""" |
| 137 |
Configuration options for an MQTT-based request-response operation. |
| 138 |
|
| 139 |
Args: |
| 140 |
subscription_topic_filters (Sequence[str]): Set of topic filters that should be subscribed to in order to cover all possible response paths. Sometimes using wildcards can cut down on the subscriptions needed; other times that isn't valid. |
| 141 |
response_paths (Sequence[ResponsePath]): Set of all possible response paths associated with this request type. |
| 142 |
publish_topic (str): Topic to publish the request to once response subscriptions have been established. |
| 143 |
payload (bytes): Payload to publish to 'publishTopic' in order to initiate the request |
| 144 |
correlation_token (Optional[str]): Correlation token embedded in the request that must be found in a response message. This can be null to support certain services which don't use correlation tokens. In that case, the client only allows one token-less request at a time. |
| 145 |
""" |
| 146 |
subscription_topic_filters: 'Sequence[str]' |
| 147 |
response_paths: 'Sequence[ResponsePath]' |
| 148 |
publish_topic: str |
| 149 |
payload: bytes |
| 150 |
correlation_token: 'Optional[str]' = None |
| 151 |
|
| 152 |
def validate(self): |
| 153 |
""" |
| 154 |
Stringently type-checks an instance's field values. |
| 155 |
""" |
| 156 |
assert isinstance(self.subscription_topic_filters, Sequence) |
| 157 |
for topic_filter in self.subscription_topic_filters: |
| 158 |
assert isinstance(topic_filter, str) |
| 159 |
|
| 160 |
assert isinstance(self.response_paths, Sequence) |
| 161 |
for response_path in self.response_paths: |
| 162 |
response_path.validate() |
| 163 |
|
| 164 |
assert isinstance(self.publish_topic, str) |
| 165 |
assert isinstance(self.payload, bytes) |
| 166 |
assert isinstance(self.correlation_token, str) or self.correlation_token is None |
| 167 |
|
| 168 |
|
| 169 |
@dataclass |
| 170 |
class ClientOptions: |
| 171 |
""" |
| 172 |
MQTT-based request-response client configuration options |
| 173 |
|
| 174 |
Args: |
| 175 |
max_request_response_subscriptions (int): Maximum number of subscriptions that the client will concurrently use for request-response operations |
| 176 |
max_streaming_subscriptions (int): Maximum number of subscriptions that the client will concurrently use for streaming operations |
| 177 |
operation_timeout_in_seconds (Optional[int]): Duration, in seconds, that a request-response operation will wait for completion before giving up |
| 178 |
""" |
| 179 |
max_request_response_subscriptions: int |
| 180 |
max_streaming_subscriptions: int |
| 181 |
operation_timeout_in_seconds: 'Optional[int]' = 60 |
| 182 |
|
| 183 |
def validate(self): |
| 184 |
""" |
| 185 |
Stringently type-checks an instance's field values. |
| 186 |
""" |
| 187 |
assert isinstance(self.max_request_response_subscriptions, int) |
| 188 |
assert isinstance(self.max_streaming_subscriptions, int) |
| 189 |
assert isinstance(self.operation_timeout_in_seconds, int) |
| 190 |
|
| 191 |
|
| 192 |
class Client(NativeResource): |
| 193 |
""" |
| 194 |
MQTT-based request-response client tuned for AWS MQTT services. |
| 195 |
|
| 196 |
Supports streaming operations (listen to a stream of modeled events from an MQTT topic) and request-response |
| 197 |
operations (performs the subscribes, publish, and incoming publish correlation and error checking needed to |
| 198 |
perform simple request-response operations over MQTT). |
| 199 |
|
| 200 |
Args: |
| 201 |
protocol_client (Union[mqtt5.Client, mqtt.Connection]): MQTT client to use as transport |
| 202 |
client_options (ClientOptions): The ClientOptions dataclass to used to configure the new request response Client. |
| 203 |
|
| 204 |
""" |
| 205 |
|
| 206 |
def __init__(self, protocol_client: Union[mqtt5.Client, mqtt.Connection], |
| 207 |
client_options: ClientOptions): |
| 208 |
|
| 209 |
assert isinstance(protocol_client, mqtt5.Client) or isinstance(protocol_client, mqtt.Connection) |
| 210 |
assert isinstance(client_options, ClientOptions) |
| 211 |
client_options.validate() |
| 212 |
|
| 213 |
super().__init__() |
| 214 |
|
| 215 |
if isinstance(protocol_client, mqtt5.Client): |
| 216 |
self._binding = _awscrt.mqtt_request_response_client_new_from_5(protocol_client, client_options) |
| 217 |
else: |
| 218 |
self._binding = _awscrt.mqtt_request_response_client_new_from_311(protocol_client, client_options) |
| 219 |
|
| 220 |
def make_request(self, options: RequestOptions): |
| 221 |
""" |
| 222 |
Initiate an MQTT-based request-response async workflow |
| 223 |
|
| 224 |
Args: |
| 225 |
options (RequestOptions): Configuration options for the request to perform |
| 226 |
|
| 227 |
Returns: |
| 228 |
concurrent.futures.Future: A Future whose result will contain the topic and payload of a response |
| 229 |
to the request. The future will contain an exception if the request fails. |
| 230 |
""" |
| 231 |
options.validate() |
| 232 |
|
| 233 |
future = Future() |
| 234 |
|
| 235 |
def on_request_complete(error_code, topic, payload): |
| 236 |
if error_code != 0: |
| 237 |
future.set_exception(exceptions.from_code(error_code)) |
| 238 |
else: |
| 239 |
response = Response(topic=topic, payload=payload) |
| 240 |
future.set_result(response) |
| 241 |
|
| 242 |
_awscrt.mqtt_request_response_client_make_request(self._binding, |
| 243 |
options.subscription_topic_filters, |
| 244 |
options.response_paths, |
| 245 |
options.publish_topic, |
| 246 |
options.payload, |
| 247 |
options.correlation_token, |
| 248 |
on_request_complete) |
| 249 |
|
| 250 |
return future |
| 251 |
|
| 252 |
def create_stream(self, options: StreamingOperationOptions): |
| 253 |
""" |
| 254 |
Creates a new streaming operation |
| 255 |
|
| 256 |
Args: |
| 257 |
options (StreamingOperationOptions): Configuration options for the streaming operation |
| 258 |
|
| 259 |
Returns: |
| 260 |
StreamingOperation: a new streaming operation. Opening the operation triggers the client to maintain |
| 261 |
an MQTT subscription for relevant events. Matching publishes and subscription status changes are |
| 262 |
communicated by invoking configuration-controlled callbacks. |
| 263 |
""" |
| 264 |
options.validate() |
| 265 |
|
| 266 |
def on_subscription_status_event(event_type, error_code): |
| 267 |
if options.subscription_status_listener is not None: |
| 268 |
event = SubscriptionStatusEvent(event_type) |
| 269 |
if error_code != 0: |
| 270 |
event.error = exceptions.from_code(error_code) |
| 271 |
options.subscription_status_listener(event) |
| 272 |
|
| 273 |
def on_incoming_publish_event(topic, payload): |
| 274 |
if options.incoming_publish_listener is not None: |
| 275 |
event = IncomingPublishEvent(topic, payload) |
| 276 |
options.incoming_publish_listener(event) |
| 277 |
|
| 278 |
stream_binding = _awscrt.mqtt_request_response_client_create_stream( |
| 279 |
self._binding, options.subscription_topic_filter, on_subscription_status_event, on_incoming_publish_event) |
| 280 |
|
| 281 |
return StreamingOperation(stream_binding) |
| 282 |
|
| 283 |
|
| 284 |
class StreamingOperation(NativeResource): |
| 285 |
""" |
| 286 |
An operation that represents a stream of events broadcast to an MQTT topic |
| 287 |
""" |
| 288 |
|
| 289 |
def __init__(self, binding): |
| 290 |
super().__init__() |
| 291 |
|
| 292 |
self._binding = binding |
| 293 |
|
| 294 |
def open(self): |
| 295 |
""" |
| 296 |
Triggers the streaming operation to maintain an MQTT subscription for relevant events. Until a stream is |
| 297 |
opened, no events can be received. |
| 298 |
""" |
| 299 |
_awscrt.mqtt_streaming_operation_open(self._binding) |