Debian Codegraph @

crt/aws-c-event-stream/source/event_stream_rpc_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/event-stream/event_stream_rpc_client.h>
7
8 #include <aws/common/atomics.h>
9 #include <aws/common/hash_table.h>
10 #include <aws/common/mutex.h>
11 #include <aws/event-stream/event_stream_channel_handler.h>
12 #include <aws/event-stream/private/event_stream_rpc_priv.h>
13 #include <aws/io/channel_bootstrap.h>
14 #include <aws/io/event_loop.h>
15
16 #include <inttypes.h>
17
18 #ifdef _MSC_VER
19 /* allow declared initializer using address of automatic variable */
20 # pragma warning(disable : 4221)
21 /* allow non-constant aggregate initializers */
22 # pragma warning(disable : 4204)
23
24 #endif
25
26 static void s_clear_continuation_table(struct aws_event_stream_rpc_client_connection *connection);
27
28 struct aws_event_stream_rpc_client_connection {
29 /* const-at-creation data */
30 struct aws_allocator *allocator;
31 struct aws_client_bootstrap *bootstrap_ref;
32 struct aws_event_loop *event_loop;
33 aws_event_stream_rpc_client_on_connection_setup_fn *on_connection_setup;
34 aws_event_stream_rpc_client_connection_protocol_message_fn *on_connection_protocol_message;
35 aws_event_stream_rpc_client_on_connection_shutdown_fn *on_connection_shutdown;
36 aws_event_stream_rpc_client_on_connection_terminated_fn *on_connection_terminated;
37 void *user_data;
38
39 /* independent */
40 struct aws_atomic_var ref_count;
41
42 /* private to event loop thread. unsafe to access otherwise. */
43 struct aws_channel *channel;
44 struct aws_channel_handler *event_stream_handler;
45 bool bootstrap_owned;
46
47 /* lock and synchronized data */
48 struct aws_mutex lock;
49 struct {
50 struct aws_hash_table continuation_table;
51 uint32_t latest_stream_id;
52 bool is_open;
53 enum aws_event_stream_connection_handshake_state handshake_state;
54 } synced_data;
55 };
56
57 struct aws_event_stream_rpc_client_continuation_token {
58 uint32_t stream_id;
59 struct aws_event_stream_rpc_client_connection *connection;
60 aws_event_stream_rpc_client_stream_continuation_fn *continuation_fn;
61 aws_event_stream_rpc_client_stream_continuation_closed_fn *closed_fn;
62 aws_event_stream_rpc_client_stream_continuation_terminated_fn *terminated_fn;
63 void *user_data;
64 struct aws_atomic_var ref_count;
65 struct aws_atomic_var is_closed;
66 struct aws_atomic_var is_complete;
67 };
68
69 static void s_on_message_received(struct aws_event_stream_message *message, int error_code, void *user_data);
70
71 static int s_create_connection_on_channel(
72 struct aws_event_stream_rpc_client_connection *connection,
73 struct aws_channel *channel) {
74
75 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(connection->event_loop));
76
77 struct aws_channel_handler *event_stream_handler = NULL;
78 struct aws_channel_slot *slot = NULL;
79
80 struct aws_event_stream_channel_handler_options handler_options = {
81 .on_message_received = s_on_message_received,
82 .user_data = connection,
83 .initial_window_size = 0,
84 .manual_window_management = false,
85 };
86
87 AWS_LOGF_TRACE(
88 AWS_LS_EVENT_STREAM_RPC_CLIENT,
89 "id=%p: creating an event-stream handler on channel %p",
90 (void *)connection,
91 (void *)channel);
92 event_stream_handler = aws_event_stream_channel_handler_new(connection->allocator, &handler_options);
93
94 if (!event_stream_handler) {
95 AWS_LOGF_ERROR(
96 AWS_LS_EVENT_STREAM_RPC_CLIENT,
97 "id=%p: creating an event-stream handler failed with error %s",
98 (void *)connection,
99 aws_error_debug_str(aws_last_error()));
100 goto error;
101 }
102
103 slot = aws_channel_slot_new(channel);
104
105 if (!slot) {
106 AWS_LOGF_ERROR(
107 AWS_LS_EVENT_STREAM_RPC_CLIENT,
108 "id=%p: creating channel slot failed with error %s",
109 (void *)connection,
110 aws_error_debug_str(aws_last_error()));
111 goto error;
112 }
113
114 aws_channel_slot_insert_end(channel, slot);
115 if (aws_channel_slot_set_handler(slot, event_stream_handler)) {
116 AWS_LOGF_ERROR(
117 AWS_LS_EVENT_STREAM_RPC_CLIENT,
118 "id=%p: setting handler on channel slot failed with error %s",
119 (void *)connection,
120 aws_error_debug_str(aws_last_error()));
121 goto error;
122 }
123
124 connection->event_stream_handler = event_stream_handler;
125 connection->channel = channel;
126 aws_channel_acquire_hold(channel);
127
128 return AWS_OP_SUCCESS;
129
130 error:
131 if (!slot && event_stream_handler) {
132 aws_channel_handler_destroy(event_stream_handler);
133 }
134
135 return AWS_OP_ERR;
136 }
137
138 static void s_on_channel_setup_fn(
139 struct aws_client_bootstrap *bootstrap,
140 int error_code,
141 struct aws_channel *channel,
142 void *user_data) {
143 (void)bootstrap;
144
145 struct aws_event_stream_rpc_client_connection *connection = user_data;
146 AWS_LOGF_DEBUG(
147 AWS_LS_EVENT_STREAM_RPC_CLIENT,
148 "id=%p: on_channel_setup_fn invoked with error_code %d with channel %p",
149 (void *)connection,
150 error_code,
151 (void *)channel);
152
153 if (!error_code) {
154 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(connection->event_loop));
155 connection->bootstrap_owned = true;
156
157 if (s_create_connection_on_channel(connection, channel)) {
158 int last_error = aws_last_error();
159 connection->on_connection_setup(NULL, last_error, connection->user_data);
160
161 /* we have to shut down the successfully-created channel, so we don't want to release the connection yet */
162 aws_channel_shutdown(channel, last_error);
163 return;
164 }
165
166 AWS_LOGF_DEBUG(
167 AWS_LS_EVENT_STREAM_RPC_CLIENT,
168 "id=%p: successful event-stream channel setup %p",
169 (void *)connection,
170 (void *)channel);
171
172 /* keep the connection alive past this function */
173 aws_event_stream_rpc_client_connection_acquire(connection);
174 connection->on_connection_setup(connection, AWS_OP_SUCCESS, connection->user_data);
175 } else {
176 connection->on_connection_setup(NULL, error_code, connection->user_data);
177 }
178
179 /*
180 * 2 -> 1 on a successful connection, 1 -> 0 on a failed one
181 *
182 * Note that the 1 ref is the channel's hold on the connection. The user is required to acquire the connection
183 * in the setup callback to avoid early destruction.
184 *
185 * A corollary of this is that if you release the connection without calling close first, it will stay alive and
186 * leak.
187 */
188 aws_event_stream_rpc_client_connection_release(connection);
189 }
190
191 static void s_on_channel_shutdown_fn(
192 struct aws_client_bootstrap *bootstrap,
193 int error_code,
194 struct aws_channel *channel,
195 void *user_data) {
196 (void)bootstrap;
197
198 struct aws_event_stream_rpc_client_connection *connection = user_data;
199 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(connection->event_loop));
200
201 AWS_LOGF_DEBUG(
202 AWS_LS_EVENT_STREAM_RPC_CLIENT,
203 "id=%p: on_channel_shutdown_fn invoked with error_code %d with channel %p",
204 (void *)connection,
205 error_code,
206 (void *)channel);
207
208 aws_mutex_lock(&connection->lock);
209 connection->synced_data.is_open = false;
210 aws_mutex_unlock(&connection->lock);
211
212 bool is_externally_visible_shutdown = connection->bootstrap_owned;
213 connection->channel = NULL;
214 connection->event_stream_handler = NULL;
215
216 if (is_externally_visible_shutdown) {
217 s_clear_continuation_table(connection);
218
219 aws_event_stream_rpc_client_connection_acquire(connection);
220 connection->on_connection_shutdown(connection, error_code, connection->user_data);
221 aws_event_stream_rpc_client_connection_release(connection);
222 }
223
224 aws_channel_release_hold(channel);
225 aws_event_stream_rpc_client_connection_release(connection);
226 }
227
228 /* Set each continuation's is_closed=true. */
229 static int s_mark_each_continuation_closed(void *context, struct aws_hash_element *p_element) {
230 (void)context;
231 struct aws_event_stream_rpc_client_continuation_token *continuation = p_element->value;
232
233 aws_atomic_store_int(&continuation->is_closed, 1U);
234
235 return AWS_COMMON_HASH_TABLE_ITER_CONTINUE;
236 }
237
238 /* Invoke continuation's on_closed() callback.
239 * A lock must NOT be hold while calling this */
240 static void s_complete_continuation(struct aws_event_stream_rpc_client_continuation_token *token) {
241 size_t expect_not_complete = 0U;
242 if (aws_atomic_compare_exchange_int(&token->is_complete, &expect_not_complete, 1U)) {
243
244 AWS_LOGF_DEBUG(
245 AWS_LS_EVENT_STREAM_RPC_CLIENT,
246 "token=%p: completing continuation with stream-id %" PRIu32,
247 (void *)token,
248 token->stream_id);
249
250 if (token->stream_id) {
251 token->closed_fn(token, token->user_data);
252 }
253
254 aws_event_stream_rpc_client_continuation_release(token);
255 }
256 }
257
258 static int s_complete_and_clear_each_continuation(void *context, struct aws_hash_element *p_element) {
259 (void)context;
260 struct aws_event_stream_rpc_client_continuation_token *continuation = p_element->value;
261
262 s_complete_continuation(continuation);
263
264 return AWS_COMMON_HASH_TABLE_ITER_DELETE | AWS_COMMON_HASH_TABLE_ITER_CONTINUE;
265 }
266
267 /* Remove each continuation from hash-table and invoke its on_closed() callback.
268 * The connection->is_open must be set false before calling this. */
269 static void s_clear_continuation_table(struct aws_event_stream_rpc_client_connection *connection) {
270 AWS_ASSERT(!aws_event_stream_rpc_client_connection_is_open(connection));
271
272 struct aws_hash_table temp_table;
273 aws_hash_table_init(
274 &temp_table,
275 connection->allocator,
276 64,
277 aws_event_stream_rpc_hash_streamid,
278 aws_event_stream_rpc_streamid_eq,
279 NULL,
280 NULL);
281
282 /* Use lock to ensure synchronization with code that adds entries to table.
283 * Since connection was just marked closed, no further entries will be
284 * added to table once we acquire the lock.
285 *
286 * While no further entries can be added, there are concurrent execution paths where things can be
287 * removed. So rather than iterating the connection's table, swap it out for an empty one and iterate
288 * the temporary table instead. Removing from an empty table will be harmless.
289 */
290 aws_mutex_lock(&connection->lock);
291 aws_hash_table_swap(&temp_table, &connection->synced_data.continuation_table);
292 aws_mutex_unlock(&connection->lock);
293
294 aws_hash_table_foreach(&temp_table, s_mark_each_continuation_closed, NULL);
295 aws_hash_table_foreach(&temp_table, s_complete_and_clear_each_continuation, NULL);
296 aws_hash_table_clean_up(&temp_table);
297 }
298
299 int aws_event_stream_rpc_client_connection_connect(
300 struct aws_allocator *allocator,
301 const struct aws_event_stream_rpc_client_connection_options *conn_options) {
302 AWS_PRECONDITION(allocator);
303 AWS_PRECONDITION(conn_options);
304 AWS_PRECONDITION(conn_options->on_connection_protocol_message);
305 AWS_PRECONDITION(conn_options->on_connection_setup);
306 AWS_PRECONDITION(conn_options->on_connection_shutdown);
307
308 struct aws_event_stream_rpc_client_connection *connection =
309 aws_mem_calloc(allocator, 1, sizeof(struct aws_event_stream_rpc_client_connection));
310
311 AWS_LOGF_TRACE(AWS_LS_EVENT_STREAM_RPC_CLIENT, "id=%p: creating new connection", (void *)connection);
312
313 connection->allocator = allocator;
314 aws_atomic_init_int(&connection->ref_count, 1);
315 connection->bootstrap_ref = conn_options->bootstrap;
316 connection->event_loop = aws_event_loop_group_get_next_loop(connection->bootstrap_ref->event_loop_group);
317
318 /* this is released in the connection release which gets called regardless of if this function is successful or
319 * not*/
320 aws_client_bootstrap_acquire(connection->bootstrap_ref);
321 connection->synced_data.handshake_state = CONNECTION_HANDSHAKE_STATE_INITIALIZED;
322 connection->synced_data.is_open = true;
323 aws_mutex_init(&connection->lock);
324
325 connection->on_connection_shutdown = conn_options->on_connection_shutdown;
326 connection->on_connection_terminated = conn_options->on_connection_terminated;
327 connection->on_connection_protocol_message = conn_options->on_connection_protocol_message;
328 connection->on_connection_setup = conn_options->on_connection_setup;
329 connection->user_data = conn_options->user_data;
330
331 if (aws_hash_table_init(
332 &connection->synced_data.continuation_table,
333 allocator,
334 64,
335 aws_event_stream_rpc_hash_streamid,
336 aws_event_stream_rpc_streamid_eq,
337 NULL,
338 NULL)) {
339 AWS_LOGF_ERROR(
340 AWS_LS_EVENT_STREAM_RPC_CLIENT,
341 "id=%p: failed initializing continuation table with error %s.",
342 (void *)connection,
343 aws_error_debug_str(aws_last_error()));
344
345 goto error;
346 }
347
348 struct aws_socket_channel_bootstrap_options bootstrap_options = {
349 .bootstrap = connection->bootstrap_ref,
350 .tls_options = conn_options->tls_options,
351 .socket_options = conn_options->socket_options,
352 .user_data = connection,
353 .host_name = conn_options->host_name,
354 .port = conn_options->port,
355 .setup_callback = s_on_channel_setup_fn,
356 .shutdown_callback = s_on_channel_shutdown_fn,
357 .requested_event_loop = connection->event_loop,
358 };
359
360 if (aws_client_bootstrap_new_socket_channel(&bootstrap_options)) {
361 AWS_LOGF_ERROR(
362 AWS_LS_EVENT_STREAM_RPC_CLIENT,
363 "id=%p: failed creating new socket channel with error %s.",
364 (void *)connection,
365 aws_error_debug_str(aws_last_error()));
366 goto error;
367 }
368
369 return AWS_OP_SUCCESS;
370
371 error:
372 aws_event_stream_rpc_client_connection_release(connection);
373 return AWS_OP_ERR;
374 }
375
376 void aws_event_stream_rpc_client_connection_acquire(const struct aws_event_stream_rpc_client_connection *connection) {
377 AWS_PRECONDITION(connection);
378 size_t current_count = aws_atomic_fetch_add_explicit(
379 &((struct aws_event_stream_rpc_client_connection *)connection)->ref_count, 1, aws_memory_order_relaxed);
380 AWS_LOGF_TRACE(
381 AWS_LS_EVENT_STREAM_RPC_CLIENT,
382 "id=%p: connection acquired, new ref count is %zu.",
383 (void *)connection,
384 current_count + 1);
385 }
386
387 static void s_destroy_connection(struct aws_event_stream_rpc_client_connection *connection) {
388 AWS_LOGF_DEBUG(AWS_LS_EVENT_STREAM_RPC_CLIENT, "id=%p: destroying connection.", (void *)connection);
389 aws_hash_table_clean_up(&connection->synced_data.continuation_table);
390 aws_client_bootstrap_release(connection->bootstrap_ref);
391 aws_mutex_clean_up(&connection->lock);
392
393 aws_event_stream_rpc_client_on_connection_terminated_fn *terminated_fn = connection->on_connection_terminated;
394 void *terminated_user_data = connection->user_data;
395
396 aws_mem_release(connection->allocator, connection);
397
398 if (terminated_fn) {
399 terminated_fn(terminated_user_data);
400 }
401 }
402
403 void aws_event_stream_rpc_client_connection_release(const struct aws_event_stream_rpc_client_connection *connection) {
404 if (!connection) {
405 return;
406 }
407
408 struct aws_event_stream_rpc_client_connection *connection_mut =
409 (struct aws_event_stream_rpc_client_connection *)connection;
410 size_t ref_count = aws_atomic_fetch_sub_explicit(&connection_mut->ref_count, 1, aws_memory_order_seq_cst);
411
412 AWS_LOGF_TRACE(
413 AWS_LS_EVENT_STREAM_RPC_CLIENT,
414 "id=%p: connection released, new ref count is %zu.",
415 (void *)connection,
416 ref_count - 1);
417
418 AWS_FATAL_ASSERT(ref_count != 0 && "Connection ref count has gone negative");
419
420 if (ref_count == 1) {
421 s_destroy_connection(connection_mut);
422 }
423 }
424
425 struct aws_event_stream_client_connection_close_task {
426 struct aws_allocator *allocator;
427
428 struct aws_task base;
429 struct aws_event_stream_rpc_client_connection *connection;
430 int error_code;
431 };
432
433 static void s_aws_event_stream_client_connection_close_task_destroy(
434 struct aws_event_stream_client_connection_close_task *task) {
435 aws_event_stream_rpc_client_connection_release(task->connection);
436 aws_mem_release(task->allocator, task);
437 }
438
439 static void s_close_connection(struct aws_task *task, void *arg, enum aws_task_status status) {
440 (void)task;
441 (void)status;
442
443 struct aws_event_stream_client_connection_close_task *close_task = arg;
444
445 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(close_task->connection->event_loop));
446
447 if (close_task->connection->channel != NULL) {
448 aws_channel_shutdown(close_task->connection->channel, close_task->error_code);
449 }
450
451 s_aws_event_stream_client_connection_close_task_destroy(close_task);
452 }
453
454 static struct aws_event_stream_client_connection_close_task *s_aws_event_stream_client_connection_close_task_new(
455 struct aws_allocator *allocator,
456 struct aws_event_stream_rpc_client_connection *connection,
457 int error_code) {
458 struct aws_event_stream_client_connection_close_task *task =
459 aws_mem_calloc(allocator, 1, sizeof(struct aws_event_stream_client_connection_close_task));
460 task->allocator = allocator;
461 aws_task_init(&task->base, s_close_connection, task, "aws_event_stream_client_connection_close_task");
462 task->connection = connection;
463 task->error_code = error_code;
464 aws_event_stream_rpc_client_connection_acquire(connection);
465
466 return task;
467 }
468
469 void aws_event_stream_rpc_client_connection_close(
470 struct aws_event_stream_rpc_client_connection *connection,
471 int shutdown_error_code) {
472
473 AWS_LOGF_TRACE(
474 AWS_LS_EVENT_STREAM_RPC_CLIENT,
475 "id=%p: connection close invoked with reason %s.",
476 (void *)connection,
477 aws_error_debug_str(shutdown_error_code));
478
479 bool should_close = false;
480 aws_mutex_lock(&connection->lock);
481 should_close = connection->synced_data.is_open;
482 connection->synced_data.is_open = false;
483 aws_mutex_unlock(&connection->lock);
484
485 if (should_close) {
486 /* We may need to access the channel, which is only allowed on the event loop thread. */
487 struct aws_event_stream_client_connection_close_task *close_task =
488 s_aws_event_stream_client_connection_close_task_new(connection->allocator, connection, shutdown_error_code);
489 aws_event_loop_schedule_task_now(connection->event_loop, &close_task->base);
490 } else {
491 AWS_LOGF_INFO(AWS_LS_EVENT_STREAM_RPC_CLIENT, "id=%p: connection already closed.", (void *)connection);
492 }
493 }
494
495 bool aws_event_stream_rpc_client_connection_is_open(const struct aws_event_stream_rpc_client_connection *connection) {
496 struct aws_event_stream_rpc_client_connection *mutable_connection =
497 (struct aws_event_stream_rpc_client_connection *)connection;
498
499 bool is_open = false;
500 aws_mutex_lock(&mutable_connection->lock);
501 is_open = connection->synced_data.is_open;
502 aws_mutex_unlock(&mutable_connection->lock);
503
504 return is_open;
505 }
506
507 struct event_stream_connection_send_message_args {
508 struct aws_allocator *allocator;
509 struct aws_event_stream_message message;
510 enum aws_event_stream_rpc_message_type message_type;
511 struct aws_event_stream_rpc_client_connection *connection;
512 struct aws_event_stream_rpc_client_continuation_token *continuation;
513 aws_event_stream_rpc_client_message_flush_fn *flush_fn;
514 void *user_data;
515 bool end_stream;
516 bool terminate_connection;
517 };
518
519 static void s_event_stream_connection_send_message_args_delete(struct event_stream_connection_send_message_args *args) {
520 if (args == NULL) {
521 return;
522 }
523
524 if (args->continuation) {
525 aws_event_stream_rpc_client_continuation_release(args->continuation);
526 }
527
528 if (args->connection) {
529 aws_event_stream_rpc_client_connection_release(args->connection);
530 }
531
532 aws_event_stream_message_clean_up(&args->message);
533
534 aws_mem_release(args->allocator, args);
535 }
536
537 static struct event_stream_connection_send_message_args *s_event_stream_connection_send_message_args_new(
538 struct aws_event_stream_rpc_client_connection *connection,
539 struct aws_event_stream_rpc_client_continuation_token *continuation,
540 struct aws_byte_cursor *operation_name,
541 const struct aws_event_stream_rpc_message_args *message_args,
542 int32_t stream_id,
543 aws_event_stream_rpc_client_message_flush_fn *flush_fn,
544 void *user_data) {
545
546 struct aws_array_list headers_list;
547 AWS_ZERO_STRUCT(headers_list);
548
549 struct event_stream_connection_send_message_args *args =
550 aws_mem_calloc(connection->allocator, 1, sizeof(struct event_stream_connection_send_message_args));
551 args->allocator = connection->allocator;
552 args->user_data = user_data;
553 args->message_type = message_args->message_type;
554 args->connection = connection;
555 aws_event_stream_rpc_client_connection_acquire(connection);
556
557 args->flush_fn = flush_fn;
558
559 if (continuation) {
560 AWS_LOGF_TRACE(
561 AWS_LS_EVENT_STREAM_RPC_CLIENT,
562 "id=%p: creating message on continuation %p",
563 (void *)connection,
564 (void *)continuation);
565 args->continuation = continuation;
566 aws_event_stream_rpc_client_continuation_acquire(continuation);
567
568 if (message_args->message_flags & AWS_EVENT_STREAM_RPC_MESSAGE_FLAG_TERMINATE_STREAM) {
569 AWS_LOGF_DEBUG(
570 AWS_LS_EVENT_STREAM_RPC_CLIENT,
571 "id=%p:end stream flag was specified on continuation %p",
572 (void *)connection,
573 (void *)continuation);
574 args->end_stream = true;
575 }
576 }
577
578 if (message_args->message_type == AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_CONNECT_ACK &&
579 !(message_args->message_flags & AWS_EVENT_STREAM_RPC_MESSAGE_FLAG_CONNECTION_ACCEPTED)) {
580 AWS_LOGF_DEBUG(AWS_LS_EVENT_STREAM_RPC_CLIENT, "id=%p: terminating connection", (void *)connection);
581 args->terminate_connection = true;
582 }
583
584 args->flush_fn = flush_fn;
585
586 size_t headers_count = 0;
587
588 if (operation_name) {
589 if (aws_add_size_checked(message_args->headers_count, 4, &headers_count)) {
590 goto error;
591 }
592 } else {
593 if (aws_add_size_checked(message_args->headers_count, 3, &headers_count)) {
594 goto error;
595 }
596 }
597
598 aws_array_list_init_dynamic(
599 &headers_list, connection->allocator, headers_count, sizeof(struct aws_event_stream_header_value_pair));
600
601 /* since we preallocated the space for the headers, these can't fail, but we'll go ahead an assert on them just in
602 * case */
603 for (size_t i = 0; i < message_args->headers_count; ++i) {
604 AWS_FATAL_ASSERT(!aws_array_list_push_back(&headers_list, &message_args->headers[i]));
605 }
606
607 AWS_FATAL_ASSERT(!aws_event_stream_add_int32_header(
608 &headers_list,
609 (const char *)aws_event_stream_rpc_message_type_name.ptr,
610 (uint8_t)aws_event_stream_rpc_message_type_name.len,
611 message_args->message_type));
612 AWS_FATAL_ASSERT(!aws_event_stream_add_int32_header(
613 &headers_list,
614 (const char *)aws_event_stream_rpc_message_flags_name.ptr,
615 (uint8_t)aws_event_stream_rpc_message_flags_name.len,
616 message_args->message_flags));
617 AWS_FATAL_ASSERT(!aws_event_stream_add_int32_header(
618 &headers_list,
619 (const char *)aws_event_stream_rpc_stream_id_name.ptr,
620 (uint8_t)aws_event_stream_rpc_stream_id_name.len,
621 stream_id));
622
623 if (operation_name) {
624 AWS_LOGF_DEBUG(
625 AWS_LS_EVENT_STREAM_RPC_CLIENT,
626 "id=%p: operation name specified " PRInSTR,
627 (void *)connection,
628 AWS_BYTE_CURSOR_PRI(*operation_name));
629 AWS_FATAL_ASSERT(!aws_event_stream_add_string_header(
630 &headers_list,
631 (const char *)aws_event_stream_rpc_operation_name.ptr,
632 (uint8_t)aws_event_stream_rpc_operation_name.len,
633 (const char *)operation_name->ptr,
634 (uint16_t)operation_name->len,
635 0));
636 }
637
638 int init_result =
639 aws_event_stream_message_init(&args->message, connection->allocator, &headers_list, message_args->payload);
640 aws_array_list_clean_up(&headers_list);
641
642 if (init_result) {
643 AWS_LOGF_ERROR(
644 AWS_LS_EVENT_STREAM_RPC_CLIENT,
645 "id=%p: message init failed with error %s",
646 (void *)connection,
647 aws_error_debug_str(aws_last_error()));
648 goto error;
649 }
650
651 return args;
652
653 error:
654
655 s_event_stream_connection_send_message_args_delete(args);
656
657 return NULL;
658 }
659
660 struct aws_event_stream_client_connection_send_message_task {
661 struct aws_allocator *allocator;
662
663 struct aws_task base;
664 struct event_stream_connection_send_message_args *message_args;
665 };
666
667 static void s_aws_event_stream_client_connection_send_message_task_destroy(
668 struct aws_event_stream_client_connection_send_message_task *task) {
669
670 if (task->message_args != NULL) {
671 s_event_stream_connection_send_message_args_delete(task->message_args);
672 }
673
674 aws_mem_release(task->allocator, task);
675 }
676
677 static void s_on_protocol_message_written_fn(
678 struct aws_event_stream_message *message,
679 int error_code,
680 void *user_data) {
681 (void)message;
682
683 struct event_stream_connection_send_message_args *message_args = user_data;
684
685 if (message_args->message_type == AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_CONNECT) {
686 AWS_LOGF_DEBUG(
687 AWS_LS_EVENT_STREAM_RPC_CLIENT,
688 "id=%p: connect message flushed to the wire.",
689 (void *)message_args->connection);
690 } else {
691 AWS_LOGF_TRACE(
692 AWS_LS_EVENT_STREAM_RPC_CLIENT,
693 "id=%p: message %p flushed to channel.",
694 (void *)message_args->connection,
695 (void *)message);
696 }
697
698 if (message_args->end_stream) {
699 AWS_LOGF_DEBUG(
700 AWS_LS_EVENT_STREAM_RPC_CLIENT,
701 "id=%p: the end stream flag was set, closing continuation %p.",
702 (void *)message_args->connection,
703 (void *)message_args->continuation);
704 AWS_FATAL_ASSERT(message_args->continuation && "end stream flag was set but it wasn't on a continuation");
705 aws_atomic_store_int(&message_args->continuation->is_closed, 1U);
706
707 int was_present = 0;
708 aws_mutex_lock(&message_args->connection->lock);
709 aws_hash_table_remove(
710 &message_args->connection->synced_data.continuation_table,
711 &message_args->continuation->stream_id,
712 NULL,
713 &was_present);
714 aws_mutex_unlock(&message_args->connection->lock);
715
716 /*
717 * Whoever successfully removes the continuation from the table gets to complete it.
718 * Lock must NOT be held while invoking callback
719 */
720 if (was_present) {
721 s_complete_continuation(message_args->continuation);
722 }
723 }
724
725 message_args->flush_fn(error_code, message_args->user_data);
726
727 if (message_args->terminate_connection) {
728 AWS_LOGF_DEBUG(
729 AWS_LS_EVENT_STREAM_RPC_CLIENT,
730 "id=%p: terminate_connection flag was specified. Shutting down the connection.",
731 (void *)message_args->connection);
732 aws_event_stream_rpc_client_connection_close(message_args->connection, AWS_ERROR_SUCCESS);
733 }
734
735 s_event_stream_connection_send_message_args_delete(message_args);
736 }
737
738 static void s_send_message_task_fn(struct aws_task *task, void *arg, enum aws_task_status status) {
739 (void)task;
740
741 struct aws_event_stream_client_connection_send_message_task *send_task = arg;
742 struct event_stream_connection_send_message_args *message_args = send_task->message_args;
743 struct aws_event_stream_rpc_client_connection *connection = message_args->connection;
744 enum aws_event_stream_rpc_message_type message_type = message_args->message_type;
745
746 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(message_args->connection->event_loop));
747
748 int failure_error_code = AWS_ERROR_UNKNOWN;
749 bool should_fail = true;
750 if (status == AWS_TASK_STATUS_RUN_READY) {
751 bool is_open = false;
752 bool is_handshake_state_valid = false;
753 aws_mutex_lock(&connection->lock);
754
755 is_open = connection->synced_data.is_open;
756 switch (connection->synced_data.handshake_state) {
757 case CONNECTION_HANDSHAKE_STATE_INITIALIZED:
758 is_handshake_state_valid = message_type == AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_CONNECT;
759 if (is_handshake_state_valid) {
760 connection->synced_data.handshake_state = CONNECTION_HANDSHAKE_STATE_CONNECT_PROCESSED;
761 }
762 break;
763
764 case CONNECTION_HANDSHAKE_STATE_CONNECT_ACK_PROCESSED:
765 is_handshake_state_valid = message_type != AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_CONNECT &&
766 message_type != AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_CONNECT_ACK;
767 break;
768
769 default:
770 // nothing is valid to send while awaiting the connack
771 break;
772 }
773
774 aws_mutex_unlock(&connection->lock);
775
776 if (!is_open) {
777 AWS_LOGF_INFO(
778 AWS_LS_EVENT_STREAM_RPC_CLIENT, "id=%p: connection closed, cannot send messages", (void *)connection);
779 failure_error_code = AWS_ERROR_EVENT_STREAM_RPC_CONNECTION_CLOSED;
780 goto should_fail_block;
781 }
782
783 if (connection->channel == NULL || connection->event_stream_handler == NULL) {
784 AWS_LOGF_INFO(
785 AWS_LS_EVENT_STREAM_RPC_CLIENT, "id=%p: channel destroyed, cannot send messages", (void *)connection);
786 failure_error_code = AWS_ERROR_EVENT_STREAM_RPC_CONNECTION_CLOSED;
787 goto should_fail_block;
788 }
789
790 if (!is_handshake_state_valid) {
791 AWS_LOGF_ERROR(
792 AWS_LS_EVENT_STREAM_RPC_CLIENT,
793 "id=%p: invalid handshake state for message type (%d)",
794 (void *)connection,
795 (int)message_args->message_type);
796 failure_error_code = AWS_ERROR_EVENT_STREAM_RPC_PROTOCOL_ERROR;
797 goto should_fail_block;
798 }
799
800 if (message_args->continuation != NULL) {
801 if (aws_event_stream_rpc_client_continuation_is_closed(message_args->continuation)) {
802 AWS_LOGF_INFO(
803 AWS_LS_EVENT_STREAM_RPC_CLIENT,
804 "id=%p: continuation closed, cannot send messages",
805 (void *)message_args->continuation);
806
807 failure_error_code = AWS_ERROR_EVENT_STREAM_RPC_STREAM_CLOSED;
808 goto should_fail_block;
809 }
810 }
811
812 should_fail = false;
813 }
814
815 if (!should_fail) {
816 if (aws_event_stream_channel_handler_write_message(
817 connection->event_stream_handler,
818 &message_args->message,
819 s_on_protocol_message_written_fn,
820 message_args)) {
821 failure_error_code = aws_last_error();
822 should_fail = true;
823 AWS_LOGF_ERROR(
824 AWS_LS_EVENT_STREAM_RPC_CLIENT,
825 "id=%p: writing message failed with error %s",
826 (void *)connection,
827 aws_error_debug_str(failure_error_code));
828 } else {
829 /* ownership transfer to flush callback, so don't destroy on task destruction */
830 send_task->message_args = NULL;
831 }
832 }
833
834 should_fail_block:
835
836 if (should_fail) {
837 AWS_FATAL_ASSERT(send_task->message_args != NULL);
838
839 /*
840 * We didn't transfer ownership of the message args to the flush callback via a successful handler send
841 * call. We must invoke a failed callback.
842 */
843 if (message_args->flush_fn != NULL) {
844 (*message_args->flush_fn)(failure_error_code, message_args->user_data);
845 }
846
847 /* Fail-to-send a non-application message is connection fatal */
848 if (connection->channel != NULL &&
849 message_args->message_type != AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_APPLICATION_MESSAGE &&
850 message_args->message_type != AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_APPLICATION_ERROR) {
851 aws_channel_shutdown(connection->channel, failure_error_code);
852 }
853 }
854
855 s_aws_event_stream_client_connection_send_message_task_destroy(send_task);
856 }
857
858 static struct aws_event_stream_client_connection_send_message_task *
859 s_aws_event_stream_client_connection_send_message_task_new(
860 struct aws_allocator *allocator,
861 struct event_stream_connection_send_message_args *message_args) {
862 struct aws_event_stream_client_connection_send_message_task *task =
863 aws_mem_calloc(allocator, 1, sizeof(struct aws_event_stream_client_connection_send_message_task));
864 task->allocator = allocator;
865 aws_task_init(&task->base, s_send_message_task_fn, task, "aws_event_stream_client_connection_send_message_task");
866 task->message_args = message_args;
867
868 return task;
869 }
870
871 static int s_send_protocol_message(
872 struct aws_event_stream_rpc_client_connection *connection,
873 struct aws_event_stream_rpc_client_continuation_token *continuation,
874 struct aws_byte_cursor *operation_name,
875 const struct aws_event_stream_rpc_message_args *message_args,
876 int32_t stream_id,
877 aws_event_stream_rpc_client_message_flush_fn *flush_fn,
878 void *user_data) {
879
880 AWS_LOGF_TRACE(AWS_LS_EVENT_STREAM_RPC_CLIENT, "id=%p: attempting to send protocol message", (void *)connection);
881
882 struct event_stream_connection_send_message_args *args = s_event_stream_connection_send_message_args_new(
883 connection, continuation, operation_name, message_args, stream_id, flush_fn, user_data);
884 if (args == NULL) {
885 return AWS_OP_ERR;
886 }
887
888 struct aws_event_stream_client_connection_send_message_task *task =
889 s_aws_event_stream_client_connection_send_message_task_new(connection->allocator, args);
890 aws_event_loop_schedule_task_now_serialized(connection->event_loop, &task->base);
891
892 return AWS_OP_SUCCESS;
893 }
894
895 int aws_event_stream_rpc_client_connection_send_protocol_message(
896 struct aws_event_stream_rpc_client_connection *connection,
897 const struct aws_event_stream_rpc_message_args *message_args,
898 aws_event_stream_rpc_client_message_flush_fn *flush_fn,
899 void *user_data) {
900
901 return s_send_protocol_message(connection, NULL, NULL, message_args, 0, flush_fn, user_data);
902 }
903
904 static void s_connection_error_message_flush_fn(int error_code, void *user_data) {
905 (void)error_code;
906
907 struct aws_event_stream_rpc_client_connection *connection = user_data;
908 aws_event_stream_rpc_client_connection_close(connection, AWS_ERROR_EVENT_STREAM_RPC_PROTOCOL_ERROR);
909 }
910
911 static void s_send_connection_level_error(
912 struct aws_event_stream_rpc_client_connection *connection,
913 uint32_t message_type,
914 uint32_t message_flags,
915 const struct aws_byte_cursor *message) {
916 struct aws_byte_buf payload_buf = aws_byte_buf_from_array(message->ptr, message->len);
917
918 AWS_LOGF_DEBUG(
919 AWS_LS_EVENT_STREAM_RPC_CLIENT,
920 "id=%p: sending connection-level error\n" PRInSTR,
921 (void *)connection,
922 AWS_BYTE_BUF_PRI(payload_buf));
923
924 struct aws_event_stream_header_value_pair content_type_header =
925 aws_event_stream_create_string_header(s_json_content_type_name, s_json_content_type_value);
926
927 struct aws_event_stream_header_value_pair headers[] = {
928 content_type_header,
929 };
930
931 struct aws_event_stream_rpc_message_args message_args = {
932 .message_type = message_type,
933 .message_flags = message_flags,
934 .payload = &payload_buf,
935 .headers_count = 1,
936 .headers = headers,
937 };
938
939 aws_event_stream_rpc_client_connection_send_protocol_message(
940 connection, &message_args, s_connection_error_message_flush_fn, connection);
941 }
942
943 static void s_route_message_by_type(
944 struct aws_event_stream_rpc_client_connection *connection,
945 struct aws_event_stream_message *message,
946 struct aws_array_list *headers_list,
947 uint32_t stream_id,
948 uint32_t message_type,
949 uint32_t message_flags) {
950 struct aws_byte_buf payload_buf = aws_byte_buf_from_array(
951 aws_event_stream_message_payload(message), aws_event_stream_message_payload_len(message));
952
953 struct aws_event_stream_rpc_message_args message_args = {
954 .headers = headers_list->data,
955 .headers_count = aws_array_list_length(headers_list),
956 .payload = &payload_buf,
957 .message_flags = message_flags,
958 .message_type = message_type,
959 };
960
961 aws_mutex_lock(&connection->lock);
962 enum aws_event_stream_connection_handshake_state handshake_state = connection->synced_data.handshake_state;
963 aws_mutex_unlock(&connection->lock);
964
965 /* make sure if this is not a CONNECT message being received, the handshake has been completed. */
966 if (handshake_state < CONNECTION_HANDSHAKE_STATE_CONNECT_ACK_PROCESSED &&
967 message_type != AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_CONNECT_ACK) {
968 AWS_LOGF_ERROR(
969 AWS_LS_EVENT_STREAM_RPC_CLIENT,
970 "id=%p: a message was received on this connection prior to the "
971 "connect handshake completing",
972 (void *)connection);
973 aws_raise_error(AWS_ERROR_EVENT_STREAM_RPC_PROTOCOL_ERROR);
974 s_send_connection_level_error(
975 connection, AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_PROTOCOL_ERROR, 0, &s_connect_not_completed_error);
976 return;
977 }
978
979 /* stream_id being non zero ALWAYS indicates APPLICATION_DATA or APPLICATION_ERROR. */
980 if (stream_id > 0) {
981 AWS_LOGF_TRACE(AWS_LS_EVENT_STREAM_RPC_CLIENT, "id=%p: stream id %" PRIu32, (void *)connection, stream_id);
982 struct aws_event_stream_rpc_client_continuation_token *continuation = NULL;
983 if (message_type > AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_APPLICATION_ERROR) {
984 AWS_LOGF_ERROR(
985 AWS_LS_EVENT_STREAM_RPC_CLIENT,
986 "id=%p: only application messages can be sent on a stream id, "
987 "but this message is the incorrect type",
988 (void *)connection);
989 aws_raise_error(AWS_ERROR_EVENT_STREAM_RPC_PROTOCOL_ERROR);
990 s_send_connection_level_error(
991 connection, AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_PROTOCOL_ERROR, 0, &s_invalid_stream_id_error);
992 return;
993 }
994
995 aws_mutex_lock(&connection->lock);
996 struct aws_hash_element *continuation_element = NULL;
997 if (aws_hash_table_find(&connection->synced_data.continuation_table, &stream_id, &continuation_element) ||
998 !continuation_element) {
999 bool old_stream_id = stream_id <= connection->synced_data.latest_stream_id;
1000 aws_mutex_unlock(&connection->lock);
1001 if (!old_stream_id) {
1002 AWS_LOGF_ERROR(
1003 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1004 "id=%p: a stream id was received that was not created by this client",
1005 (void *)connection);
1006 aws_raise_error(AWS_ERROR_EVENT_STREAM_RPC_PROTOCOL_ERROR);
1007 s_send_connection_level_error(
1008 connection, AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_PROTOCOL_ERROR, 0, &s_invalid_client_stream_id_error);
1009 } else {
1010 AWS_LOGF_WARN(
1011 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1012 "id=%p: a stream id was received that corresponds to an already-closed stream",
1013 (void *)connection);
1014 }
1015 return;
1016 }
1017
1018 continuation = continuation_element->value;
1019 AWS_FATAL_ASSERT(continuation != NULL);
1020 aws_event_stream_rpc_client_continuation_acquire(continuation);
1021
1022 aws_mutex_unlock(&connection->lock);
1023
1024 if (message_flags & AWS_EVENT_STREAM_RPC_MESSAGE_FLAG_TERMINATE_STREAM) {
1025 AWS_LOGF_DEBUG(
1026 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1027 "id=%p: the terminate stream flag was specified for continuation %p",
1028 (void *)connection,
1029 (void *)continuation);
1030 aws_atomic_store_int(&continuation->is_closed, 1U);
1031 }
1032
1033 continuation->continuation_fn(continuation, &message_args, continuation->user_data);
1034
1035 /* if it was a terminal stream message purge it from the hash table. The delete will decref the continuation. */
1036 if (message_flags & AWS_EVENT_STREAM_RPC_MESSAGE_FLAG_TERMINATE_STREAM) {
1037 int was_present = 0;
1038 aws_mutex_lock(&connection->lock);
1039 aws_hash_table_remove(&connection->synced_data.continuation_table, &stream_id, NULL, &was_present);
1040 aws_mutex_unlock(&connection->lock);
1041
1042 /*
1043 * Whoever successfully removes the continuation from the table gets to complete it.
1044 * Lock must NOT be held while invoking callback
1045 */
1046 if (was_present) {
1047 s_complete_continuation(continuation);
1048 }
1049 }
1050
1051 aws_event_stream_rpc_client_continuation_release(continuation);
1052 } else {
1053 if (message_type <= AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_APPLICATION_ERROR ||
1054 message_type >= AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_COUNT) {
1055 AWS_LOGF_ERROR(
1056 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1057 "id=%p: a zero stream id was received with an invalid message-type %" PRIu32,
1058 (void *)connection,
1059 message_type);
1060 s_send_connection_level_error(
1061 connection, AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_PROTOCOL_ERROR, 0, &s_invalid_message_type_error);
1062 return;
1063 }
1064
1065 if (message_type == AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_CONNECT_ACK) {
1066 aws_mutex_lock(&connection->lock);
1067 bool bad_handshake_state =
1068 connection->synced_data.handshake_state != CONNECTION_HANDSHAKE_STATE_CONNECT_PROCESSED;
1069 if (!bad_handshake_state) {
1070 connection->synced_data.handshake_state = CONNECTION_HANDSHAKE_STATE_CONNECT_ACK_PROCESSED;
1071 }
1072 aws_mutex_unlock(&connection->lock);
1073
1074 if (bad_handshake_state) {
1075 AWS_LOGF_ERROR(
1076 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1077 "id=%p: connect ack received but the handshake is already completed. Only one is allowed.",
1078 (void *)connection);
1079 /* only one connect is allowed. This would be a duplicate. */
1080 s_send_connection_level_error(
1081 connection, AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_PROTOCOL_ERROR, 0, &s_connect_not_completed_error);
1082 return;
1083 }
1084
1085 AWS_LOGF_INFO(
1086 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1087 "id=%p: connect ack received, connection handshake completed",
1088 (void *)connection);
1089 }
1090
1091 connection->on_connection_protocol_message(connection, &message_args, connection->user_data);
1092 }
1093 }
1094
1095 /* invoked by the event stream channel handler when a complete message has been read from the channel. */
1096 static void s_on_message_received(struct aws_event_stream_message *message, int error_code, void *user_data) {
1097
1098 if (!error_code) {
1099 struct aws_event_stream_rpc_client_connection *connection = user_data;
1100
1101 AWS_LOGF_TRACE(
1102 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1103 "id=%p: message received on connection of length %" PRIu32,
1104 (void *)connection,
1105 aws_event_stream_message_total_length(message));
1106
1107 struct aws_array_list headers;
1108 if (aws_array_list_init_dynamic(
1109 &headers, connection->allocator, 8, sizeof(struct aws_event_stream_header_value_pair))) {
1110 AWS_LOGF_ERROR(
1111 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1112 "id=%p: error initializing headers %s",
1113 (void *)connection,
1114 aws_error_debug_str(aws_last_error()));
1115 s_send_connection_level_error(
1116 connection, AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_INTERNAL_ERROR, 0, &s_internal_error);
1117 return;
1118 }
1119
1120 if (aws_event_stream_message_headers(message, &headers)) {
1121 AWS_LOGF_ERROR(
1122 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1123 "id=%p: error fetching headers %s",
1124 (void *)connection,
1125 aws_error_debug_str(aws_last_error()));
1126 s_send_connection_level_error(
1127 connection, AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_INTERNAL_ERROR, 0, &s_internal_error);
1128 goto clean_up;
1129 }
1130
1131 int32_t stream_id = -1;
1132 int32_t message_type = -1;
1133 int32_t message_flags = -1;
1134
1135 struct aws_byte_buf operation_name_buf;
1136 AWS_ZERO_STRUCT(operation_name_buf);
1137 if (aws_event_stream_rpc_extract_message_metadata(
1138 &headers, &stream_id, &message_type, &message_flags, &operation_name_buf)) {
1139 AWS_LOGF_ERROR(
1140 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1141 "id=%p: invalid protocol message with error %s",
1142 (void *)connection,
1143 aws_error_debug_str(aws_last_error()));
1144 s_send_connection_level_error(
1145 connection, AWS_EVENT_STREAM_RPC_MESSAGE_TYPE_PROTOCOL_ERROR, 0, &s_invalid_message_error);
1146 goto clean_up;
1147 }
1148
1149 (void)operation_name_buf;
1150
1151 AWS_LOGF_TRACE(AWS_LS_EVENT_STREAM_RPC_CLIENT, "id=%p: routing message", (void *)connection);
1152 s_route_message_by_type(connection, message, &headers, stream_id, message_type, message_flags);
1153
1154 clean_up:
1155 aws_event_stream_headers_list_cleanup(&headers);
1156 }
1157 }
1158
1159 struct aws_event_stream_rpc_client_continuation_token *aws_event_stream_rpc_client_connection_new_stream(
1160 struct aws_event_stream_rpc_client_connection *connection,
1161 const struct aws_event_stream_rpc_client_stream_continuation_options *continuation_options) {
1162 AWS_PRECONDITION(continuation_options->on_continuation_closed);
1163 AWS_PRECONDITION(continuation_options->on_continuation);
1164
1165 AWS_LOGF_TRACE(AWS_LS_EVENT_STREAM_RPC_CLIENT, "id=%p: creating a new stream on connection", (void *)connection);
1166
1167 struct aws_event_stream_rpc_client_continuation_token *continuation =
1168 aws_mem_calloc(connection->allocator, 1, sizeof(struct aws_event_stream_rpc_client_continuation_token));
1169
1170 if (!continuation) {
1171 AWS_LOGF_ERROR(
1172 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1173 "id=%p: error while allocating continuation %s",
1174 (void *)connection,
1175 aws_error_debug_str(aws_last_error()));
1176 return NULL;
1177 }
1178
1179 AWS_LOGF_DEBUG(
1180 AWS_LS_EVENT_STREAM_RPC_CLIENT, "id=%p: continuation created %p", (void *)connection, (void *)continuation);
1181 continuation->connection = connection;
1182 aws_event_stream_rpc_client_connection_acquire(continuation->connection);
1183 aws_atomic_init_int(&continuation->ref_count, 1);
1184 aws_atomic_init_int(&continuation->is_closed, 0);
1185 aws_atomic_init_int(&continuation->is_complete, 0);
1186 continuation->continuation_fn = continuation_options->on_continuation;
1187 continuation->closed_fn = continuation_options->on_continuation_closed;
1188 continuation->terminated_fn = continuation_options->on_continuation_terminated;
1189 continuation->user_data = continuation_options->user_data;
1190
1191 return continuation;
1192 }
1193
1194 void *aws_event_stream_rpc_client_continuation_get_user_data(
1195 struct aws_event_stream_rpc_client_continuation_token *continuation) {
1196 return continuation->user_data;
1197 }
1198
1199 void aws_event_stream_rpc_client_continuation_acquire(
1200 const struct aws_event_stream_rpc_client_continuation_token *continuation) {
1201 size_t current_count = aws_atomic_fetch_add_explicit(
1202 &((struct aws_event_stream_rpc_client_continuation_token *)continuation)->ref_count,
1203 1u,
1204 aws_memory_order_relaxed);
1205 AWS_LOGF_TRACE(
1206 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1207 "id=%p: continuation acquired, new ref count is %zu.",
1208 (void *)continuation,
1209 current_count + 1);
1210 }
1211
1212 void aws_event_stream_rpc_client_continuation_release(
1213 const struct aws_event_stream_rpc_client_continuation_token *continuation) {
1214 if (AWS_UNLIKELY(!continuation)) {
1215 return;
1216 }
1217
1218 struct aws_event_stream_rpc_client_continuation_token *continuation_mut =
1219 (struct aws_event_stream_rpc_client_continuation_token *)continuation;
1220 size_t ref_count = aws_atomic_fetch_sub_explicit(&continuation_mut->ref_count, 1, aws_memory_order_seq_cst);
1221
1222 AWS_LOGF_TRACE(
1223 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1224 "id=%p: continuation released, new ref count is %zu.",
1225 (void *)continuation,
1226 ref_count - 1);
1227
1228 AWS_FATAL_ASSERT(ref_count != 0 && "Continuation ref count has gone negative");
1229
1230 if (ref_count == 1) {
1231 struct aws_allocator *allocator = continuation_mut->connection->allocator;
1232 aws_event_stream_rpc_client_connection_release(continuation_mut->connection);
1233
1234 aws_event_stream_rpc_client_stream_continuation_terminated_fn *terminated_fn = continuation_mut->terminated_fn;
1235 void *terminated_user_data = continuation_mut->user_data;
1236
1237 aws_mem_release(allocator, continuation_mut);
1238
1239 if (terminated_fn) {
1240 terminated_fn(terminated_user_data);
1241 }
1242 }
1243 }
1244
1245 bool aws_event_stream_rpc_client_continuation_is_closed(
1246 const struct aws_event_stream_rpc_client_continuation_token *continuation) {
1247 return aws_atomic_load_int(&continuation->is_closed) == 1u;
1248 }
1249
1250 int aws_event_stream_rpc_client_continuation_activate(
1251 struct aws_event_stream_rpc_client_continuation_token *continuation,
1252 struct aws_byte_cursor operation_name,
1253 const struct aws_event_stream_rpc_message_args *message_args,
1254 aws_event_stream_rpc_client_message_flush_fn *flush_fn,
1255 void *user_data) {
1256
1257 AWS_LOGF_TRACE(AWS_LS_EVENT_STREAM_RPC_CLIENT, "id=%p: activating continuation", (void *)continuation);
1258 int ret_val = AWS_OP_ERR;
1259
1260 aws_mutex_lock(&continuation->connection->lock);
1261
1262 if (continuation->stream_id) {
1263 aws_mutex_unlock(&continuation->connection->lock);
1264 AWS_LOGF_ERROR(
1265 AWS_LS_EVENT_STREAM_RPC_CLIENT, "id=%p: stream has already been activated", (void *)continuation);
1266 return aws_raise_error(AWS_ERROR_INVALID_STATE);
1267 }
1268
1269 if (continuation->connection->synced_data.is_open &&
1270 continuation->connection->synced_data.handshake_state == CONNECTION_HANDSHAKE_STATE_CONNECT_ACK_PROCESSED) {
1271 continuation->stream_id = continuation->connection->synced_data.latest_stream_id + 1;
1272 AWS_LOGF_DEBUG(
1273 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1274 "id=%p: continuation's new stream id is %" PRIu32,
1275 (void *)continuation,
1276 continuation->stream_id);
1277
1278 if (aws_hash_table_put(
1279 &continuation->connection->synced_data.continuation_table,
1280 &continuation->stream_id,
1281 continuation,
1282 NULL)) {
1283 AWS_LOGF_ERROR(
1284 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1285 "id=%p: storing the new stream failed with %s",
1286 (void *)continuation,
1287 aws_error_debug_str(aws_last_error()));
1288 continuation->stream_id = 0;
1289 goto clean_up;
1290 }
1291
1292 /*
1293 * In the original event stream, this was a synchronous operation and so the stream id increment happened after
1294 * flush callback. Post-refactor, this submits an async cross-thread task to the event loop that sends the
1295 * message.
1296 *
1297 * Cross thread tasks are handled in-order and we hold the lock while allocating and submitting the task, so we
1298 * know that the send tasks will be processed in stream id order on the event loop. The question remains, what
1299 * happens if there's a failure to send; will that disrupt stream id order due to a need to rewind? The answer
1300 * is no because any failures to send after this point are connection-fatal, so it doesn't matter that the
1301 * stream ids get out-of-order.
1302 */
1303 if (s_send_protocol_message(
1304 continuation->connection,
1305 continuation,
1306 &operation_name,
1307 message_args,
1308 continuation->stream_id,
1309 flush_fn,
1310 user_data)) {
1311 aws_hash_table_remove(
1312 &continuation->connection->synced_data.continuation_table, &continuation->stream_id, NULL, NULL);
1313 continuation->stream_id = 0;
1314 AWS_LOGF_ERROR(
1315 AWS_LS_EVENT_STREAM_RPC_CLIENT,
1316 "id=%p: failed to flush the new stream to the channel with error %s",
1317 (void *)continuation,
1318 aws_error_debug_str(aws_last_error()));
1319 goto clean_up;
1320 }
1321
1322 /* The continuation table gets a ref count on the continuation. Take it here. */
1323 aws_event_stream_rpc_client_continuation_acquire(continuation);
1324
1325 continuation->connection->synced_data.latest_stream_id = continuation->stream_id;
1326 ret_val = AWS_OP_SUCCESS;
1327 } else {
1328 /*
1329 * This catches two cases:
1330 *
1331 * (1) Attempting to activate a continuation before the connack is processed. This would result in a protocol
1332 * error that would shut down the channel, so fail it before that can happen.
1333 * (2) Attempting to activate a continuation after the channel has gone down. This leads to a situation where
1334 * the activate is guaranteed to fail but the table cleanup may already have run before we insert ourselves,
1335 * creating an orphaned continuation that leaks.
1336 */
1337 aws_raise_error(AWS_ERROR_EVENT_STREAM_RPC_CONNECTION_CLOSED);
1338 }
1339
1340 clean_up:
1341 aws_mutex_unlock(&continuation->connection->lock);
1342 return ret_val;
1343 }
1344
1345 int aws_event_stream_rpc_client_continuation_send_message(
1346 struct aws_event_stream_rpc_client_continuation_token *continuation,
1347 const struct aws_event_stream_rpc_message_args *message_args,
1348 aws_event_stream_rpc_client_message_flush_fn *flush_fn,
1349 void *user_data) {
1350
1351 if (aws_event_stream_rpc_client_continuation_is_closed(continuation)) {
1352 return aws_raise_error(AWS_ERROR_EVENT_STREAM_RPC_STREAM_CLOSED);
1353 }
1354
1355 if (!continuation->stream_id) {
1356 return aws_raise_error(AWS_ERROR_EVENT_STREAM_RPC_STREAM_NOT_ACTIVATED);
1357 }
1358
1359 return s_send_protocol_message(
1360 continuation->connection, continuation, NULL, message_args, continuation->stream_id, flush_fn, user_data);
1361 }
1362
1363 struct aws_event_loop *aws_event_stream_rpc_client_connection_get_event_loop(
1364 const struct aws_event_stream_rpc_client_connection *connection) {
1365
1366 if (!connection) {
1367 return NULL;
1368 }
1369
1370 return connection->event_loop;
1371 }