Debian Codegraph @

crt/aws-c-mqtt/source/request-response/request_response_client.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include <aws/mqtt/request-response/request_response_client.h>
7
8 #include <aws/common/clock.h>
9 #include <aws/common/json.h>
10 #include <aws/common/ref_count.h>
11 #include <aws/common/task_scheduler.h>
12 #include <aws/io/event_loop.h>
13 #include <aws/mqtt/private/client_impl_shared.h>
14 #include <aws/mqtt/private/request-response/protocol_adapter.h>
15 #include <aws/mqtt/private/request-response/request_response_subscription_set.h>
16 #include <aws/mqtt/private/request-response/subscription_manager.h>
17 #include <aws/mqtt/private/v5/mqtt5_client_impl.h>
18
19 #include <inttypes.h>
20
21 #define MQTT_RR_CLIENT_OPERATION_TABLE_DEFAULT_SIZE 50
22
23 struct aws_mqtt_request_operation_storage {
24 struct aws_mqtt_request_operation_options options;
25
26 struct aws_array_list operation_response_paths;
27 struct aws_array_list subscription_topic_filters;
28
29 struct aws_byte_buf operation_data;
30 };
31
32 struct aws_mqtt_streaming_operation_storage {
33 struct aws_mqtt_streaming_operation_options options;
34
35 struct aws_byte_buf operation_data;
36
37 struct aws_atomic_var activated;
38 };
39
40 enum aws_mqtt_request_response_operation_type {
41 AWS_MRROT_REQUEST,
42 AWS_MRROT_STREAMING,
43 };
44
45 enum aws_mqtt_request_response_operation_state {
46 /* creation -> in event loop enqueue */
47 AWS_MRROS_NONE,
48
49 /* in event loop queue -> non blocked response from subscription manager */
50 AWS_MRROS_QUEUED,
51
52 /* subscribing response from sub manager -> subscription success/failure event */
53 AWS_MRROS_PENDING_SUBSCRIPTION,
54
55 /* (request only) subscription success -> (publish failure OR correlated response received) */
56 AWS_MRROS_PENDING_RESPONSE,
57
58 /* (request only) the operation's destroy task has been scheduled but not yet executed */
59 AWS_MRROS_PENDING_DESTROY,
60
61 /* (streaming only) subscription success -> (operation finished OR subscription ended event) */
62 AWS_MRROS_SUBSCRIBED,
63
64 /* (streaming only) (subscription failure OR subscription ended) -> operation close/terminate */
65 AWS_MRROS_TERMINAL,
66 };
67
68 const char *s_aws_mqtt_request_response_operation_state_to_c_str(enum aws_mqtt_request_response_operation_state state) {
69 switch (state) {
70 case AWS_MRROS_NONE:
71 return "NONE";
72
73 case AWS_MRROS_QUEUED:
74 return "QUEUED";
75
76 case AWS_MRROS_PENDING_SUBSCRIPTION:
77 return "PENDING_SUBSCRIPTION";
78
79 case AWS_MRROS_PENDING_RESPONSE:
80 return "PENDING_RESPONSE";
81
82 case AWS_MRROS_SUBSCRIBED:
83 return "SUBSCRIBED";
84
85 case AWS_MRROS_TERMINAL:
86 return "TERMINAL";
87
88 case AWS_MRROS_PENDING_DESTROY:
89 return "PENDING_DESTROY";
90
91 default:
92 return "Unknown";
93 }
94 }
95
96 const char *s_aws_acquire_subscription_result_type(enum aws_acquire_subscription_result_type result) {
97 switch (result) {
98 case AASRT_SUBSCRIBED:
99 return "SUBSCRIBED";
100
101 case AASRT_SUBSCRIBING:
102 return "SUBSCRIBING";
103
104 case AASRT_BLOCKED:
105 return "BLOCKED";
106
107 case AASRT_NO_CAPACITY:
108 return "NO_CAPACITY";
109
110 case AASRT_FAILURE:
111 return "FAILURE";
112
113 default:
114 return "Unknown";
115 }
116 }
117
118 /*
119
120 Client Tables/Lookups
121
122 (operations: authoritative operation container)
123 1. &operation.id -> &operation // added on in-thread enqueue, removed on operation completion/destruction
124
125 (request_response_paths: response path topic -> Correlation token extraction info)
126 2. &topic -> &{topic, topic_buffer, correlation token json path buffer} // ref-counted, per-message-path add on
127 request dequeue into subscribing/subscribed state, decref/removed on operation completion/destruction
128
129 (operations_by_correlation_tokens: correlationToken -> request operation)
130 3. &operation.correlation token -> (request) &operation // added on request dequeue into subscribing/subscribed
131 state, removed on operation completion/destruction
132
133 (streaming_operation_subscription_lists: streaming subscription filter -> list of all operations using that filter)
134 4. &topic_filter -> &{topic_filter, linked_list} // added on request dequeue into subscribing/subscribed state,
135 removed from list on operation completion/destruction also checked for empty and removed from table
136
137 */
138
139 struct aws_mqtt_rr_client_operation {
140 struct aws_allocator *allocator;
141
142 /*
143 * Operation ref-counting is a bit tricky and un-intuitive because it differs based on the type of operation.
144 *
145 * Streaming operations are managed by the user, and so the ref count is their responsibility to drop to zero.
146 * Dropping a streaming operation's ref count to zero schedules a task on the client event loop to destroy the
147 * operation. It is expected that the binding client will track (with proper synchronization) all unclosed
148 * streaming operations and safely close them for the user when close is called on the binding client.
149 *
150 * Request operations are managed by the client, and so the ref count is dropped to zero when either the
151 * operation completes normally (success or failure) or when the client is shutdown due to its external ref
152 * count dropping to zero. In all cases, this event happens naturally on the client event loop.
153 *
154 * So the summary is:
155 *
156 * (1) Streaming operation clean up is initiated by the user calling dec ref on the streaming operation
157 * (2) Request operation clean up is initiated by normal completion or client shutdown invoking dec ref.
158 *
159 * The upshot is that client shutdown dec-refs request operations but not streaming operations.
160 */
161 struct aws_ref_count ref_count;
162
163 struct aws_mqtt_request_response_client *client_internal_ref;
164
165 uint64_t id;
166
167 enum aws_mqtt_request_response_operation_type type;
168
169 union {
170 struct aws_mqtt_streaming_operation_storage streaming_storage;
171 struct aws_mqtt_request_operation_storage request_storage;
172 } storage;
173
174 uint64_t timeout_timepoint_ns;
175 struct aws_priority_queue_node priority_queue_node;
176
177 /* Sometimes this is client->operation_queue, other times it is an entry in the client's topic_filter table */
178 struct aws_linked_list_node node;
179
180 enum aws_mqtt_request_response_operation_state state;
181
182 size_t pending_subscriptions;
183
184 bool in_client_tables;
185
186 struct aws_task submit_task;
187 struct aws_task destroy_task;
188 };
189
190 /*******************************************************************************************/
191
192 /* Tracks the current state of the request-response client */
193 enum aws_request_response_client_state {
194
195 /* cross-thread initialization has not completed and all protocol adapter callbacks are ignored */
196 AWS_RRCS_UNINITIALIZED,
197
198 /* Normal operating state for the client. */
199 AWS_RRCS_ACTIVE,
200
201 /* asynchronously shutting down, no more servicing will be done and all protocol adapter callbacks are ignored */
202 AWS_RRCS_SHUTTING_DOWN,
203 };
204
205 /*
206 * Request-Response Client Notes
207 *
208 * Ref-counting/Shutdown
209 *
210 * The request-response client uses a double ref-count pattern.
211 *
212 * External references represent user references. When the external reference reaches zero, the client's asynchronous
213 * shutdown process is started.
214 *
215 * Internal references block final destruction. Asynchronous shutdown will not complete until all internal references
216 * are dropped. In addition to one long-lived internal reference (the protocol client adapter's back reference to
217 * the request-response client), all event loop tasks that target the request-response client hold an internal
218 * reference between task submission and task completion. This ensures that the task always has a valid reference
219 * to the client, even if we're trying to shut down at the same time.
220 *
221 *
222 * Initialization
223 *
224 * Initialization is complicated by the fact that the subscription manager needs to be initialized from the
225 * event loop thread that the client/protocol adapter/protocol client are all seated on. To do this safely,
226 * we add an uninitialized state that ignores all callbacks and we schedule a task on initial construction to do
227 * the event-loop-only initialization. Once that initialization completes on the event loop thread, we move
228 * the client into an active state where it will process operations and protocol adapter callbacks.
229 */
230 struct aws_mqtt_request_response_client {
231 struct aws_allocator *allocator;
232
233 struct aws_ref_count external_ref_count;
234 struct aws_ref_count internal_ref_count;
235
236 struct aws_mqtt_request_response_client_options config;
237
238 struct aws_mqtt_protocol_adapter *client_adapter;
239
240 struct aws_rr_subscription_manager subscription_manager;
241
242 struct aws_event_loop *loop;
243
244 struct aws_task initialize_task;
245 struct aws_task external_shutdown_task;
246 struct aws_task internal_shutdown_task;
247
248 uint64_t scheduled_service_timepoint_ns;
249 struct aws_task service_task;
250
251 enum aws_request_response_client_state state;
252
253 struct aws_atomic_var next_id;
254
255 struct aws_linked_list operation_queue;
256
257 /* &operation->id -> &operation */
258 struct aws_hash_table operations;
259
260 /*
261 * heap of operation pointers where the timeout is the sort value. Elements are added to this on operation
262 * submission and removed on operation timeout/completion/termination. Request-response operations have actual
263 * timeouts, while streaming operations have UINT64_MAX timeouts.
264 */
265 struct aws_priority_queue operations_by_timeout;
266
267 /*
268 * Structure to handle stream and request subscriptions.
269 */
270 struct aws_request_response_subscriptions subscriptions;
271
272 /*
273 * Map from cursor (correlation token) -> request operation
274 */
275 struct aws_hash_table operations_by_correlation_tokens;
276 };
277
278 struct aws_mqtt_request_response_client *aws_mqtt_request_response_client_acquire_internal(
279 struct aws_mqtt_request_response_client *client) {
280 if (client != NULL) {
281 aws_ref_count_acquire(&client->internal_ref_count);
282 }
283
284 return client;
285 }
286
287 struct aws_mqtt_request_response_client *aws_mqtt_request_response_client_release_internal(
288 struct aws_mqtt_request_response_client *client) {
289 if (client != NULL) {
290 aws_ref_count_release(&client->internal_ref_count);
291 }
292
293 return NULL;
294 }
295
296 static void s_aws_rr_client_on_zero_internal_ref_count(void *context) {
297 struct aws_mqtt_request_response_client *client = context;
298
299 /* Both ref counts are zero, but it's still safest to schedule final destruction, not invoke it directly */
300 aws_event_loop_schedule_task_now(client->loop, &client->internal_shutdown_task);
301 }
302
303 static void s_aws_rr_client_on_zero_external_ref_count(void *context) {
304 struct aws_mqtt_request_response_client *client = context;
305
306 /* Start the asynchronous shutdown process */
307 aws_event_loop_schedule_task_now(client->loop, &client->external_shutdown_task);
308 }
309
310 static void s_mqtt_request_response_client_final_destroy(struct aws_mqtt_request_response_client *client) {
311 aws_mqtt_request_response_client_terminated_callback_fn *terminate_callback = client->config.terminated_callback;
312 void *user_data = client->config.user_data;
313
314 AWS_FATAL_ASSERT(aws_hash_table_get_entry_count(&client->operations) == 0);
315 aws_hash_table_clean_up(&client->operations);
316
317 aws_priority_queue_clean_up(&client->operations_by_timeout);
318
319 aws_mqtt_request_response_client_subscriptions_clean_up(&client->subscriptions);
320 aws_hash_table_clean_up(&client->operations_by_correlation_tokens);
321
322 aws_event_loop_group_release_from_event_loop(client->loop);
323 aws_mem_release(client->allocator, client);
324
325 if (terminate_callback != NULL) {
326 (*terminate_callback)(user_data);
327 }
328 }
329
330 static void s_mqtt_request_response_client_internal_shutdown_task_fn(
331 struct aws_task *task,
332 void *arg,
333 enum aws_task_status task_status) {
334 (void)task;
335 (void)task_status;
336
337 struct aws_mqtt_request_response_client *client = arg;
338
339 /* All internal and external refs are gone; it is safe to clean up synchronously. */
340 s_mqtt_request_response_client_final_destroy(client);
341 }
342
343 static void s_remove_operation_from_timeout_queue(struct aws_mqtt_rr_client_operation *operation) {
344 struct aws_mqtt_request_response_client *client = operation->client_internal_ref;
345
346 if (aws_priority_queue_node_is_in_queue(&operation->priority_queue_node)) {
347 struct aws_mqtt_rr_client_operation *queued_operation = NULL;
348 aws_priority_queue_remove(&client->operations_by_timeout, &queued_operation, &operation->priority_queue_node);
349 }
350 }
351
352 static void s_change_operation_state(
353 struct aws_mqtt_rr_client_operation *operation,
354 enum aws_mqtt_request_response_operation_state new_state) {
355 enum aws_mqtt_request_response_operation_state old_state = operation->state;
356 if (old_state == new_state) {
357 return;
358 }
359
360 operation->state = new_state;
361
362 AWS_LOGF_DEBUG(
363 AWS_LS_MQTT_REQUEST_RESPONSE,
364 "id=%p: request-response operation %" PRIu64 " changing state from %s to %s",
365 (void *)operation->client_internal_ref,
366 operation->id,
367 s_aws_mqtt_request_response_operation_state_to_c_str(old_state),
368 s_aws_mqtt_request_response_operation_state_to_c_str(new_state));
369 }
370
371 static void s_complete_request_operation_with_failure(struct aws_mqtt_rr_client_operation *operation, int error_code) {
372 AWS_FATAL_ASSERT(operation->type == AWS_MRROT_REQUEST);
373 AWS_FATAL_ASSERT(error_code != AWS_ERROR_SUCCESS);
374
375 if (operation->state == AWS_MRROS_PENDING_DESTROY) {
376 return;
377 }
378
379 AWS_LOGF_DEBUG(
380 AWS_LS_MQTT_REQUEST_RESPONSE,
381 "id=%p: request-response operation %" PRIu64 " failed with error code %d(%s)",
382 (void *)operation->client_internal_ref,
383 operation->id,
384 error_code,
385 aws_error_debug_str(error_code));
386
387 aws_mqtt_request_operation_completion_fn *completion_callback =
388 operation->storage.request_storage.options.completion_callback;
389 void *user_data = operation->storage.request_storage.options.user_data;
390
391 if (completion_callback != NULL) {
392 (*completion_callback)(NULL, error_code, user_data);
393 }
394
395 s_change_operation_state(operation, AWS_MRROS_PENDING_DESTROY);
396
397 aws_mqtt_rr_client_operation_release(operation);
398 }
399
400 static void s_streaming_operation_emit_streaming_subscription_event(
401 struct aws_mqtt_rr_client_operation *operation,
402 enum aws_rr_streaming_subscription_event_type event_type,
403 int error_code) {
404 aws_mqtt_streaming_operation_subscription_status_fn *subscription_status_callback =
405 operation->storage.streaming_storage.options.subscription_status_callback;
406
407 if (subscription_status_callback != NULL) {
408 void *user_data = operation->storage.streaming_storage.options.user_data;
409 (*subscription_status_callback)(event_type, error_code, user_data);
410 }
411 }
412
413 static void s_halt_streaming_operation_with_failure(struct aws_mqtt_rr_client_operation *operation, int error_code) {
414 AWS_FATAL_ASSERT(operation->type == AWS_MRROT_STREAMING);
415 AWS_FATAL_ASSERT(error_code != AWS_ERROR_SUCCESS);
416
417 if (operation->state == AWS_MRROS_PENDING_DESTROY || operation->state == AWS_MRROS_TERMINAL) {
418 return;
419 }
420
421 AWS_LOGF_DEBUG(
422 AWS_LS_MQTT_REQUEST_RESPONSE,
423 "id=%p: streaming operation %" PRIu64 " halted with error code %d(%s)",
424 (void *)operation->client_internal_ref,
425 operation->id,
426 error_code,
427 aws_error_debug_str(error_code));
428
429 s_streaming_operation_emit_streaming_subscription_event(operation, ARRSSET_SUBSCRIPTION_HALTED, error_code);
430
431 s_change_operation_state(operation, AWS_MRROS_TERMINAL);
432 }
433
434 static void s_request_response_fail_operation(struct aws_mqtt_rr_client_operation *operation, int error_code) {
435 if (operation->type == AWS_MRROT_STREAMING) {
436 s_halt_streaming_operation_with_failure(operation, error_code);
437 } else {
438 s_complete_request_operation_with_failure(operation, error_code);
439 }
440 }
441
442 static int s_rr_client_clean_up_operation(void *context, struct aws_hash_element *elem) {
443 (void)context;
444 struct aws_mqtt_rr_client_operation *operation = elem->value;
445
446 s_request_response_fail_operation(operation, AWS_ERROR_MQTT_REQUEST_RESPONSE_CLIENT_SHUT_DOWN);
447
448 return AWS_COMMON_HASH_TABLE_ITER_CONTINUE;
449 }
450
451 static void s_mqtt_request_response_client_external_shutdown_task_fn(
452 struct aws_task *task,
453 void *arg,
454 enum aws_task_status task_status) {
455 (void)task;
456
457 AWS_FATAL_ASSERT(task_status != AWS_TASK_STATUS_CANCELED);
458
459 struct aws_mqtt_request_response_client *client = arg;
460
461 /* stop handling adapter event callbacks */
462 client->state = AWS_RRCS_SHUTTING_DOWN;
463
464 if (client->scheduled_service_timepoint_ns != 0) {
465 aws_event_loop_cancel_task(client->loop, &client->service_task);
466 client->scheduled_service_timepoint_ns = 0;
467 }
468
469 aws_rr_subscription_manager_clean_up(&client->subscription_manager);
470
471 if (client->client_adapter != NULL) {
472 aws_mqtt_protocol_adapter_destroy(client->client_adapter);
473 }
474
475 /*
476 * It is a client invariant that when external shutdown starts, it must be the case that there are no in-flight
477 * operations with un-executed submit tasks. This means it safe to assume that all tracked request operations are
478 * either in the process of cleaning up already (state == AWS_MRROS_PENDING_DESTROY) or can be
479 * completed now (state != AWS_MRROS_PENDING_DESTROY). Non-terminal streaming operations are moved into
480 * a terminal state and emit an appropriate failure/ended event.
481 *
482 * Actual operation destruction and client ref-count release is done by a scheduled task
483 * on the operation that is triggered by dec-refing it (assuming streaming operations get closed by the binding
484 * client).
485 */
486 aws_hash_table_foreach(&client->operations, s_rr_client_clean_up_operation, NULL);
487
488 aws_ref_count_release(&client->internal_ref_count);
489 }
490
491 static void s_mqtt_request_response_client_wake_service(struct aws_mqtt_request_response_client *client) {
492 uint64_t now = 0;
493 aws_high_res_clock_get_ticks(&now);
494
495 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(client->loop));
496
497 if (client->state != AWS_RRCS_ACTIVE) {
498 return;
499 }
500
501 if (client->scheduled_service_timepoint_ns == 0 || now < client->scheduled_service_timepoint_ns) {
502 if (now < client->scheduled_service_timepoint_ns) {
503 aws_event_loop_cancel_task(client->loop, &client->service_task);
504 }
505
506 client->scheduled_service_timepoint_ns = now;
507 aws_event_loop_schedule_task_now(client->loop, &client->service_task);
508
509 AWS_LOGF_DEBUG(
510 AWS_LS_MQTT_REQUEST_RESPONSE, "id=%p: request-response client service task woke", (void *)client);
511 }
512 }
513
514 struct aws_rrc_incomplete_publish {
515 struct aws_allocator *allocator;
516
517 struct aws_mqtt_request_response_client *rr_client;
518
519 uint64_t operation_id;
520 };
521
522 static void s_aws_rrc_incomplete_publish_destroy(struct aws_rrc_incomplete_publish *user_data) {
523 if (user_data == NULL) {
524 return;
525 }
526
527 aws_mqtt_request_response_client_release_internal(user_data->rr_client);
528
529 aws_mem_release(user_data->allocator, user_data);
530 }
531
532 static void s_on_request_publish_completion(int error_code, void *userdata) {
533 struct aws_rrc_incomplete_publish *publish_user_data = userdata;
534
535 if (error_code != AWS_ERROR_SUCCESS) {
536 AWS_LOGF_ERROR(
537 AWS_LS_MQTT_REQUEST_RESPONSE,
538 "id=%p: request-response operation %" PRIu64 " failed publish step due to error %d(%s)",
539 (void *)publish_user_data->rr_client,
540 publish_user_data->operation_id,
541 error_code,
542 aws_error_debug_str(error_code));
543
544 struct aws_hash_element *element = NULL;
545 if (aws_hash_table_find(
546 &publish_user_data->rr_client->operations, &publish_user_data->operation_id, &element) ==
547 AWS_OP_SUCCESS &&
548 element != NULL) {
549 struct aws_mqtt_rr_client_operation *operation = element->value;
550 s_complete_request_operation_with_failure(operation, AWS_ERROR_MQTT_REQUEST_RESPONSE_PUBLISH_FAILURE);
551 }
552 }
553
554 s_aws_rrc_incomplete_publish_destroy(publish_user_data);
555 }
556
557 static void s_make_mqtt_request(
558 struct aws_mqtt_request_response_client *client,
559 struct aws_mqtt_rr_client_operation *operation) {
560 (void)client;
561
562 AWS_FATAL_ASSERT(operation->type == AWS_MRROT_REQUEST);
563
564 struct aws_mqtt_request_operation_options *request_options = &operation->storage.request_storage.options;
565
566 struct aws_rrc_incomplete_publish *publish_user_data =
567 aws_mem_calloc(client->allocator, 1, sizeof(struct aws_rrc_incomplete_publish));
568 publish_user_data->allocator = client->allocator;
569 publish_user_data->rr_client = aws_mqtt_request_response_client_acquire_internal(client);
570 publish_user_data->operation_id = operation->id;
571
572 struct aws_protocol_adapter_publish_options publish_options = {
573 .topic = request_options->publish_topic,
574 .payload = request_options->serialized_request,
575 .ack_timeout_seconds = client->config.operation_timeout_seconds,
576 .completion_callback_fn = s_on_request_publish_completion,
577 .user_data = publish_user_data,
578 };
579
580 if (aws_mqtt_protocol_adapter_publish(client->client_adapter, &publish_options)) {
581 int error_code = aws_last_error();
582
583 AWS_LOGF_ERROR(
584 AWS_LS_MQTT_REQUEST_RESPONSE,
585 "id=%p: request-response operation %" PRIu64 " synchronously failed publish step due to error %d(%s)",
586 (void *)publish_user_data->rr_client,
587 publish_user_data->operation_id,
588 error_code,
589 aws_error_debug_str(error_code));
590 s_complete_request_operation_with_failure(operation, AWS_ERROR_MQTT_REQUEST_RESPONSE_PUBLISH_FAILURE);
591 goto error;
592 }
593
594 return;
595
596 error:
597
598 s_aws_rrc_incomplete_publish_destroy(publish_user_data);
599 }
600
601 struct aws_rr_subscription_status_event_task {
602 struct aws_allocator *allocator;
603
604 struct aws_task task;
605
606 struct aws_mqtt_request_response_client *rr_client;
607
608 enum aws_rr_subscription_event_type type;
609 struct aws_byte_buf topic_filter;
610 uint64_t operation_id;
611 };
612
613 static void s_aws_rr_subscription_status_event_task_delete(struct aws_rr_subscription_status_event_task *task) {
614 if (task == NULL) {
615 return;
616 }
617
618 aws_byte_buf_clean_up(&task->topic_filter);
619 aws_mqtt_request_response_client_release_internal(task->rr_client);
620
621 aws_mem_release(task->allocator, task);
622 }
623
624 static void s_on_request_operation_subscription_status_event(
625 struct aws_mqtt_rr_client_operation *operation,
626 struct aws_byte_cursor topic_filter,
627 enum aws_rr_subscription_event_type event_type) {
628 (void)topic_filter;
629
630 switch (event_type) {
631 case ARRSET_REQUEST_SUBSCRIBE_FAILURE:
632 case ARRSET_REQUEST_SUBSCRIPTION_ENDED:
633 s_complete_request_operation_with_failure(operation, AWS_ERROR_MQTT_REQUEST_RESPONSE_SUBSCRIBE_FAILURE);
634 break;
635
636 case ARRSET_REQUEST_SUBSCRIBE_SUCCESS:
637 if (operation->state == AWS_MRROS_PENDING_SUBSCRIPTION) {
638 --operation->pending_subscriptions;
639 if (operation->pending_subscriptions == 0) {
640 s_change_operation_state(operation, AWS_MRROS_PENDING_RESPONSE);
641 s_make_mqtt_request(operation->client_internal_ref, operation);
642 }
643 }
644 break;
645
646 default:
647 AWS_FATAL_ASSERT(false);
648 }
649 }
650
651 static void s_on_streaming_operation_subscription_status_event(
652 struct aws_mqtt_rr_client_operation *operation,
653 struct aws_byte_cursor topic_filter,
654 enum aws_rr_subscription_event_type event_type) {
655 (void)topic_filter;
656
657 switch (event_type) {
658 case ARRSET_STREAMING_SUBSCRIPTION_ESTABLISHED:
659 if (operation->state == AWS_MRROS_PENDING_SUBSCRIPTION) {
660 s_change_operation_state(operation, AWS_MRROS_SUBSCRIBED);
661 }
662
663 s_streaming_operation_emit_streaming_subscription_event(
664 operation, ARRSSET_SUBSCRIPTION_ESTABLISHED, AWS_ERROR_SUCCESS);
665 break;
666
667 case ARRSET_STREAMING_SUBSCRIPTION_LOST:
668 s_streaming_operation_emit_streaming_subscription_event(
669 operation, ARRSSET_SUBSCRIPTION_LOST, AWS_ERROR_SUCCESS);
670 break;
671
672 case ARRSET_STREAMING_SUBSCRIPTION_HALTED:
673 s_halt_streaming_operation_with_failure(operation, AWS_ERROR_MQTT_REQUEST_RESPONSE_SUBSCRIBE_FAILURE);
674 break;
675
676 default:
677 AWS_FATAL_ASSERT(false);
678 }
679 }
680
681 static void s_handle_subscription_status_event_task(struct aws_task *task, void *arg, enum aws_task_status status) {
682 (void)task;
683
684 struct aws_rr_subscription_status_event_task *event_task = arg;
685
686 if (status == AWS_TASK_STATUS_CANCELED) {
687 goto done;
688 }
689
690 if (event_task->type == ARRSET_UNSUBSCRIBE_COMPLETE || event_task->type == ARRSET_SUBSCRIPTION_EMPTY) {
691 s_mqtt_request_response_client_wake_service(event_task->rr_client);
692 goto done;
693 }
694
695 struct aws_hash_element *element = NULL;
696 if (aws_hash_table_find(&event_task->rr_client->operations, &event_task->operation_id, &element) ||
697 element == NULL) {
698 goto done;
699 }
700
701 struct aws_mqtt_rr_client_operation *operation = element->value;
702
703 switch (event_task->type) {
704 case ARRSET_REQUEST_SUBSCRIBE_SUCCESS:
705 case ARRSET_REQUEST_SUBSCRIBE_FAILURE:
706 case ARRSET_REQUEST_SUBSCRIPTION_ENDED:
707 s_on_request_operation_subscription_status_event(
708 operation, aws_byte_cursor_from_buf(&event_task->topic_filter), event_task->type);
709 break;
710
711 case ARRSET_STREAMING_SUBSCRIPTION_ESTABLISHED:
712 case ARRSET_STREAMING_SUBSCRIPTION_LOST:
713 case ARRSET_STREAMING_SUBSCRIPTION_HALTED:
714 s_on_streaming_operation_subscription_status_event(
715 operation, aws_byte_cursor_from_buf(&event_task->topic_filter), event_task->type);
716 break;
717
718 default:
719 break;
720 }
721
722 done:
723
724 s_aws_rr_subscription_status_event_task_delete(event_task);
725 }
726
727 static struct aws_rr_subscription_status_event_task *s_aws_rr_subscription_status_event_task_new(
728 struct aws_allocator *allocator,
729 struct aws_mqtt_request_response_client *rr_client,
730 const struct aws_rr_subscription_status_event *event) {
731 struct aws_rr_subscription_status_event_task *task =
732 aws_mem_calloc(allocator, 1, sizeof(struct aws_rr_subscription_status_event_task));
733
734 task->allocator = allocator;
735 task->type = event->type;
736 task->operation_id = event->operation_id;
737 task->rr_client = aws_mqtt_request_response_client_acquire_internal(rr_client);
738
739 aws_byte_buf_init_copy_from_cursor(&task->topic_filter, allocator, event->topic_filter);
740
741 aws_task_init(&task->task, s_handle_subscription_status_event_task, task, "SubscriptionStatusEventTask");
742
743 return task;
744 }
745
746 static void s_aws_rr_client_subscription_status_event_callback(
747 const struct aws_rr_subscription_status_event *event,
748 void *userdata) {
749 (void)event;
750 (void)userdata;
751
752 /*
753 * We must be on the event loop, but it's safer overall to process this event as a top-level event loop task. The
754 * subscription manager assumes that we won't call APIs on it while iterating subscription records and listeners.
755 *
756 * These tasks hold an internal reference while they exist.
757 */
758
759 struct aws_mqtt_request_response_client *rr_client = userdata;
760
761 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(rr_client->loop));
762 AWS_FATAL_ASSERT(rr_client->state != AWS_RRCS_SHUTTING_DOWN);
763
764 struct aws_rr_subscription_status_event_task *task =
765 s_aws_rr_subscription_status_event_task_new(rr_client->allocator, rr_client, event);
766
767 aws_event_loop_schedule_task_now(rr_client->loop, &task->task);
768 }
769
770 static void s_aws_rr_client_protocol_adapter_subscription_event_callback(
771 const struct aws_protocol_adapter_subscription_event *event,
772 void *user_data) {
773 struct aws_mqtt_request_response_client *rr_client = user_data;
774
775 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(rr_client->loop));
776
777 if (rr_client->state != AWS_RRCS_ACTIVE) {
778 return;
779 }
780
781 aws_rr_subscription_manager_on_protocol_adapter_subscription_event(&rr_client->subscription_manager, event);
782 }
783
784 static void s_apply_publish_to_streaming_operation_list(
785 const struct aws_linked_list *operations,
786 const struct aws_byte_cursor *topic_filter,
787 const struct aws_mqtt_rr_incoming_publish_event *publish_event,
788 void *user_data) {
789
790 AWS_FATAL_ASSERT(operations != NULL);
791
792 struct aws_mqtt_request_response_client *rr_client = user_data;
793
794 AWS_LOGF_DEBUG(
795 AWS_LS_MQTT_REQUEST_RESPONSE,
796 "id=%p: request-response client incoming publish on topic '" PRInSTR
797 "' matches streaming subscription on topic filter '" PRInSTR "'",
798 (void *)rr_client,
799 AWS_BYTE_CURSOR_PRI(publish_event->topic),
800 AWS_BYTE_CURSOR_PRI(*topic_filter));
801
802 struct aws_linked_list_node *node = aws_linked_list_begin(operations);
803 while (node != aws_linked_list_end(operations)) {
804 struct aws_mqtt_rr_client_operation *operation =
805 AWS_CONTAINER_OF(node, struct aws_mqtt_rr_client_operation, node);
806 node = aws_linked_list_next(node);
807
808 if (operation->type != AWS_MRROT_STREAMING) {
809 continue;
810 }
811
812 if (operation->state == AWS_MRROS_PENDING_DESTROY || operation->state == AWS_MRROS_TERMINAL) {
813 continue;
814 }
815
816 aws_mqtt_streaming_operation_incoming_publish_fn *incoming_publish_callback =
817 operation->storage.streaming_storage.options.incoming_publish_callback;
818 if (!incoming_publish_callback) {
819 continue;
820 }
821
822 void *operation_user_data = operation->storage.streaming_storage.options.user_data;
823 (*incoming_publish_callback)(publish_event, operation_user_data);
824
825 AWS_LOGF_DEBUG(
826 AWS_LS_MQTT_REQUEST_RESPONSE,
827 "id=%p: request-response client incoming publish on topic '" PRInSTR
828 "' routed to streaming operation %" PRIu64,
829 (void *)operation->client_internal_ref,
830 AWS_BYTE_CURSOR_PRI(publish_event->topic),
831 operation->id);
832 }
833 }
834
835 static void s_complete_operation_with_correlation_token(
836 struct aws_mqtt_request_response_client *rr_client,
837 struct aws_byte_cursor correlation_token,
838 const struct aws_mqtt_rr_incoming_publish_event *publish_event) {
839 struct aws_hash_element *hash_element = NULL;
840
841 if (aws_hash_table_find(&rr_client->operations_by_correlation_tokens, &correlation_token, &hash_element)) {
842 return;
843 }
844
845 if (hash_element == NULL) {
846 AWS_LOGF_DEBUG(
847 AWS_LS_MQTT_REQUEST_RESPONSE,
848 "id=%p: request-response client incoming publish on response path topic '" PRInSTR
849 "' and correlation token '" PRInSTR "' does not have an originating request entry",
850 (void *)rr_client,
851 AWS_BYTE_CURSOR_PRI(publish_event->topic),
852 AWS_BYTE_CURSOR_PRI(correlation_token));
853 return;
854 }
855
856 struct aws_mqtt_rr_client_operation *operation = hash_element->value;
857 AWS_FATAL_ASSERT(operation->type == AWS_MRROT_REQUEST);
858
859 if (operation->state == AWS_MRROS_PENDING_DESTROY) {
860 AWS_LOGF_DEBUG(
861 AWS_LS_MQTT_REQUEST_RESPONSE,
862 "id=%p: request-response operation %" PRIu64 " cannot be completed, already in pending destruction state",
863 (void *)operation->client_internal_ref,
864 operation->id);
865 return;
866 }
867
868 AWS_LOGF_DEBUG(
869 AWS_LS_MQTT_REQUEST_RESPONSE,
870 "id=%p: request-response operation %" PRIu64 " completed successfully",
871 (void *)operation->client_internal_ref,
872 operation->id);
873
874 aws_mqtt_request_operation_completion_fn *completion_callback =
875 operation->storage.request_storage.options.completion_callback;
876 void *user_data = operation->storage.request_storage.options.user_data;
877
878 if (completion_callback != NULL) {
879 (*completion_callback)(publish_event, AWS_ERROR_SUCCESS, user_data);
880 }
881
882 s_change_operation_state(operation, AWS_MRROS_PENDING_DESTROY);
883
884 aws_mqtt_rr_client_operation_release(operation);
885 }
886
887 static void s_apply_publish_to_response_path_entry(
888 struct aws_rr_response_path_entry *entry,
889 const struct aws_mqtt_rr_incoming_publish_event *publish_event,
890 void *user_data) {
891
892 struct aws_mqtt_request_response_client *rr_client = user_data;
893
894 AWS_LOGF_DEBUG(
895 AWS_LS_MQTT_REQUEST_RESPONSE,
896 "id=%p: request-response client incoming publish on topic '" PRInSTR "' matches response path",
897 (void *)rr_client,
898 AWS_BYTE_CURSOR_PRI(publish_event->topic));
899
900 struct aws_json_value *json_payload = NULL;
901
902 struct aws_byte_cursor correlation_token;
903 AWS_ZERO_STRUCT(correlation_token);
904 struct aws_byte_cursor correlation_token_json_path = aws_byte_cursor_from_buf(&entry->correlation_token_json_path);
905 if (correlation_token_json_path.len > 0) {
906 json_payload = aws_json_value_new_from_string(rr_client->allocator, publish_event->payload);
907 if (json_payload == NULL) {
908 AWS_LOGF_ERROR(
909 AWS_LS_MQTT_REQUEST_RESPONSE,
910 "id=%p: request-response client incoming publish on response path topic '" PRInSTR
911 "' could not be deserialized into JSON",
912 (void *)rr_client,
913 AWS_BYTE_CURSOR_PRI(publish_event->topic));
914 return;
915 }
916
917 struct aws_byte_cursor segment;
918 AWS_ZERO_STRUCT(segment);
919
920 struct aws_json_value *correlation_token_entry = json_payload;
921 while (aws_byte_cursor_next_split(&correlation_token_json_path, '.', &segment)) {
922 if (!aws_json_value_is_object(correlation_token_entry)) {
923 AWS_LOGF_ERROR(
924 AWS_LS_MQTT_REQUEST_RESPONSE,
925 "id=%p: request-response client incoming publish on response path topic '" PRInSTR
926 "' unable to walk correlation token path '" PRInSTR "'",
927 (void *)rr_client,
928 AWS_BYTE_CURSOR_PRI(publish_event->topic),
929 AWS_BYTE_CURSOR_PRI(correlation_token_json_path));
930 goto done;
931 }
932
933 correlation_token_entry = aws_json_value_get_from_object(correlation_token_entry, segment);
934 if (correlation_token_entry == NULL) {
935 AWS_LOGF_ERROR(
936 AWS_LS_MQTT_REQUEST_RESPONSE,
937 "id=%p: request-response client incoming publish on response path topic '" PRInSTR
938 "' could not find path segment '" PRInSTR "'",
939 (void *)rr_client,
940 AWS_BYTE_CURSOR_PRI(publish_event->topic),
941 AWS_BYTE_CURSOR_PRI(segment));
942 goto done;
943 }
944 }
945
946 if (!aws_json_value_is_string(correlation_token_entry)) {
947 AWS_LOGF_ERROR(
948 AWS_LS_MQTT_REQUEST_RESPONSE,
949 "id=%p: request-response client incoming publish on response path topic '" PRInSTR
950 "' token entry is not a string",
951 (void *)rr_client,
952 AWS_BYTE_CURSOR_PRI(publish_event->topic));
953 goto done;
954 }
955
956 if (aws_json_value_get_string(correlation_token_entry, &correlation_token)) {
957 AWS_LOGF_ERROR(
958 AWS_LS_MQTT_REQUEST_RESPONSE,
959 "id=%p: request-response client incoming publish on response path topic '" PRInSTR
960 "' failed to extract string from token entry",
961 (void *)rr_client,
962 AWS_BYTE_CURSOR_PRI(publish_event->topic));
963 goto done;
964 }
965 }
966
967 s_complete_operation_with_correlation_token(rr_client, correlation_token, publish_event);
968
969 done:
970
971 if (json_payload != NULL) {
972 aws_json_value_destroy(json_payload);
973 }
974 }
975
976 static void s_aws_rr_client_protocol_adapter_incoming_publish_callback(
977 const struct aws_mqtt_rr_incoming_publish_event *publish_event,
978 void *user_data) {
979
980 struct aws_mqtt_request_response_client *rr_client = user_data;
981
982 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(rr_client->loop));
983
984 if (rr_client->state != AWS_RRCS_ACTIVE) {
985 return;
986 }
987
988 aws_mqtt_request_response_client_subscriptions_handle_incoming_publish(
989 &rr_client->subscriptions,
990 publish_event,
991 s_apply_publish_to_streaming_operation_list,
992 s_apply_publish_to_response_path_entry,
993 rr_client);
994 }
995
996 static void s_aws_rr_client_protocol_adapter_terminate_callback(void *user_data) {
997 struct aws_mqtt_request_response_client *rr_client = user_data;
998
999 /* release the internal ref count "held" by the protocol adapter's existence */
1000 aws_ref_count_release(&rr_client->internal_ref_count);
1001 }
1002
1003 static void s_aws_rr_client_protocol_adapter_connection_event_callback(
1004 const struct aws_protocol_adapter_connection_event *event,
1005 void *user_data) {
1006 struct aws_mqtt_request_response_client *rr_client = user_data;
1007
1008 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(rr_client->loop));
1009
1010 if (rr_client->state != AWS_RRCS_ACTIVE) {
1011 return;
1012 }
1013
1014 AWS_LOGF_DEBUG(
1015 AWS_LS_MQTT_REQUEST_RESPONSE,
1016 "id=%p: request-response client applying connection event to subscription manager",
1017 (void *)rr_client);
1018
1019 aws_rr_subscription_manager_on_protocol_adapter_connection_event(&rr_client->subscription_manager, event);
1020 }
1021
1022 static int s_compare_rr_operation_timeouts(const void *a, const void *b) {
1023 const struct aws_mqtt_rr_client_operation **operation_a_ptr = (void *)a;
1024 const struct aws_mqtt_rr_client_operation *operation_a = *operation_a_ptr;
1025
1026 const struct aws_mqtt_rr_client_operation **operation_b_ptr = (void *)b;
1027 const struct aws_mqtt_rr_client_operation *operation_b = *operation_b_ptr;
1028
1029 if (operation_a->timeout_timepoint_ns < operation_b->timeout_timepoint_ns) {
1030 return -1;
1031 } else if (operation_a->timeout_timepoint_ns > operation_b->timeout_timepoint_ns) {
1032 return 1;
1033 } else {
1034 return 0;
1035 }
1036 }
1037
1038 static struct aws_mqtt_request_response_client *s_aws_mqtt_request_response_client_new(
1039 struct aws_allocator *allocator,
1040 const struct aws_mqtt_request_response_client_options *options,
1041 struct aws_event_loop *loop) {
1042 struct aws_rr_subscription_manager_options sm_options = {
1043 .max_request_response_subscriptions = options->max_request_response_subscriptions,
1044 .max_streaming_subscriptions = options->max_streaming_subscriptions,
1045 .operation_timeout_seconds = options->operation_timeout_seconds,
1046 };
1047
1048 /*
1049 * We can't initialize the subscription manager until we're running on the event loop, so make sure that
1050 * initialize can't fail by checking its options for validity now.
1051 */
1052 if (!aws_rr_subscription_manager_are_options_valid(&sm_options)) {
1053 AWS_LOGF_ERROR(
1054 AWS_LS_MQTT_REQUEST_RESPONSE, "(static) request response client creation failed - invalid client options");
1055 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1056 return NULL;
1057 }
1058
1059 struct aws_mqtt_request_response_client *rr_client =
1060 aws_mem_calloc(allocator, 1, sizeof(struct aws_mqtt_request_response_client));
1061
1062 rr_client->allocator = allocator;
1063 rr_client->config = *options;
1064 rr_client->state = AWS_RRCS_UNINITIALIZED;
1065
1066 rr_client->loop = loop;
1067 // kept a reference to the event loop group to keep the event loop alive. It should be released when the client is
1068 // destroyed.
1069 if (!aws_event_loop_group_acquire_from_event_loop(loop)) {
1070 aws_mem_release(allocator, rr_client);
1071 AWS_LOGF_ERROR(
1072 AWS_LS_MQTT_REQUEST_RESPONSE,
1073 "(static) request response client creation failed - unable to acquire event loop group");
1074 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1075 return NULL;
1076 }
1077
1078 aws_hash_table_init(
1079 &rr_client->operations,
1080 allocator,
1081 MQTT_RR_CLIENT_OPERATION_TABLE_DEFAULT_SIZE,
1082 aws_hash_uint64_t_by_identity,
1083 aws_hash_compare_uint64_t_eq,
1084 NULL,
1085 NULL);
1086
1087 aws_priority_queue_init_dynamic(
1088 &rr_client->operations_by_timeout,
1089 allocator,
1090 100,
1091 sizeof(struct aws_mqtt_rr_client_operation *),
1092 s_compare_rr_operation_timeouts);
1093
1094 aws_mqtt_request_response_client_subscriptions_init(&rr_client->subscriptions, allocator);
1095
1096 aws_hash_table_init(
1097 &rr_client->operations_by_correlation_tokens,
1098 allocator,
1099 MQTT_RR_CLIENT_OPERATION_TABLE_DEFAULT_SIZE,
1100 aws_hash_byte_cursor_ptr,
1101 aws_mqtt_byte_cursor_hash_equality,
1102 NULL,
1103 NULL);
1104
1105 aws_linked_list_init(&rr_client->operation_queue);
1106
1107 aws_task_init(
1108 &rr_client->external_shutdown_task,
1109 s_mqtt_request_response_client_external_shutdown_task_fn,
1110 rr_client,
1111 "mqtt_rr_client_external_shutdown");
1112
1113 aws_task_init(
1114 &rr_client->internal_shutdown_task,
1115 s_mqtt_request_response_client_internal_shutdown_task_fn,
1116 rr_client,
1117 "mqtt_rr_client_internal_shutdown");
1118
1119 /* The initial external ref belongs to the caller */
1120 aws_ref_count_init(&rr_client->external_ref_count, rr_client, s_aws_rr_client_on_zero_external_ref_count);
1121
1122 /* The initial internal ref belongs to ourselves (the external ref count shutdown task) */
1123 aws_ref_count_init(&rr_client->internal_ref_count, rr_client, s_aws_rr_client_on_zero_internal_ref_count);
1124
1125 aws_atomic_store_int(&rr_client->next_id, 1);
1126
1127 return rr_client;
1128 }
1129
1130 static void s_aws_rr_client_init_subscription_manager(
1131 struct aws_mqtt_request_response_client *rr_client,
1132 struct aws_allocator *allocator) {
1133 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(rr_client->loop));
1134
1135 struct aws_rr_subscription_manager_options subscription_manager_options = {
1136 .operation_timeout_seconds = rr_client->config.operation_timeout_seconds,
1137 .max_request_response_subscriptions = rr_client->config.max_request_response_subscriptions,
1138 .max_streaming_subscriptions = rr_client->config.max_streaming_subscriptions,
1139 .subscription_status_callback = s_aws_rr_client_subscription_status_event_callback,
1140 .userdata = rr_client,
1141 };
1142
1143 aws_rr_subscription_manager_init(
1144 &rr_client->subscription_manager, allocator, rr_client->client_adapter, &subscription_manager_options);
1145 }
1146
1147 static void s_check_for_operation_timeouts(struct aws_mqtt_request_response_client *client) {
1148 uint64_t now = 0;
1149 aws_high_res_clock_get_ticks(&now);
1150
1151 struct aws_priority_queue *timeout_queue = &client->operations_by_timeout;
1152
1153 bool done = aws_priority_queue_size(timeout_queue) == 0;
1154 while (!done) {
1155 struct aws_mqtt_rr_client_operation **next_operation_by_timeout_ptr = NULL;
1156 aws_priority_queue_top(timeout_queue, (void **)&next_operation_by_timeout_ptr);
1157 AWS_FATAL_ASSERT(next_operation_by_timeout_ptr != NULL);
1158 struct aws_mqtt_rr_client_operation *next_operation_by_timeout = *next_operation_by_timeout_ptr;
1159 AWS_FATAL_ASSERT(next_operation_by_timeout != NULL);
1160
1161 // If the current top of the heap hasn't timed out than nothing has
1162 if (next_operation_by_timeout->timeout_timepoint_ns > now) {
1163 break;
1164 }
1165
1166 /* Ack timeout for this operation has been reached */
1167 aws_priority_queue_pop(timeout_queue, &next_operation_by_timeout);
1168
1169 s_request_response_fail_operation(next_operation_by_timeout, AWS_ERROR_MQTT_REQUEST_RESPONSE_TIMEOUT);
1170
1171 done = aws_priority_queue_size(timeout_queue) == 0;
1172 }
1173 }
1174
1175 static uint64_t s_mqtt_request_response_client_get_next_service_time(struct aws_mqtt_request_response_client *client) {
1176 if (aws_priority_queue_size(&client->operations_by_timeout) > 0) {
1177 struct aws_mqtt_rr_client_operation **next_operation_by_timeout_ptr = NULL;
1178 aws_priority_queue_top(&client->operations_by_timeout, (void **)&next_operation_by_timeout_ptr);
1179 AWS_FATAL_ASSERT(next_operation_by_timeout_ptr != NULL);
1180 struct aws_mqtt_rr_client_operation *next_operation_by_timeout = *next_operation_by_timeout_ptr;
1181 AWS_FATAL_ASSERT(next_operation_by_timeout != NULL);
1182
1183 return next_operation_by_timeout->timeout_timepoint_ns;
1184 }
1185
1186 return UINT64_MAX;
1187 }
1188
1189 static int s_add_streaming_operation_to_subscription_topic_filter_table(
1190 struct aws_mqtt_request_response_client *client,
1191 struct aws_mqtt_rr_client_operation *operation) {
1192
1193 struct aws_byte_cursor topic_filter_cursor = operation->storage.streaming_storage.options.topic_filter;
1194
1195 struct aws_rr_operation_list_topic_filter_entry *entry =
1196 aws_mqtt_request_response_client_subscriptions_add_stream_subscription(
1197 &client->subscriptions, &topic_filter_cursor);
1198 if (entry == NULL) {
1199 return AWS_OP_ERR;
1200 }
1201
1202 if (aws_linked_list_node_is_in_list(&operation->node)) {
1203 aws_linked_list_remove(&operation->node);
1204 }
1205
1206 AWS_LOGF_DEBUG(
1207 AWS_LS_MQTT_REQUEST_RESPONSE,
1208 "id=%p: request-response client adding streaming operation %" PRIu64
1209 " to streaming subscription table with topic_filter '" PRInSTR "'",
1210 (void *)client,
1211 operation->id,
1212 AWS_BYTE_CURSOR_PRI(topic_filter_cursor));
1213
1214 aws_linked_list_push_back(&entry->operations, &operation->node);
1215
1216 return AWS_OP_SUCCESS;
1217 }
1218
1219 static int s_add_request_operation_to_response_path_table(
1220 struct aws_mqtt_request_response_client *client,
1221 struct aws_mqtt_rr_client_operation *operation) {
1222
1223 struct aws_array_list *paths = &operation->storage.request_storage.operation_response_paths;
1224 size_t path_count = aws_array_list_length(paths);
1225 for (size_t i = 0; i < path_count; ++i) {
1226 struct aws_mqtt_request_operation_response_path path;
1227 aws_array_list_get_at(paths, &path, i);
1228 if (aws_mqtt_request_response_client_subscriptions_add_request_subscription(
1229 &client->subscriptions, &path.topic, &path.correlation_token_json_path)) {
1230 return AWS_OP_ERR;
1231 }
1232 }
1233 return AWS_OP_SUCCESS;
1234 }
1235
1236 static int s_add_request_operation_to_correlation_token_table(
1237 struct aws_mqtt_request_response_client *client,
1238 struct aws_mqtt_rr_client_operation *operation) {
1239
1240 return aws_hash_table_put(
1241 &client->operations_by_correlation_tokens,
1242 &operation->storage.request_storage.options.correlation_token,
1243 operation,
1244 NULL);
1245 }
1246
1247 static int s_add_in_progress_operation_to_tracking_tables(
1248 struct aws_mqtt_request_response_client *client,
1249 struct aws_mqtt_rr_client_operation *operation) {
1250 if (operation->type == AWS_MRROT_STREAMING) {
1251 if (s_add_streaming_operation_to_subscription_topic_filter_table(client, operation)) {
1252 return AWS_OP_ERR;
1253 }
1254 } else {
1255 if (s_add_request_operation_to_response_path_table(client, operation)) {
1256 return AWS_OP_ERR;
1257 }
1258
1259 if (s_add_request_operation_to_correlation_token_table(client, operation)) {
1260 return AWS_OP_ERR;
1261 }
1262 }
1263
1264 operation->in_client_tables = true;
1265
1266 return AWS_OP_SUCCESS;
1267 }
1268
1269 static void s_handle_operation_subscribe_result(
1270 struct aws_mqtt_request_response_client *client,
1271 struct aws_mqtt_rr_client_operation *operation,
1272 enum aws_acquire_subscription_result_type subscribe_result) {
1273 if (subscribe_result == AASRT_FAILURE || subscribe_result == AASRT_NO_CAPACITY) {
1274 int error_code = (subscribe_result == AASRT_NO_CAPACITY)
1275 ? AWS_ERROR_MQTT_REQUEST_RESPONSE_NO_SUBSCRIPTION_CAPACITY
1276 : AWS_ERROR_MQTT_REQUEST_RESPONSE_SUBSCRIBE_FAILURE;
1277 s_request_response_fail_operation(operation, error_code);
1278 return;
1279 }
1280
1281 if (s_add_in_progress_operation_to_tracking_tables(client, operation)) {
1282 s_request_response_fail_operation(operation, AWS_ERROR_MQTT_REQUEST_RESPONSE_INTERNAL_ERROR);
1283 return;
1284 }
1285
1286 if (subscribe_result == AASRT_SUBSCRIBING) {
1287 s_change_operation_state(operation, AWS_MRROS_PENDING_SUBSCRIPTION);
1288 return;
1289 }
1290
1291 if (operation->type == AWS_MRROT_STREAMING) {
1292 s_change_operation_state(operation, AWS_MRROS_SUBSCRIBED);
1293 s_streaming_operation_emit_streaming_subscription_event(
1294 operation, ARRSSET_SUBSCRIPTION_ESTABLISHED, AWS_ERROR_SUCCESS);
1295 } else {
1296 s_make_mqtt_request(client, operation);
1297 }
1298 }
1299
1300 static enum aws_rr_subscription_type s_rr_operation_type_to_subscription_type(
1301 enum aws_mqtt_request_response_operation_type type) {
1302 if (type == AWS_MRROT_REQUEST) {
1303 return ARRST_REQUEST_RESPONSE;
1304 }
1305
1306 return ARRST_EVENT_STREAM;
1307 }
1308
1309 static bool s_can_operation_dequeue(
1310 struct aws_mqtt_request_response_client *client,
1311 struct aws_mqtt_rr_client_operation *operation) {
1312 if (operation->type != AWS_MRROT_REQUEST) {
1313 return true;
1314 }
1315
1316 struct aws_hash_element *token_element = NULL;
1317 if (aws_hash_table_find(
1318 &client->operations_by_correlation_tokens,
1319 &operation->storage.request_storage.options.correlation_token,
1320 &token_element)) {
1321 return false;
1322 }
1323
1324 return token_element == NULL;
1325 }
1326
1327 static struct aws_byte_cursor *s_aws_mqtt_rr_operation_get_subscription_topic_filters(
1328 struct aws_mqtt_rr_client_operation *operation) {
1329 if (operation->type == AWS_MRROT_STREAMING) {
1330 return &operation->storage.streaming_storage.options.topic_filter;
1331 } else {
1332 return operation->storage.request_storage.options.subscription_topic_filters;
1333 }
1334 }
1335
1336 static size_t s_aws_mqtt_rr_operation_get_subscription_topic_filter_count(
1337 struct aws_mqtt_rr_client_operation *operation) {
1338 if (operation->type == AWS_MRROT_STREAMING) {
1339 return 1;
1340 } else {
1341 return operation->storage.request_storage.options.subscription_topic_filter_count;
1342 }
1343 }
1344
1345 static void s_process_queued_operations(struct aws_mqtt_request_response_client *client) {
1346 aws_rr_subscription_manager_purge_unused(&client->subscription_manager);
1347
1348 while (!aws_linked_list_empty(&client->operation_queue)) {
1349 struct aws_linked_list_node *head = aws_linked_list_front(&client->operation_queue);
1350 struct aws_mqtt_rr_client_operation *head_operation =
1351 AWS_CONTAINER_OF(head, struct aws_mqtt_rr_client_operation, node);
1352
1353 if (!s_can_operation_dequeue(client, head_operation)) {
1354 break;
1355 }
1356
1357 struct aws_rr_acquire_subscription_options subscribe_options = {
1358 .topic_filters = s_aws_mqtt_rr_operation_get_subscription_topic_filters(head_operation),
1359 .topic_filter_count = s_aws_mqtt_rr_operation_get_subscription_topic_filter_count(head_operation),
1360 .operation_id = head_operation->id,
1361 .type = s_rr_operation_type_to_subscription_type(head_operation->type),
1362 };
1363
1364 enum aws_acquire_subscription_result_type subscribe_result =
1365 aws_rr_subscription_manager_acquire_subscription(&client->subscription_manager, &subscribe_options);
1366
1367 AWS_LOGF_DEBUG(
1368 AWS_LS_MQTT_REQUEST_RESPONSE,
1369 "id=%p: request-response client intake, queued operation %" PRIu64
1370 " yielded acquire subscription result: %s",
1371 (void *)client,
1372 head_operation->id,
1373 s_aws_acquire_subscription_result_type(subscribe_result));
1374
1375 if (subscribe_result == AASRT_BLOCKED) {
1376 break;
1377 }
1378
1379 aws_linked_list_pop_front(&client->operation_queue);
1380 s_handle_operation_subscribe_result(client, head_operation, subscribe_result);
1381 }
1382 }
1383
1384 static void s_mqtt_request_response_service_task_fn(
1385 struct aws_task *task,
1386 void *arg,
1387 enum aws_task_status task_status) {
1388 (void)task;
1389
1390 if (task_status == AWS_TASK_STATUS_CANCELED) {
1391 return;
1392 }
1393
1394 struct aws_mqtt_request_response_client *client = arg;
1395 client->scheduled_service_timepoint_ns = 0;
1396
1397 if (client->state == AWS_RRCS_ACTIVE) {
1398
1399 // timeouts
1400 s_check_for_operation_timeouts(client);
1401
1402 // operation queue
1403 s_process_queued_operations(client);
1404
1405 // schedule next service
1406 client->scheduled_service_timepoint_ns = s_mqtt_request_response_client_get_next_service_time(client);
1407 aws_event_loop_schedule_task_future(
1408 client->loop, &client->service_task, client->scheduled_service_timepoint_ns);
1409
1410 AWS_LOGF_DEBUG(
1411 AWS_LS_MQTT_REQUEST_RESPONSE,
1412 "id=%p: request-response client service, next timepoint: %" PRIu64,
1413 (void *)client,
1414 client->scheduled_service_timepoint_ns);
1415 }
1416 }
1417
1418 static void s_mqtt_request_response_client_initialize_task_fn(
1419 struct aws_task *task,
1420 void *arg,
1421 enum aws_task_status task_status) {
1422 (void)task;
1423
1424 AWS_FATAL_ASSERT(task_status != AWS_TASK_STATUS_CANCELED);
1425
1426 struct aws_mqtt_request_response_client *client = arg;
1427
1428 if (client->state == AWS_RRCS_UNINITIALIZED) {
1429 s_aws_rr_client_init_subscription_manager(client, client->allocator);
1430
1431 client->state = AWS_RRCS_ACTIVE;
1432
1433 aws_task_init(&client->service_task, s_mqtt_request_response_service_task_fn, client, "mqtt_rr_client_service");
1434
1435 aws_event_loop_schedule_task_future(client->loop, &client->service_task, UINT64_MAX);
1436 client->scheduled_service_timepoint_ns = UINT64_MAX;
1437 }
1438
1439 if (client->config.initialized_callback != NULL) {
1440 (*client->config.initialized_callback)(client->config.user_data);
1441 }
1442
1443 /* give up the internal ref we held while the task was pending */
1444 aws_ref_count_release(&client->internal_ref_count);
1445 }
1446
1447 static void s_setup_cross_thread_initialization(struct aws_mqtt_request_response_client *rr_client) {
1448 /* now that it exists, 1 internal ref belongs to protocol adapter termination */
1449 aws_ref_count_acquire(&rr_client->internal_ref_count);
1450
1451 /* 1 internal ref belongs to the initialize task until it runs */
1452 aws_ref_count_acquire(&rr_client->internal_ref_count);
1453
1454 aws_task_init(
1455 &rr_client->initialize_task,
1456 s_mqtt_request_response_client_initialize_task_fn,
1457 rr_client,
1458 "mqtt_rr_client_initialize");
1459 aws_event_loop_schedule_task_now(rr_client->loop, &rr_client->initialize_task);
1460 }
1461
1462 struct aws_mqtt_request_response_client *aws_mqtt_request_response_client_new_from_mqtt311_client(
1463 struct aws_allocator *allocator,
1464 struct aws_mqtt_client_connection *client,
1465 const struct aws_mqtt_request_response_client_options *options) {
1466
1467 struct aws_mqtt_request_response_client *rr_client =
1468 s_aws_mqtt_request_response_client_new(allocator, options, aws_mqtt_client_connection_get_event_loop(client));
1469
1470 if (rr_client == NULL) {
1471 return NULL;
1472 }
1473
1474 struct aws_mqtt_protocol_adapter_options adapter_options = {
1475 .subscription_event_callback = s_aws_rr_client_protocol_adapter_subscription_event_callback,
1476 .incoming_publish_callback = s_aws_rr_client_protocol_adapter_incoming_publish_callback,
1477 .terminate_callback = s_aws_rr_client_protocol_adapter_terminate_callback,
1478 .connection_event_callback = s_aws_rr_client_protocol_adapter_connection_event_callback,
1479 .user_data = rr_client,
1480 };
1481
1482 rr_client->client_adapter = aws_mqtt_protocol_adapter_new_from_311(rr_client->allocator, &adapter_options, client);
1483 if (rr_client->client_adapter == NULL) {
1484 goto error;
1485 }
1486
1487 s_setup_cross_thread_initialization(rr_client);
1488
1489 return rr_client;
1490
1491 error:
1492
1493 /* even on construction failures we still need to walk through the async shutdown process */
1494 aws_mqtt_request_response_client_release(rr_client);
1495
1496 return NULL;
1497 }
1498
1499 struct aws_mqtt_request_response_client *aws_mqtt_request_response_client_new_from_mqtt5_client(
1500 struct aws_allocator *allocator,
1501 struct aws_mqtt5_client *client,
1502 const struct aws_mqtt_request_response_client_options *options) {
1503
1504 struct aws_mqtt_request_response_client *rr_client =
1505 s_aws_mqtt_request_response_client_new(allocator, options, client->loop);
1506
1507 if (rr_client == NULL) {
1508 return NULL;
1509 }
1510
1511 struct aws_mqtt_protocol_adapter_options adapter_options = {
1512 .subscription_event_callback = s_aws_rr_client_protocol_adapter_subscription_event_callback,
1513 .incoming_publish_callback = s_aws_rr_client_protocol_adapter_incoming_publish_callback,
1514 .terminate_callback = s_aws_rr_client_protocol_adapter_terminate_callback,
1515 .connection_event_callback = s_aws_rr_client_protocol_adapter_connection_event_callback,
1516 .user_data = rr_client,
1517 };
1518
1519 rr_client->client_adapter = aws_mqtt_protocol_adapter_new_from_5(rr_client->allocator, &adapter_options, client);
1520 if (rr_client->client_adapter == NULL) {
1521 goto error;
1522 }
1523
1524 s_setup_cross_thread_initialization(rr_client);
1525
1526 return rr_client;
1527
1528 error:
1529
1530 /* even on construction failures we still need to walk through the async shutdown process */
1531 aws_mqtt_request_response_client_release(rr_client);
1532
1533 return NULL;
1534 }
1535
1536 struct aws_mqtt_request_response_client *aws_mqtt_request_response_client_acquire(
1537 struct aws_mqtt_request_response_client *client) {
1538 if (client != NULL) {
1539 aws_ref_count_acquire(&client->external_ref_count);
1540 }
1541
1542 return client;
1543 }
1544
1545 struct aws_mqtt_request_response_client *aws_mqtt_request_response_client_release(
1546 struct aws_mqtt_request_response_client *client) {
1547 if (client != NULL) {
1548 aws_ref_count_release(&client->external_ref_count);
1549 }
1550
1551 return NULL;
1552 }
1553
1554 /////////////////////////////////////////////////
1555
1556 static bool s_are_request_operation_options_valid(
1557 const struct aws_mqtt_request_response_client *client,
1558 const struct aws_mqtt_request_operation_options *request_options) {
1559 if (request_options == NULL) {
1560 AWS_LOGF_ERROR(AWS_LS_MQTT_REQUEST_RESPONSE, "(%p) rr client - NULL request options", (void *)client);
1561 return false;
1562 }
1563
1564 if (request_options->response_path_count == 0) {
1565 AWS_LOGF_ERROR(
1566 AWS_LS_MQTT_REQUEST_RESPONSE,
1567 "(%p) rr client request options - no response paths supplied",
1568 (void *)client);
1569 return false;
1570 }
1571
1572 for (size_t i = 0; i < request_options->response_path_count; ++i) {
1573 const struct aws_mqtt_request_operation_response_path *path = &request_options->response_paths[i];
1574 if (!aws_mqtt_is_valid_topic(&path->topic)) {
1575 AWS_LOGF_ERROR(
1576 AWS_LS_MQTT_REQUEST_RESPONSE,
1577 "(%p) rr client request options - " PRInSTR " is not a valid topic",
1578 (void *)client,
1579 AWS_BYTE_CURSOR_PRI(path->topic));
1580 return false;
1581 }
1582 }
1583
1584 if (!aws_mqtt_is_valid_topic(&request_options->publish_topic)) {
1585 AWS_LOGF_ERROR(
1586 AWS_LS_MQTT_REQUEST_RESPONSE,
1587 "(%p) rr client request options - " PRInSTR " is not a valid topic",
1588 (void *)client,
1589 AWS_BYTE_CURSOR_PRI(request_options->publish_topic));
1590 return false;
1591 }
1592
1593 if (request_options->subscription_topic_filter_count == 0) {
1594 AWS_LOGF_ERROR(
1595 AWS_LS_MQTT_REQUEST_RESPONSE,
1596 "(%p) rr client request options - no subscription topic filters supplied",
1597 (void *)client);
1598 return false;
1599 }
1600
1601 for (size_t i = 0; i < request_options->subscription_topic_filter_count; ++i) {
1602 const struct aws_byte_cursor subscription_topic_filter = request_options->subscription_topic_filters[i];
1603 if (!aws_mqtt_is_valid_topic_filter(&subscription_topic_filter)) {
1604 AWS_LOGF_ERROR(
1605 AWS_LS_MQTT_REQUEST_RESPONSE,
1606 "(%p) rr client request options - " PRInSTR " is not a valid subscription topic filter",
1607 (void *)client,
1608 AWS_BYTE_CURSOR_PRI(subscription_topic_filter));
1609 return false;
1610 }
1611 }
1612
1613 if (request_options->serialized_request.len == 0) {
1614 AWS_LOGF_ERROR(
1615 AWS_LS_MQTT_REQUEST_RESPONSE, "(%p) rr client request options - empty request payload", (void *)client);
1616 return false;
1617 }
1618
1619 return true;
1620 }
1621
1622 static bool s_are_streaming_operation_options_valid(
1623 struct aws_mqtt_request_response_client *client,
1624 const struct aws_mqtt_streaming_operation_options *streaming_options) {
1625 if (streaming_options == NULL) {
1626 AWS_LOGF_ERROR(AWS_LS_MQTT_REQUEST_RESPONSE, "(%p) rr client - NULL streaming options", (void *)client);
1627 return false;
1628 }
1629
1630 if (!aws_mqtt_is_valid_topic_filter(&streaming_options->topic_filter)) {
1631 AWS_LOGF_ERROR(
1632 AWS_LS_MQTT_REQUEST_RESPONSE,
1633 "(%p) rr client streaming options - " PRInSTR " is not a valid topic filter",
1634 (void *)client,
1635 AWS_BYTE_CURSOR_PRI(streaming_options->topic_filter));
1636 return false;
1637 }
1638
1639 return true;
1640 }
1641
1642 static uint64_t s_aws_mqtt_request_response_client_allocate_operation_id(
1643 struct aws_mqtt_request_response_client *client) {
1644 return aws_atomic_fetch_add(&client->next_id, 1);
1645 }
1646
1647 static void s_mqtt_rr_client_submit_operation(struct aws_task *task, void *arg, enum aws_task_status status) {
1648 (void)task;
1649
1650 struct aws_mqtt_rr_client_operation *operation = arg;
1651 struct aws_mqtt_request_response_client *client = operation->client_internal_ref;
1652
1653 if (status == AWS_TASK_STATUS_CANCELED) {
1654 goto done;
1655 }
1656
1657 if (client->state == AWS_RRCS_SHUTTING_DOWN) {
1658 s_request_response_fail_operation(operation, AWS_ERROR_MQTT_REQUEST_RESPONSE_CLIENT_SHUT_DOWN);
1659 goto done;
1660 }
1661
1662 AWS_LOGF_DEBUG(
1663 AWS_LS_MQTT_REQUEST_RESPONSE,
1664 "id=%p: request-response client, queuing operation %" PRIu64,
1665 (void *)client,
1666 operation->id);
1667
1668 // add appropriate client table entries
1669 aws_hash_table_put(&client->operations, &operation->id, operation, NULL);
1670
1671 // add to timeout priority queue
1672 if (operation->type == AWS_MRROT_REQUEST) {
1673 aws_priority_queue_push_ref(
1674 &client->operations_by_timeout, (void *)&operation, &operation->priority_queue_node);
1675 }
1676
1677 // enqueue
1678 aws_linked_list_push_back(&operation->client_internal_ref->operation_queue, &operation->node);
1679
1680 s_change_operation_state(operation, AWS_MRROS_QUEUED);
1681
1682 s_mqtt_request_response_client_wake_service(operation->client_internal_ref);
1683
1684 done:
1685
1686 /*
1687 * We hold a second reference to the operation during submission. This ensures that even if a streaming operation
1688 * is immediately dec-refed by the creator (before submission completes), the operation will not get destroyed.
1689 *
1690 * It is now safe and correct to release that reference.
1691 *
1692 * After this, streaming operation lifetime is completely user-driven, while request operation lifetime is
1693 * completely client-internal.
1694 */
1695 aws_mqtt_rr_client_operation_release(operation);
1696 }
1697
1698 static void s_aws_mqtt_streaming_operation_storage_clean_up(struct aws_mqtt_streaming_operation_storage *storage) {
1699 aws_byte_buf_clean_up(&storage->operation_data);
1700 }
1701
1702 static void s_aws_mqtt_request_operation_storage_clean_up(struct aws_mqtt_request_operation_storage *storage) {
1703 aws_array_list_clean_up(&storage->operation_response_paths);
1704 aws_array_list_clean_up(&storage->subscription_topic_filters);
1705 aws_byte_buf_clean_up(&storage->operation_data);
1706 }
1707
1708 static void s_remove_operation_from_client_tables(struct aws_mqtt_rr_client_operation *operation) {
1709 if (operation->type != AWS_MRROT_REQUEST) {
1710 return;
1711 }
1712
1713 if (!operation->in_client_tables) {
1714 return;
1715 }
1716
1717 struct aws_mqtt_request_response_client *client = operation->client_internal_ref;
1718
1719 aws_hash_table_remove(
1720 &client->operations_by_correlation_tokens,
1721 &operation->storage.request_storage.options.correlation_token,
1722 NULL,
1723 NULL);
1724
1725 struct aws_array_list *paths = &operation->storage.request_storage.operation_response_paths;
1726
1727 size_t path_count = aws_array_list_length(paths);
1728 for (size_t i = 0; i < path_count; ++i) {
1729 struct aws_mqtt_request_operation_response_path path;
1730 aws_array_list_get_at(paths, &path, i);
1731 if (aws_mqtt_request_response_client_subscriptions_remove_request_subscription(
1732 &client->subscriptions, &path.topic) == AWS_OP_ERR) {
1733 AWS_LOGF_ERROR(
1734 AWS_LS_MQTT_REQUEST_RESPONSE,
1735 "id=%p: internal state error removing reference to response path for topic " PRInSTR,
1736 (void *)client,
1737 AWS_BYTE_CURSOR_PRI(path.topic));
1738 }
1739 }
1740 }
1741
1742 static void s_mqtt_rr_client_destroy_operation(struct aws_task *task, void *arg, enum aws_task_status status) {
1743 (void)task;
1744 (void)status;
1745
1746 struct aws_mqtt_rr_client_operation *operation = arg;
1747 struct aws_mqtt_request_response_client *client = operation->client_internal_ref;
1748
1749 aws_hash_table_remove(&client->operations, &operation->id, NULL, NULL);
1750 s_remove_operation_from_timeout_queue(operation);
1751
1752 if (aws_linked_list_node_is_in_list(&operation->node)) {
1753 aws_linked_list_remove(&operation->node);
1754 }
1755
1756 if (client->state != AWS_RRCS_SHUTTING_DOWN) {
1757 struct aws_rr_release_subscription_options release_options = {
1758 .topic_filters = s_aws_mqtt_rr_operation_get_subscription_topic_filters(operation),
1759 .topic_filter_count = s_aws_mqtt_rr_operation_get_subscription_topic_filter_count(operation),
1760 .operation_id = operation->id,
1761 };
1762 aws_rr_subscription_manager_release_subscription(&client->subscription_manager, &release_options);
1763 }
1764
1765 s_remove_operation_from_client_tables(operation);
1766
1767 aws_mqtt_request_response_client_release_internal(operation->client_internal_ref);
1768
1769 if (operation->type == AWS_MRROT_STREAMING) {
1770 s_aws_mqtt_streaming_operation_storage_clean_up(&operation->storage.streaming_storage);
1771 } else {
1772 s_aws_mqtt_request_operation_storage_clean_up(&operation->storage.request_storage);
1773 }
1774
1775 aws_mqtt_streaming_operation_terminated_fn *terminated_callback = NULL;
1776 void *terminated_user_data = NULL;
1777 if (operation->type == AWS_MRROT_STREAMING) {
1778 terminated_callback = operation->storage.streaming_storage.options.terminated_callback;
1779 terminated_user_data = operation->storage.streaming_storage.options.user_data;
1780 }
1781
1782 aws_mem_release(operation->allocator, operation);
1783
1784 if (terminated_callback != NULL) {
1785 (*terminated_callback)(terminated_user_data);
1786 }
1787 }
1788
1789 static void s_on_mqtt_rr_client_operation_zero_ref_count(void *context) {
1790 struct aws_mqtt_rr_client_operation *operation = context;
1791
1792 aws_event_loop_schedule_task_now(operation->client_internal_ref->loop, &operation->destroy_task);
1793 }
1794
1795 static void s_aws_mqtt_rr_client_operation_init_shared(
1796 struct aws_mqtt_rr_client_operation *operation,
1797 struct aws_mqtt_request_response_client *client) {
1798 operation->allocator = client->allocator;
1799 aws_ref_count_init(&operation->ref_count, operation, s_on_mqtt_rr_client_operation_zero_ref_count);
1800
1801 operation->client_internal_ref = aws_mqtt_request_response_client_acquire_internal(client);
1802 operation->id = s_aws_mqtt_request_response_client_allocate_operation_id(client);
1803 s_change_operation_state(operation, AWS_MRROS_NONE);
1804
1805 aws_task_init(
1806 &operation->submit_task,
1807 s_mqtt_rr_client_submit_operation,
1808 operation,
1809 "MQTTRequestResponseClientOperationSubmit");
1810 aws_task_init(
1811 &operation->destroy_task,
1812 s_mqtt_rr_client_destroy_operation,
1813 operation,
1814 "MQTTRequestResponseClientOperationDestroy");
1815 }
1816
1817 void s_aws_mqtt_request_operation_storage_init_from_options(
1818 struct aws_mqtt_request_operation_storage *storage,
1819 struct aws_allocator *allocator,
1820 const struct aws_mqtt_request_operation_options *request_options) {
1821
1822 size_t bytes_needed = 0;
1823 bytes_needed += request_options->publish_topic.len;
1824 bytes_needed += request_options->serialized_request.len;
1825 bytes_needed += request_options->correlation_token.len;
1826
1827 for (size_t i = 0; i < request_options->subscription_topic_filter_count; ++i) {
1828 const struct aws_byte_cursor *subscription_topic_filter = &request_options->subscription_topic_filters[i];
1829
1830 bytes_needed += subscription_topic_filter->len;
1831 }
1832
1833 for (size_t i = 0; i < request_options->response_path_count; ++i) {
1834 const struct aws_mqtt_request_operation_response_path *response_path = &request_options->response_paths[i];
1835
1836 bytes_needed += response_path->topic.len;
1837 bytes_needed += response_path->correlation_token_json_path.len;
1838 }
1839
1840 storage->options = *request_options;
1841
1842 aws_byte_buf_init(&storage->operation_data, allocator, bytes_needed);
1843 aws_array_list_init_dynamic(
1844 &storage->operation_response_paths,
1845 allocator,
1846 request_options->response_path_count,
1847 sizeof(struct aws_mqtt_request_operation_response_path));
1848 aws_array_list_init_dynamic(
1849 &storage->subscription_topic_filters,
1850 allocator,
1851 request_options->subscription_topic_filter_count,
1852 sizeof(struct aws_byte_cursor));
1853
1854 AWS_FATAL_ASSERT(
1855 aws_byte_buf_append_and_update(&storage->operation_data, &storage->options.publish_topic) == AWS_OP_SUCCESS);
1856 AWS_FATAL_ASSERT(
1857 aws_byte_buf_append_and_update(&storage->operation_data, &storage->options.serialized_request) ==
1858 AWS_OP_SUCCESS);
1859 AWS_FATAL_ASSERT(
1860 aws_byte_buf_append_and_update(&storage->operation_data, &storage->options.correlation_token) ==
1861 AWS_OP_SUCCESS);
1862
1863 for (size_t i = 0; i < request_options->subscription_topic_filter_count; ++i) {
1864 struct aws_byte_cursor subscription_topic_filter = request_options->subscription_topic_filters[i];
1865
1866 AWS_FATAL_ASSERT(
1867 aws_byte_buf_append_and_update(&storage->operation_data, &subscription_topic_filter) == AWS_OP_SUCCESS);
1868
1869 aws_array_list_push_back(&storage->subscription_topic_filters, &subscription_topic_filter);
1870 }
1871
1872 storage->options.subscription_topic_filters = storage->subscription_topic_filters.data;
1873
1874 for (size_t i = 0; i < request_options->response_path_count; ++i) {
1875 struct aws_mqtt_request_operation_response_path response_path = request_options->response_paths[i];
1876
1877 AWS_FATAL_ASSERT(
1878 aws_byte_buf_append_and_update(&storage->operation_data, &response_path.topic) == AWS_OP_SUCCESS);
1879 AWS_FATAL_ASSERT(
1880 aws_byte_buf_append_and_update(&storage->operation_data, &response_path.correlation_token_json_path) ==
1881 AWS_OP_SUCCESS);
1882
1883 aws_array_list_push_back(&storage->operation_response_paths, &response_path);
1884 }
1885
1886 storage->options.response_paths = storage->operation_response_paths.data;
1887 }
1888
1889 static void s_log_request_response_operation(
1890 struct aws_mqtt_rr_client_operation *operation,
1891 struct aws_mqtt_request_response_client *client) {
1892 struct aws_logger *log_handle = aws_logger_get_conditional(AWS_LS_MQTT_REQUEST_RESPONSE, AWS_LL_DEBUG);
1893 if (log_handle == NULL) {
1894 return;
1895 }
1896
1897 struct aws_mqtt_request_operation_options *options = &operation->storage.request_storage.options;
1898
1899 for (size_t i = 0; i < options->subscription_topic_filter_count; ++i) {
1900 struct aws_byte_cursor subscription_topic_filter = options->subscription_topic_filters[i];
1901
1902 AWS_LOGUF(
1903 log_handle,
1904 AWS_LL_DEBUG,
1905 AWS_LS_MQTT_REQUEST_RESPONSE,
1906 "id=%p: request-response client operation %" PRIu64 " - subscription topic filter %zu topic '" PRInSTR "'",
1907 (void *)client,
1908 operation->id,
1909 i,
1910 AWS_BYTE_CURSOR_PRI(subscription_topic_filter));
1911 }
1912
1913 AWS_LOGUF(
1914 log_handle,
1915 AWS_LL_DEBUG,
1916 AWS_LS_MQTT_REQUEST_RESPONSE,
1917 "id=%p: request-response client operation %" PRIu64 " - correlation token: '" PRInSTR "'",
1918 (void *)client,
1919 operation->id,
1920 AWS_BYTE_CURSOR_PRI(options->correlation_token));
1921
1922 AWS_LOGUF(
1923 log_handle,
1924 AWS_LL_DEBUG,
1925 AWS_LS_MQTT_REQUEST_RESPONSE,
1926 "id=%p: request-response client operation %" PRIu64 " - publish topic: '" PRInSTR "'",
1927 (void *)client,
1928 operation->id,
1929 AWS_BYTE_CURSOR_PRI(options->publish_topic));
1930
1931 AWS_LOGUF(
1932 log_handle,
1933 AWS_LL_DEBUG,
1934 AWS_LS_MQTT_REQUEST_RESPONSE,
1935 "id=%p: request-response client operation %" PRIu64 " - %zu response paths:",
1936 (void *)client,
1937 operation->id,
1938 options->response_path_count);
1939
1940 for (size_t i = 0; i < options->response_path_count; ++i) {
1941 struct aws_mqtt_request_operation_response_path *response_path = &options->response_paths[i];
1942
1943 AWS_LOGUF(
1944 log_handle,
1945 AWS_LL_DEBUG,
1946 AWS_LS_MQTT_REQUEST_RESPONSE,
1947 "id=%p: request-response client operation %" PRIu64 " - response path %zu topic '" PRInSTR "'",
1948 (void *)client,
1949 operation->id,
1950 i,
1951 AWS_BYTE_CURSOR_PRI(response_path->topic));
1952
1953 AWS_LOGUF(
1954 log_handle,
1955 AWS_LL_DEBUG,
1956 AWS_LS_MQTT_REQUEST_RESPONSE,
1957 "id=%p: request-response client operation %" PRIu64 " - response path %zu correlation token path '" PRInSTR
1958 "'",
1959 (void *)client,
1960 operation->id,
1961 i,
1962 AWS_BYTE_CURSOR_PRI(response_path->correlation_token_json_path));
1963 }
1964 }
1965
1966 int aws_mqtt_request_response_client_submit_request(
1967 struct aws_mqtt_request_response_client *client,
1968 const struct aws_mqtt_request_operation_options *request_options) {
1969
1970 if (client == NULL) {
1971 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1972 }
1973
1974 if (!s_are_request_operation_options_valid(client, request_options)) {
1975 /* all failure cases have logged the problem already */
1976 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1977 }
1978
1979 uint64_t now = 0;
1980 if (aws_high_res_clock_get_ticks(&now)) {
1981 return aws_raise_error(AWS_ERROR_CLOCK_FAILURE);
1982 }
1983
1984 struct aws_allocator *allocator = client->allocator;
1985 struct aws_mqtt_rr_client_operation *operation =
1986 aws_mem_calloc(allocator, 1, sizeof(struct aws_mqtt_rr_client_operation));
1987 operation->allocator = allocator;
1988 operation->type = AWS_MRROT_REQUEST;
1989 operation->timeout_timepoint_ns =
1990 now +
1991 aws_timestamp_convert(client->config.operation_timeout_seconds, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL);
1992 operation->pending_subscriptions = request_options->subscription_topic_filter_count;
1993
1994 s_aws_mqtt_request_operation_storage_init_from_options(
1995 &operation->storage.request_storage, allocator, request_options);
1996 s_aws_mqtt_rr_client_operation_init_shared(operation, client);
1997
1998 AWS_LOGF_INFO(
1999 AWS_LS_MQTT_REQUEST_RESPONSE,
2000 "id=%p: request-response client - submitting request-response operation with id %" PRIu64,
2001 (void *)client,
2002 operation->id);
2003
2004 s_log_request_response_operation(operation, client);
2005
2006 /*
2007 * We hold a second reference to the operation during submission. This ensures that even if a streaming operation
2008 * is immediately dec-refed by the creator (before submission runs), the operation will not get destroyed.
2009 */
2010 aws_mqtt_rr_client_operation_acquire(operation);
2011
2012 aws_event_loop_schedule_task_now(client->loop, &operation->submit_task);
2013
2014 return AWS_OP_SUCCESS;
2015 }
2016
2017 void s_aws_mqtt_streaming_operation_storage_init_from_options(
2018 struct aws_mqtt_streaming_operation_storage *storage,
2019 struct aws_allocator *allocator,
2020 const struct aws_mqtt_streaming_operation_options *streaming_options) {
2021 size_t bytes_needed = streaming_options->topic_filter.len;
2022
2023 storage->options = *streaming_options;
2024 aws_byte_buf_init(&storage->operation_data, allocator, bytes_needed);
2025
2026 AWS_FATAL_ASSERT(
2027 aws_byte_buf_append_and_update(&storage->operation_data, &storage->options.topic_filter) == AWS_OP_SUCCESS);
2028
2029 aws_atomic_init_int(&storage->activated, 0);
2030 }
2031
2032 static void s_log_streaming_operation(
2033 struct aws_mqtt_rr_client_operation *operation,
2034 struct aws_mqtt_request_response_client *client) {
2035 struct aws_logger *log_handle = aws_logger_get_conditional(AWS_LS_MQTT_REQUEST_RESPONSE, AWS_LL_DEBUG);
2036 if (log_handle == NULL) {
2037 return;
2038 }
2039
2040 struct aws_mqtt_streaming_operation_options *options = &operation->storage.streaming_storage.options;
2041
2042 AWS_LOGUF(
2043 log_handle,
2044 AWS_LL_DEBUG,
2045 AWS_LS_MQTT_REQUEST_RESPONSE,
2046 "id=%p: request-response client streaming operation %" PRIu64 ": topic filter: '" PRInSTR "'",
2047 (void *)client,
2048 operation->id,
2049 AWS_BYTE_CURSOR_PRI(options->topic_filter));
2050 }
2051
2052 struct aws_mqtt_rr_client_operation *aws_mqtt_request_response_client_create_streaming_operation(
2053 struct aws_mqtt_request_response_client *client,
2054 const struct aws_mqtt_streaming_operation_options *streaming_options) {
2055
2056 if (client == NULL) {
2057 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
2058 return NULL;
2059 }
2060
2061 if (!s_are_streaming_operation_options_valid(client, streaming_options)) {
2062 /* all failure cases have logged the problem already */
2063 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
2064 return NULL;
2065 }
2066
2067 struct aws_allocator *allocator = client->allocator;
2068 struct aws_mqtt_rr_client_operation *operation =
2069 aws_mem_calloc(allocator, 1, sizeof(struct aws_mqtt_rr_client_operation));
2070 operation->allocator = allocator;
2071 operation->type = AWS_MRROT_STREAMING;
2072 operation->timeout_timepoint_ns = UINT64_MAX;
2073 operation->pending_subscriptions = 1;
2074
2075 s_aws_mqtt_streaming_operation_storage_init_from_options(
2076 &operation->storage.streaming_storage, allocator, streaming_options);
2077 s_aws_mqtt_rr_client_operation_init_shared(operation, client);
2078
2079 AWS_LOGF_INFO(
2080 AWS_LS_MQTT_REQUEST_RESPONSE,
2081 "id=%p: request-response client - submitting streaming operation with id %" PRIu64,
2082 (void *)client,
2083 operation->id);
2084
2085 s_log_streaming_operation(operation, client);
2086
2087 return operation;
2088 }
2089
2090 int aws_mqtt_rr_client_operation_activate(struct aws_mqtt_rr_client_operation *operation) {
2091 struct aws_atomic_var *activated = &operation->storage.streaming_storage.activated;
2092 size_t unactivated = 0;
2093 if (!aws_atomic_compare_exchange_int(activated, &unactivated, 1)) {
2094 return aws_raise_error(AWS_ERROR_MQTT_REUQEST_RESPONSE_STREAM_ALREADY_ACTIVATED);
2095 }
2096
2097 struct aws_mqtt_request_response_client *rr_client = operation->client_internal_ref;
2098
2099 AWS_LOGF_DEBUG(
2100 AWS_LS_MQTT_REQUEST_RESPONSE,
2101 "id=%p: request-response client - activating streaming operation with id %" PRIu64,
2102 (void *)rr_client,
2103 operation->id);
2104
2105 /*
2106 * We hold a second reference to the operation during submission. This ensures that even if a streaming operation
2107 * is immediately dec-refed by the creator (before submission runs), the operation will not get destroyed.
2108 */
2109 aws_mqtt_rr_client_operation_acquire(operation);
2110
2111 aws_event_loop_schedule_task_now(rr_client->loop, &operation->submit_task);
2112
2113 return AWS_OP_SUCCESS;
2114 }
2115
2116 struct aws_mqtt_rr_client_operation *aws_mqtt_rr_client_operation_acquire(
2117 struct aws_mqtt_rr_client_operation *operation) {
2118 if (operation != NULL) {
2119 aws_ref_count_acquire(&operation->ref_count);
2120 }
2121
2122 return operation;
2123 }
2124
2125 struct aws_mqtt_rr_client_operation *aws_mqtt_rr_client_operation_release(
2126 struct aws_mqtt_rr_client_operation *operation) {
2127 if (operation != NULL) {
2128 aws_ref_count_release(&operation->ref_count);
2129 }
2130
2131 return NULL;
2132 }
2133
2134 struct aws_event_loop *aws_mqtt_request_response_client_get_event_loop(
2135 struct aws_mqtt_request_response_client *client) {
2136
2137 return aws_mqtt_protocol_adapter_get_event_loop(client->client_adapter);
2138 }