Debian Codegraph @

crt/aws-c-s3/source/s3_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/s3/private/s3_auto_ranged_get.h"
7 #include "aws/s3/private/s3_auto_ranged_put.h"
8 #include "aws/s3/private/s3_client_impl.h"
9 #include "aws/s3/private/s3_copy_object.h"
10 #include "aws/s3/private/s3_default_buffer_pool.h"
11 #include "aws/s3/private/s3_default_meta_request.h"
12 #include "aws/s3/private/s3_meta_request_impl.h"
13 #include "aws/s3/private/s3_parallel_input_stream.h"
14 #include "aws/s3/private/s3_request.h"
15 #include "aws/s3/private/s3_request_messages.h"
16 #include "aws/s3/private/s3_util.h"
17 #include "aws/s3/private/s3express_credentials_provider_impl.h"
18 #include "aws/s3/s3express_credentials_provider.h"
19
20 #include <aws/auth/credentials.h>
21 #include <aws/common/assert.h>
22 #include <aws/common/atomics.h>
23 #include <aws/common/clock.h>
24 #include <aws/common/device_random.h>
25 #include <aws/common/environment.h>
26 #include <aws/common/file.h>
27 #include <aws/common/json.h>
28 #include <aws/common/math.h>
29 #include <aws/common/priority_queue.h>
30 #include <aws/common/string.h>
31 #include <aws/common/system_info.h>
32 #include <aws/http/connection.h>
33 #include <aws/http/connection_manager.h>
34 #include <aws/http/proxy.h>
35 #include <aws/http/request_response.h>
36 #include <aws/io/channel_bootstrap.h>
37 #include <aws/io/event_loop.h>
38 #include <aws/io/host_resolver.h>
39 #include <aws/io/retry_strategy.h>
40 #include <aws/io/socket.h>
41 #include <aws/io/stream.h>
42 #include <aws/io/tls_channel_handler.h>
43 #include <aws/io/uri.h>
44
45 #include <inttypes.h>
46 #include <math.h>
47
48 #ifdef _MSC_VER
49 # pragma warning(disable : 4232) /* function pointer to dll symbol */
50 #endif /* _MSC_VER */
51
52 struct aws_s3_meta_request_work {
53 struct aws_linked_list_node node;
54 struct aws_s3_meta_request *meta_request;
55 };
56
57 static const enum aws_log_level s_log_level_client_stats = AWS_LL_INFO;
58
59 /* max-requests-in-flight = ideal-num-connections * s_max_requests_multiplier */
60 static const uint32_t s_max_requests_multiplier = 4;
61
62 /* This is used to determine the ideal number of HTTP connections. Algorithm is roughly:
63 * num-connections-max = throughput-target-gbps / s_throughput_per_connection_gbps
64 *
65 * Magic value based on: match results of the previous algorithm,
66 * where throughput-target-gpbs of 100 resulted in 250 connections.
67 *
68 * TODO: Improve this algorithm (expect higher throughput for S3 Express,
69 * expect lower throughput for small objects, etc)
70 */
71 static const double s_throughput_per_connection_gbps = 100.0 / 250;
72
73 /* After throughput math, clamp the min/max number of connections */
74 const uint32_t g_min_num_connections = 10; /* Magic value based on: 10 was old behavior */
75 /* Magic value based on: 10000 is picked randomly to be reasonable. Based on s_throughput_per_connection_gbps, that will
76 * be 2500 Gbps. */
77 const uint32_t g_max_num_connections = 10000;
78
79 /**
80 * Default max part size is 5GiB as the server limit.
81 */
82 static const uint32_t s_default_max_retries = 5;
83 static size_t s_dns_host_address_ttl_seconds = 5 * 60;
84
85 /* Default time until a connection is declared dead, while handling a request but seeing no activity.
86 * 30 seconds mirrors the value currently used by the Java SDK. */
87 static const uint32_t s_default_throughput_failure_interval_seconds = 30;
88
89 /* Amount of time spent idling before trimming buffer. */
90 static const size_t s_buffer_pool_trim_time_offset_in_s = 5;
91
92 /* Interval for scheduling endpoints cleanup task. This is to trim endpoints with a zero reference
93 * count. S3 closes the idle connections in ~5 seconds. */
94 static const uint32_t s_endpoints_cleanup_time_offset_in_s = 5;
95
96 /**
97 * The envrionment variable name for memory limit control.
98 */
99 static const char *s_memory_limit_env_var = "AWS_CRT_S3_MEMORY_LIMIT_IN_GIB";
100
101 /* Called when ref count is 0. */
102 static void s_s3_client_start_destroy(void *user_data);
103
104 /* Called by s_s3_client_process_work_default when all shutdown criteria has been met. */
105 static void s_s3_client_finish_destroy_default(struct aws_s3_client *client);
106
107 /* Called when the body streaming elg shutdown has completed. */
108 static void s_s3_client_body_streaming_elg_shutdown(void *user_data);
109
110 static void s_s3_client_create_connection_for_request(struct aws_s3_client *client, struct aws_s3_request *request);
111
112 static void s_s3_endpoints_cleanup_task(struct aws_task *task, void *arg, enum aws_task_status task_status);
113
114 /* Callback which handles the HTTP connection retrieved by acquire_http_connection. */
115 static void s_s3_client_on_acquire_http_connection(
116 struct aws_http_connection *http_connection,
117 int error_code,
118 void *user_data);
119
120 static void s_s3_client_push_meta_request_synced(
121 struct aws_s3_client *client,
122 struct aws_s3_meta_request *meta_request);
123
124 /* Schedule task for processing work. (Calls the corresponding vtable function.) */
125 static void s_s3_client_schedule_process_work_synced(struct aws_s3_client *client);
126
127 /* Default implementation for scheduling processing of work. */
128 static void s_s3_client_schedule_process_work_synced_default(struct aws_s3_client *client);
129
130 /* Actual task function that processes work. */
131 static void s_s3_client_process_work_task(struct aws_task *task, void *arg, enum aws_task_status task_status);
132
133 static void s_s3_client_process_work_default(struct aws_s3_client *client);
134
135 static void s_s3_client_endpoint_shutdown_callback(struct aws_s3_client *client);
136
137 /* Default factory function for creating a meta request. */
138 static struct aws_s3_meta_request *s_s3_client_meta_request_factory_default(
139 struct aws_s3_client *client,
140 const struct aws_s3_meta_request_options *options);
141
142 static struct aws_s3_client_vtable s_s3_client_default_vtable = {
143 .meta_request_factory = s_s3_client_meta_request_factory_default,
144 .acquire_http_connection = aws_http_connection_manager_acquire_connection,
145 .get_host_address_count = aws_host_resolver_get_host_address_count,
146 .schedule_process_work_synced = s_s3_client_schedule_process_work_synced_default,
147 .process_work = s_s3_client_process_work_default,
148 .endpoint_shutdown_callback = s_s3_client_endpoint_shutdown_callback,
149 .finish_destroy = s_s3_client_finish_destroy_default,
150 .parallel_input_stream_new_from_file = aws_parallel_input_stream_new_from_file,
151 .http_connection_make_request = aws_http_connection_make_request,
152 };
153
154 void aws_s3_set_dns_ttl(size_t ttl) {
155 s_dns_host_address_ttl_seconds = ttl;
156 }
157
158 /**
159 * Determine how many connections are ideal by dividing target-throughput by throughput-per-connection.
160 * TODO: we may consider to alter this, upload to regular s3 can use more connections, and s3 express
161 * can use less connections to reach the target throughput..
162 **/
163 static uint32_t s_get_ideal_connection_number_from_throughput(double throughput_gps) {
164 double ideal_connection_count_double = throughput_gps / s_throughput_per_connection_gbps;
165 /* round up and clamp */
166 ideal_connection_count_double = ceil(ideal_connection_count_double);
167 ideal_connection_count_double = aws_min_double(g_max_num_connections, ideal_connection_count_double);
168 return (uint32_t)ideal_connection_count_double;
169 }
170
171 /* Returns the max number of connections allowed.
172 *
173 * When meta request is NULL, this will return the overall allowed number of connections based on the clinet
174 * configurations.
175 *
176 * If meta_request is not NULL, this will return the number of connections allowed based on the meta request
177 * configurations.
178 */
179 uint32_t aws_s3_client_get_max_active_connections(
180 struct aws_s3_client *client,
181 struct aws_s3_meta_request *meta_request) {
182 AWS_PRECONDITION(client);
183
184 uint32_t max_active_connections = client->ideal_connection_count;
185 if (client->max_active_connections_override > 0 &&
186 client->max_active_connections_override < max_active_connections) {
187 max_active_connections = client->max_active_connections_override;
188 }
189 if (meta_request) {
190 if (meta_request->max_active_connections_override) {
191 /* Apply the meta request level override the max active connections, but less than the client side settings.
192 */
193 max_active_connections = aws_min_u32(meta_request->max_active_connections_override, max_active_connections);
194 }
195 if (meta_request->fio_opts.should_stream && meta_request->fio_opts.disk_throughput_gbps > 0) {
196 return aws_min_u32(
197 s_get_ideal_connection_number_from_throughput(meta_request->fio_opts.disk_throughput_gbps),
198 max_active_connections);
199 }
200 }
201 if (client->fio_opts.should_stream && client->fio_opts.disk_throughput_gbps > 0) {
202 return aws_min_u32(
203 s_get_ideal_connection_number_from_throughput(client->fio_opts.disk_throughput_gbps),
204 max_active_connections);
205 }
206
207 return max_active_connections;
208 }
209
210 /* Returns the max number of requests allowed to be in memory */
211 uint32_t aws_s3_client_get_max_requests_in_flight(struct aws_s3_client *client) {
212 AWS_PRECONDITION(client);
213 return aws_s3_client_get_max_active_connections(client, NULL) * s_max_requests_multiplier;
214 }
215
216 /* Returns the max number of requests that should be in preparation stage (ie: reading from a stream, being signed,
217 * etc.) */
218 uint32_t aws_s3_client_get_max_requests_prepare(struct aws_s3_client *client) {
219 return aws_s3_client_get_max_active_connections(client, NULL);
220 }
221
222 static uint32_t s_s3_client_get_num_requests_network_io(
223 struct aws_s3_client *client,
224 enum aws_s3_meta_request_type meta_request_type) {
225 AWS_PRECONDITION(client);
226
227 uint32_t num_requests_network_io = 0;
228
229 if (meta_request_type == AWS_S3_META_REQUEST_TYPE_MAX) {
230 for (uint32_t i = 0; i < AWS_S3_META_REQUEST_TYPE_MAX; ++i) {
231 num_requests_network_io += (uint32_t)aws_atomic_load_int(&client->stats.num_requests_network_io[i]);
232 }
233 } else {
234 num_requests_network_io =
235 (uint32_t)aws_atomic_load_int(&client->stats.num_requests_network_io[meta_request_type]);
236 }
237
238 return num_requests_network_io;
239 }
240
241 void aws_s3_client_lock_synced_data(struct aws_s3_client *client) {
242 aws_mutex_lock(&client->synced_data.lock);
243 }
244
245 void aws_s3_client_unlock_synced_data(struct aws_s3_client *client) {
246 aws_mutex_unlock(&client->synced_data.lock);
247 }
248
249 static void s_s3express_provider_finish_destroy(void *user_data) {
250 struct aws_s3_client *client = user_data;
251 AWS_PRECONDITION(client);
252 /* BEGIN CRITICAL SECTION */
253 {
254 aws_s3_client_lock_synced_data(client);
255 client->synced_data.s3express_provider_active = false;
256 /* Schedule the work task to call s_s3_client_finish_destroy function if
257 * everything cleaning up asynchronously has finished. */
258 s_s3_client_schedule_process_work_synced(client);
259 aws_s3_client_unlock_synced_data(client);
260 }
261 /* END CRITICAL SECTION */
262 }
263
264 struct aws_s3express_credentials_provider *s_s3express_provider_default_factory(
265 struct aws_allocator *allocator,
266 struct aws_s3_client *client,
267 aws_simple_completion_callback on_provider_shutdown_callback,
268 void *shutdown_user_data,
269 void *factory_user_data) {
270 (void)factory_user_data;
271
272 struct aws_s3express_credentials_provider_default_options options = {
273 .client = client,
274 .shutdown_complete_callback = on_provider_shutdown_callback,
275 .shutdown_user_data = shutdown_user_data,
276 };
277 struct aws_s3express_credentials_provider *s3express_provider =
278 aws_s3express_credentials_provider_new_default(allocator, &options);
279 return s3express_provider;
280 }
281
282 struct aws_s3_client *aws_s3_client_new(
283 struct aws_allocator *allocator,
284 const struct aws_s3_client_config *client_config) {
285
286 AWS_PRECONDITION(allocator);
287 AWS_PRECONDITION(client_config);
288
289 if (client_config->client_bootstrap == NULL) {
290 AWS_LOGF_ERROR(
291 AWS_LS_S3_CLIENT,
292 "Cannot create client from client_config; client_bootstrap provided in options is invalid.");
293 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
294 return NULL;
295 }
296
297 /* Cannot be less than zero. If zero, use default. */
298 if (client_config->throughput_target_gbps < 0.0) {
299 AWS_LOGF_ERROR(
300 AWS_LS_S3_CLIENT,
301 "Cannot create client from client_config; throughput_target_gbps cannot less than or equal to 0.");
302 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
303 return NULL;
304 }
305
306 if (client_config->signing_config == NULL) {
307 AWS_LOGF_ERROR(AWS_LS_S3_CLIENT, "Cannot create client from client_config; signing_config is required.");
308 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
309 return NULL;
310 }
311
312 if (client_config->signing_config->credentials == NULL &&
313 client_config->signing_config->credentials_provider == NULL) {
314 AWS_LOGF_ERROR(
315 AWS_LS_S3_CLIENT,
316 "Cannot create client from client_config; Invalid signing_config provided, either credentials or "
317 "credentials provider has to be set.");
318 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
319 return NULL;
320 }
321
322 if (!client_config->enable_s3express &&
323 client_config->signing_config->algorithm == AWS_SIGNING_ALGORITHM_V4_S3EXPRESS) {
324 AWS_LOGF_ERROR(
325 AWS_LS_S3_CLIENT,
326 "Cannot create client from client_config; Client config is set use S3 Express signing, but S3 Express "
327 "support is "
328 "not configured.");
329 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
330 return NULL;
331 }
332 uint64_t mem_limit_configured = 0;
333 if (client_config->memory_limit_in_bytes == 0) {
334 /* Try to read from the envrionment variable for memory limit */
335 struct aws_string *memory_limit_from_env_var = aws_get_env_nonempty(allocator, s_memory_limit_env_var);
336 if (memory_limit_from_env_var) {
337 uint64_t mem_limit_in_gib = 0;
338 if (aws_byte_cursor_utf8_parse_u64(
339 aws_byte_cursor_from_string(memory_limit_from_env_var), &mem_limit_in_gib)) {
340 aws_string_destroy(memory_limit_from_env_var);
341 AWS_LOGF_ERROR(
342 AWS_LS_S3_CLIENT,
343 "Cannot create client from client_config; envrionment variable: %s, is not set correctly, only "
344 "integers supported.",
345 s_memory_limit_env_var);
346 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
347 return NULL;
348 }
349 aws_string_destroy(memory_limit_from_env_var);
350 uint64_t mem_limit_in_bytes = 0;
351 /* Covert mem_limit_in_gib to bytes */
352 if (aws_mul_u64_checked(mem_limit_in_gib, 1024, &mem_limit_in_bytes) ||
353 aws_mul_u64_checked(mem_limit_in_bytes, 1024, &mem_limit_in_bytes) ||
354 aws_mul_u64_checked(mem_limit_in_bytes, 1024, &mem_limit_in_bytes)) {
355 AWS_LOGF_ERROR(
356 AWS_LS_S3_CLIENT,
357 "Cannot create client from client_config; envrionment variable: %s, overflow detected.",
358 s_memory_limit_env_var);
359 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
360 return NULL;
361 }
362
363 mem_limit_configured = mem_limit_in_bytes;
364 }
365 } else {
366 mem_limit_configured = client_config->memory_limit_in_bytes;
367 }
368 #ifdef BYO_CRYPTO
369 if (client_config->tls_mode == AWS_MR_TLS_ENABLED && client_config->tls_connection_options == NULL) {
370 AWS_LOGF_ERROR(
371 AWS_LS_S3_CLIENT,
372 "Cannot create client from client_config; when using BYO_CRYPTO, tls_connection_options can not be "
373 "NULL when TLS is enabled.");
374 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
375 return NULL;
376 }
377 #endif
378
379 struct aws_s3_client *client = aws_mem_calloc(allocator, 1, sizeof(struct aws_s3_client));
380
381 client->allocator = allocator;
382
383 size_t mem_limit = 0;
384 if (mem_limit_configured == 0) {
385 #if SIZE_BITS == 32
386 if (client_config->throughput_target_gbps > 25.0) {
387 mem_limit = GB_TO_BYTES(2);
388 } else {
389 mem_limit = GB_TO_BYTES(1);
390 }
391 #else
392 if (client_config->throughput_target_gbps >= 200.0) {
393 mem_limit = GB_TO_BYTES(24);
394 } else if (client_config->throughput_target_gbps >= 100.0) {
395 mem_limit = GB_TO_BYTES(16);
396 } else if (client_config->throughput_target_gbps >= 75.0) {
397 mem_limit = GB_TO_BYTES(8);
398 } else if (client_config->throughput_target_gbps >= 25.0) {
399 mem_limit = GB_TO_BYTES(4);
400 } else {
401 mem_limit = GB_TO_BYTES(2);
402 }
403 #endif
404 } else {
405 // cap memory limit to SIZE_MAX
406 if (mem_limit_configured > SIZE_MAX) {
407 mem_limit = SIZE_MAX;
408 } else {
409 mem_limit = (size_t)mem_limit_configured;
410 }
411 }
412
413 if (client_config->throughput_target_gbps > 0.0) {
414 *((double *)&client->throughput_target_gbps) = client_config->throughput_target_gbps;
415 } else {
416 *((double *)&client->throughput_target_gbps) = g_default_throughput_target_gbps;
417 }
418
419 *((enum aws_s3_meta_request_compute_content_md5 *)&client->compute_content_md5) =
420 client_config->compute_content_md5;
421
422 *(uint32_t *)&client->ideal_connection_count = aws_max_u32(
423 g_min_num_connections, s_get_ideal_connection_number_from_throughput(client->throughput_target_gbps));
424
425 size_t part_size = (size_t)g_default_part_size_fallback;
426 if (client_config->part_size != 0) {
427 if (client_config->part_size > SIZE_MAX) {
428 part_size = SIZE_MAX;
429 } else {
430 part_size = (size_t)client_config->part_size;
431 }
432 client->part_size_set = true;
433 }
434
435 /* default max part size is the smallest of either half of mem limit or default max part size */
436 size_t max_part_size = aws_min_size(mem_limit / 2, (size_t)g_default_max_part_size);
437 if (client_config->max_part_size != 0) {
438 if (client_config->max_part_size > SIZE_MAX) {
439 max_part_size = SIZE_MAX;
440 } else {
441 max_part_size = (size_t)client_config->max_part_size;
442 }
443 }
444
445 if (client_config->fio_opts) {
446 client->fio_opts = *client_config->fio_opts;
447 client->fio_options_set = true;
448 }
449
450 struct aws_s3_buffer_pool_config buffer_pool_config = {
451 .client = client,
452 .part_size = part_size,
453 .memory_limit = mem_limit,
454 .max_part_size = max_part_size,
455 };
456
457 if (client_config->buffer_pool_factory_fn) {
458 client->buffer_pool =
459 client_config->buffer_pool_factory_fn(allocator, buffer_pool_config, client_config->buffer_pool_user_data);
460 } else {
461
462 client->buffer_pool = aws_s3_default_buffer_pool_new(allocator, buffer_pool_config);
463 }
464
465 if (client->buffer_pool == NULL) {
466 goto on_error;
467 }
468
469 /* Calculate optimal range size based on memory limits and connection count */
470 uint64_t calculated_optimal_range_size = 0;
471 if (aws_s3_calculate_client_optimal_range_size(
472 mem_limit, client->ideal_connection_count, &calculated_optimal_range_size) != AWS_OP_SUCCESS) {
473 /* Fall back to default if calculation fails */
474 calculated_optimal_range_size = g_default_part_size_fallback;
475 AWS_LOGF_WARN(
476 AWS_LS_S3_CLIENT, "id=%p: Failed to calculate optimal range size, falling back to default", (void *)client);
477 }
478 /* Apply a buffer pool alignment to the calculated optimal range size */
479 calculated_optimal_range_size =
480 aws_s3_buffer_pool_derive_aligned_buffer_size(client->buffer_pool, calculated_optimal_range_size);
481 /* Note: cap the calculated optimal range size based on the initial window size to avoid blocking. */
482 if (client->enable_read_backpressure && client->initial_read_window) {
483 /* Make sure we can have at least 10 parts to be delivered. */
484 uint64_t initial_read_window_cap = client->initial_read_window / 10;
485 initial_read_window_cap = aws_max_u64(initial_read_window_cap, g_default_part_size_fallback);
486 calculated_optimal_range_size = aws_min_u64(calculated_optimal_range_size, initial_read_window_cap);
487 }
488 *((uint64_t *)&client->optimal_range_size) = calculated_optimal_range_size;
489
490 AWS_LOGF_INFO(
491 AWS_LS_S3_CLIENT,
492 "id=%p: Calculated optimal range size: %" PRIu64 " bytes (%.2f MiB) based on memory_limit=%" PRIu64
493 " bytes, ideal_connection_count=%" PRIu32 ", and initial_read_window=%zu.",
494 (void *)client,
495 client->optimal_range_size,
496 (double)client->optimal_range_size / (1024.0 * 1024.0),
497 (uint64_t)mem_limit,
498 client->ideal_connection_count,
499 client->initial_read_window);
500
501 client->vtable = &s_s3_client_default_vtable;
502
503 aws_ref_count_init(&client->ref_count, client, (aws_simple_completion_callback *)s_s3_client_start_destroy);
504
505 if (aws_mutex_init(&client->synced_data.lock) != AWS_OP_SUCCESS) {
506 goto on_error;
507 }
508
509 aws_linked_list_init(&client->synced_data.pending_meta_request_work);
510 aws_linked_list_init(&client->synced_data.prepared_requests);
511
512 aws_linked_list_init(&client->threaded_data.meta_requests);
513 aws_linked_list_init(&client->threaded_data.request_queue);
514
515 aws_atomic_init_int(&client->stats.num_requests_in_flight, 0);
516 aws_atomic_init_int(&client->stats.num_requests_streaming_request_body, 0);
517
518 for (uint32_t i = 0; i < (uint32_t)AWS_S3_META_REQUEST_TYPE_MAX; ++i) {
519 aws_atomic_init_int(&client->stats.num_requests_network_io[i], 0);
520 }
521
522 aws_atomic_init_int(&client->stats.num_requests_stream_queued_waiting, 0);
523 aws_atomic_init_int(&client->stats.num_requests_streaming_response, 0);
524
525 *((uint32_t *)&client->max_active_connections_override) = client_config->max_active_connections_override;
526
527 /* Store our client bootstrap. */
528 client->client_bootstrap = aws_client_bootstrap_acquire(client_config->client_bootstrap);
529
530 struct aws_event_loop_group *event_loop_group = client_config->client_bootstrap->event_loop_group;
531 aws_event_loop_group_acquire(event_loop_group);
532
533 client->process_work_event_loop = aws_event_loop_group_get_next_loop(event_loop_group);
534
535 /* Make a copy of the region string. */
536 client->region = aws_string_new_from_array(allocator, client_config->region.ptr, client_config->region.len);
537
538 *((size_t *)&client->part_size) = part_size;
539
540 *((uint64_t *)&client->max_part_size) = max_part_size;
541
542 if (client_config->multipart_upload_threshold != 0) {
543 *((uint64_t *)&client->multipart_upload_threshold) = client_config->multipart_upload_threshold;
544 } else {
545 *((uint64_t *)&client->multipart_upload_threshold) =
546 part_size > g_s3_min_upload_part_size ? part_size : g_s3_min_upload_part_size;
547 }
548
549 if (client_config->max_part_size < client_config->part_size) {
550 *((uint64_t *)&client_config->max_part_size) = client_config->part_size;
551 }
552
553 client->connect_timeout_ms = client_config->connect_timeout_ms;
554 if (client_config->proxy_ev_settings) {
555 client->proxy_ev_settings = aws_mem_calloc(allocator, 1, sizeof(struct proxy_env_var_settings));
556 *client->proxy_ev_settings = *client_config->proxy_ev_settings;
557
558 if (client_config->proxy_ev_settings->tls_options) {
559 client->proxy_ev_tls_options = aws_mem_calloc(allocator, 1, sizeof(struct aws_tls_connection_options));
560 if (aws_tls_connection_options_copy(client->proxy_ev_tls_options, client->proxy_ev_settings->tls_options)) {
561 goto on_error;
562 }
563 client->proxy_ev_settings->tls_options = client->proxy_ev_tls_options;
564 }
565 }
566
567 if (client_config->tcp_keep_alive_options) {
568 client->tcp_keep_alive_options = aws_mem_calloc(allocator, 1, sizeof(struct aws_s3_tcp_keep_alive_options));
569 *client->tcp_keep_alive_options = *client_config->tcp_keep_alive_options;
570 }
571
572 if (client_config->monitoring_options) {
573 client->monitoring_options = *client_config->monitoring_options;
574 } else {
575 client->monitoring_options.minimum_throughput_bytes_per_second = 1;
576 client->monitoring_options.allowable_throughput_failure_interval_seconds =
577 s_default_throughput_failure_interval_seconds;
578 }
579
580 if (client_config->tls_mode == AWS_MR_TLS_ENABLED) {
581 client->tls_connection_options =
582 aws_mem_calloc(client->allocator, 1, sizeof(struct aws_tls_connection_options));
583
584 if (client_config->tls_connection_options != NULL) {
585 aws_tls_connection_options_copy(client->tls_connection_options, client_config->tls_connection_options);
586 } else {
587 #ifdef BYO_CRYPTO
588 AWS_FATAL_ASSERT(false);
589 goto on_error;
590 #else
591 struct aws_tls_ctx_options default_tls_ctx_options;
592 AWS_ZERO_STRUCT(default_tls_ctx_options);
593
594 aws_tls_ctx_options_init_default_client(&default_tls_ctx_options, allocator);
595
596 struct aws_tls_ctx *default_tls_ctx = aws_tls_client_ctx_new(allocator, &default_tls_ctx_options);
597 if (default_tls_ctx == NULL) {
598 goto on_error;
599 }
600
601 aws_tls_connection_options_init_from_ctx(client->tls_connection_options, default_tls_ctx);
602
603 aws_tls_ctx_release(default_tls_ctx);
604 aws_tls_ctx_options_clean_up(&default_tls_ctx_options);
605 #endif
606 }
607 }
608
609 if (client_config->proxy_options) {
610 client->proxy_config = aws_http_proxy_config_new_from_proxy_options_with_tls_info(
611 allocator, client_config->proxy_options, client_config->tls_mode == AWS_MR_TLS_ENABLED);
612 if (client->proxy_config == NULL) {
613 goto on_error;
614 }
615 }
616
617 client->num_network_interface_names = client_config->num_network_interface_names;
618 if (client_config->num_network_interface_names > 0) {
619 AWS_LOGF_DEBUG(
620 AWS_LS_S3_CLIENT,
621 "id=%p Client received network interface names array with length %zu.",
622 (void *)client,
623 client->num_network_interface_names);
624 aws_array_list_init_dynamic(
625 &client->network_interface_names,
626 client->allocator,
627 client_config->num_network_interface_names,
628 sizeof(struct aws_string *));
629 client->network_interface_names_cursor_array = aws_mem_calloc(
630 client->allocator, client_config->num_network_interface_names, sizeof(struct aws_byte_cursor));
631 for (size_t i = 0; i < client_config->num_network_interface_names; i++) {
632 struct aws_byte_cursor interface_name = client_config->network_interface_names_array[i];
633 struct aws_string *interface_name_str = aws_string_new_from_cursor(client->allocator, &interface_name);
634 aws_array_list_push_back(&client->network_interface_names, &interface_name_str);
635 if (aws_is_network_interface_name_valid(aws_string_c_str(interface_name_str)) == false) {
636 AWS_LOGF_ERROR(
637 AWS_LS_S3_CLIENT,
638 "id=%p network_interface_names_array[%zu]=" PRInSTR " is not valid.",
639 (void *)client,
640 i,
641 AWS_BYTE_CURSOR_PRI(interface_name));
642 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
643 goto on_error;
644 }
645 client->network_interface_names_cursor_array[i] = aws_byte_cursor_from_string(interface_name_str);
646 AWS_LOGF_DEBUG(
647 AWS_LS_S3_CLIENT,
648 "id=%p network_interface_names_array[%zu]=" PRInSTR "",
649 (void *)client,
650 i,
651 AWS_BYTE_CURSOR_PRI(client->network_interface_names_cursor_array[i]));
652 }
653 }
654
655 /* Set up body streaming ELG */
656 {
657 uint16_t num_event_loops =
658 (uint16_t)aws_event_loop_group_get_loop_count(client->client_bootstrap->event_loop_group);
659 uint16_t num_streaming_threads = num_event_loops;
660
661 if (num_streaming_threads < 1) {
662 num_streaming_threads = 1;
663 }
664
665 struct aws_shutdown_callback_options body_streaming_elg_shutdown_options = {
666 .shutdown_callback_fn = s_s3_client_body_streaming_elg_shutdown,
667 .shutdown_callback_user_data = client,
668 };
669
670 client->body_streaming_elg = aws_event_loop_group_new_default(
671 client->allocator, num_streaming_threads, &body_streaming_elg_shutdown_options);
672
673 if (!client->body_streaming_elg) {
674 /* Fail to create elg, we should fail the call */
675 goto on_error;
676 }
677 client->synced_data.body_streaming_elg_allocated = true;
678 }
679 /* Setup cannot fail after this point. */
680
681 client->cached_signing_config = aws_cached_signing_config_new(client, client_config->signing_config);
682 if (client_config->enable_s3express) {
683 if (client_config->s3express_provider_override_factory) {
684 client->s3express_provider_factory = client_config->s3express_provider_override_factory;
685 client->factory_user_data = client_config->factory_user_data;
686 } else {
687 client->s3express_provider_factory = s_s3express_provider_default_factory;
688 }
689 }
690
691 client->synced_data.active = true;
692
693 if (client_config->retry_strategy != NULL) {
694 aws_retry_strategy_acquire(client_config->retry_strategy);
695 client->retry_strategy = client_config->retry_strategy;
696 } else {
697 struct aws_exponential_backoff_retry_options backoff_retry_options = {
698 .el_group = client_config->client_bootstrap->event_loop_group,
699 .max_retries = s_default_max_retries,
700 };
701
702 struct aws_standard_retry_options retry_options = {
703 .backoff_retry_options = backoff_retry_options,
704 };
705
706 client->retry_strategy = aws_retry_strategy_new_standard(allocator, &retry_options);
707 }
708
709 aws_hash_table_init(
710 &client->synced_data.endpoints,
711 client->allocator,
712 10,
713 aws_hash_string,
714 aws_hash_callback_string_eq,
715 aws_hash_callback_string_destroy,
716 NULL);
717 aws_task_init(
718 &client->synced_data.endpoints_cleanup_task, s_s3_endpoints_cleanup_task, client, "s3_endpoints_cleanup_task");
719
720 /* Initialize shutdown options and tracking. */
721 client->shutdown_callback = client_config->shutdown_callback;
722 client->shutdown_callback_user_data = client_config->shutdown_callback_user_data;
723
724 *((bool *)&client->enable_read_backpressure) = client_config->enable_read_backpressure;
725 *((size_t *)&client->initial_read_window) = client_config->initial_read_window;
726
727 return client;
728
729 on_error:
730 aws_string_destroy(client->region);
731
732 if (client->tls_connection_options) {
733 aws_tls_connection_options_clean_up(client->tls_connection_options);
734 aws_mem_release(client->allocator, client->tls_connection_options);
735 client->tls_connection_options = NULL;
736 }
737 if (client->proxy_config) {
738 aws_http_proxy_config_destroy(client->proxy_config);
739 }
740 if (client->proxy_ev_tls_options) {
741 aws_tls_connection_options_clean_up(client->proxy_ev_tls_options);
742 aws_mem_release(client->allocator, client->proxy_ev_tls_options);
743 client->proxy_ev_settings->tls_options = NULL;
744 }
745 aws_mem_release(client->allocator, client->proxy_ev_settings);
746 aws_mem_release(client->allocator, client->tcp_keep_alive_options);
747
748 if (client->client_bootstrap != NULL) {
749 aws_event_loop_group_release(client->client_bootstrap->event_loop_group);
750 }
751 aws_client_bootstrap_release(client->client_bootstrap);
752 aws_mutex_clean_up(&client->synced_data.lock);
753
754 aws_mem_release(client->allocator, client->network_interface_names_cursor_array);
755 for (size_t i = 0; i < aws_array_list_length(&client->network_interface_names); i++) {
756 struct aws_string *interface_name = NULL;
757 aws_array_list_get_at(&client->network_interface_names, &interface_name, i);
758 aws_string_destroy(interface_name);
759 }
760
761 aws_array_list_clean_up(&client->network_interface_names);
762 client->buffer_pool = aws_s3_buffer_pool_release(client->buffer_pool);
763
764 aws_mem_release(client->allocator, client);
765 return NULL;
766 }
767
768 struct aws_s3_client *aws_s3_client_acquire(struct aws_s3_client *client) {
769 AWS_PRECONDITION(client);
770
771 aws_ref_count_acquire(&client->ref_count);
772 return client;
773 }
774
775 struct aws_s3_client *aws_s3_client_release(struct aws_s3_client *client) {
776 if (client != NULL) {
777 aws_ref_count_release(&client->ref_count);
778 }
779
780 return NULL;
781 }
782
783 static void s_s3_client_start_destroy(void *user_data) {
784 struct aws_s3_client *client = user_data;
785 AWS_PRECONDITION(client);
786
787 AWS_LOGF_DEBUG(AWS_LS_S3_CLIENT, "id=%p Client starting destruction.", (void *)client);
788
789 struct aws_linked_list local_vip_list;
790 aws_linked_list_init(&local_vip_list);
791
792 /* BEGIN CRITICAL SECTION */
793 {
794 aws_s3_client_lock_synced_data(client);
795
796 client->synced_data.active = false;
797 if (!client->synced_data.endpoints_cleanup_task_scheduled) {
798 client->synced_data.endpoints_cleanup_task_scheduled = true;
799 aws_event_loop_schedule_task_now(
800 client->process_work_event_loop, &client->synced_data.endpoints_cleanup_task);
801 }
802 /* Prevent the client from cleaning up in between the mutex unlock/re-lock below.*/
803 client->synced_data.start_destroy_executing = true;
804
805 aws_s3_client_unlock_synced_data(client);
806 }
807 /* END CRITICAL SECTION */
808
809 aws_event_loop_group_release(client->body_streaming_elg);
810 client->body_streaming_elg = NULL;
811 aws_s3express_credentials_provider_release(client->s3express_provider);
812
813 /* BEGIN CRITICAL SECTION */
814 {
815 aws_s3_client_lock_synced_data(client);
816 client->synced_data.start_destroy_executing = false;
817
818 /* Schedule the work task to clean up outstanding connections and to call s_s3_client_finish_destroy function if
819 * everything cleaning up asynchronously has finished. */
820 s_s3_client_schedule_process_work_synced(client);
821 aws_s3_client_unlock_synced_data(client);
822 }
823 /* END CRITICAL SECTION */
824 }
825
826 static void s_s3_client_finish_destroy_default(struct aws_s3_client *client) {
827 AWS_PRECONDITION(client);
828
829 AWS_LOGF_DEBUG(AWS_LS_S3_CLIENT, "id=%p Client finishing destruction.", (void *)client);
830
831 if (client->threaded_data.trim_buffer_pool_task_scheduled) {
832 aws_event_loop_cancel_task(client->process_work_event_loop, &client->synced_data.trim_buffer_pool_task);
833 }
834
835 aws_string_destroy(client->region);
836 client->region = NULL;
837
838 if (client->tls_connection_options) {
839 aws_tls_connection_options_clean_up(client->tls_connection_options);
840 aws_mem_release(client->allocator, client->tls_connection_options);
841 client->tls_connection_options = NULL;
842 }
843
844 if (client->proxy_config) {
845 aws_http_proxy_config_destroy(client->proxy_config);
846 }
847
848 if (client->proxy_ev_tls_options) {
849 aws_tls_connection_options_clean_up(client->proxy_ev_tls_options);
850 aws_mem_release(client->allocator, client->proxy_ev_tls_options);
851 client->proxy_ev_settings->tls_options = NULL;
852 }
853 aws_mem_release(client->allocator, client->proxy_ev_settings);
854 aws_mem_release(client->allocator, client->tcp_keep_alive_options);
855
856 aws_mutex_clean_up(&client->synced_data.lock);
857
858 AWS_ASSERT(aws_linked_list_empty(&client->synced_data.pending_meta_request_work));
859 AWS_ASSERT(aws_linked_list_empty(&client->threaded_data.meta_requests));
860 aws_hash_table_clean_up(&client->synced_data.endpoints);
861
862 aws_retry_strategy_release(client->retry_strategy);
863
864 aws_event_loop_group_release(client->client_bootstrap->event_loop_group);
865
866 aws_client_bootstrap_release(client->client_bootstrap);
867 aws_cached_signing_config_destroy(client->cached_signing_config);
868
869 aws_s3_client_shutdown_complete_callback_fn *shutdown_callback = client->shutdown_callback;
870 void *shutdown_user_data = client->shutdown_callback_user_data;
871
872 client->buffer_pool = aws_s3_buffer_pool_release(client->buffer_pool);
873
874 if (client->synced_data.upload_part_stats.initial_request_time.collecting_p90) {
875 aws_priority_queue_clean_up(&client->synced_data.upload_part_stats.initial_request_time.p90_samples);
876 }
877
878 aws_mem_release(client->allocator, client->network_interface_names_cursor_array);
879 for (size_t i = 0; i < client->num_network_interface_names; i++) {
880 struct aws_string *interface_name = NULL;
881 aws_array_list_get_at(&client->network_interface_names, &interface_name, i);
882 aws_string_destroy(interface_name);
883 }
884 aws_array_list_clean_up(&client->network_interface_names);
885
886 aws_mem_release(client->allocator, client);
887 client = NULL;
888
889 if (shutdown_callback != NULL) {
890 shutdown_callback(shutdown_user_data);
891 }
892 }
893
894 static void s_s3_client_body_streaming_elg_shutdown(void *user_data) {
895 struct aws_s3_client *client = user_data;
896 AWS_PRECONDITION(client);
897
898 AWS_LOGF_DEBUG(AWS_LS_S3_CLIENT, "id=%p Client body streaming ELG shutdown.", (void *)client);
899
900 /* BEGIN CRITICAL SECTION */
901 {
902 aws_s3_client_lock_synced_data(client);
903 client->synced_data.body_streaming_elg_allocated = false;
904 s_s3_client_schedule_process_work_synced(client);
905 aws_s3_client_unlock_synced_data(client);
906 }
907 /* END CRITICAL SECTION */
908 }
909
910 uint32_t aws_s3_client_queue_requests_threaded(
911 struct aws_s3_client *client,
912 struct aws_linked_list *request_list,
913 bool queue_front) {
914 AWS_PRECONDITION(client);
915 AWS_PRECONDITION(request_list);
916 if (aws_linked_list_empty(request_list)) {
917 return 0;
918 }
919
920 uint32_t request_list_size = 0;
921
922 for (struct aws_linked_list_node *node = aws_linked_list_begin(request_list);
923 node != aws_linked_list_end(request_list);
924 node = aws_linked_list_next(node)) {
925 ++request_list_size;
926 }
927
928 if (queue_front) {
929 aws_linked_list_move_all_front(&client->threaded_data.request_queue, request_list);
930 } else {
931 aws_linked_list_move_all_back(&client->threaded_data.request_queue, request_list);
932 }
933
934 client->threaded_data.request_queue_size += request_list_size;
935 return request_list_size;
936 }
937
938 struct aws_s3_request *aws_s3_client_dequeue_request_threaded(struct aws_s3_client *client) {
939 AWS_PRECONDITION(client);
940
941 if (aws_linked_list_empty(&client->threaded_data.request_queue)) {
942 return NULL;
943 }
944
945 struct aws_linked_list_node *request_node = aws_linked_list_pop_front(&client->threaded_data.request_queue);
946 struct aws_s3_request *request = AWS_CONTAINER_OF(request_node, struct aws_s3_request, node);
947
948 --client->threaded_data.request_queue_size;
949
950 return request;
951 }
952
953 /*
954 * There is currently some overlap between user provided Host header and endpoint
955 * override. This function handles the corner cases for when either or both are provided.
956 */
957 int s_apply_endpoint_override(
958 const struct aws_s3_client *client,
959 struct aws_http_headers *message_headers,
960 const struct aws_uri *endpoint) {
961 AWS_PRECONDITION(message_headers);
962
963 const struct aws_byte_cursor *endpoint_authority = endpoint == NULL ? NULL : aws_uri_authority(endpoint);
964
965 if (!aws_http_headers_has(message_headers, g_host_header_name)) {
966 if (endpoint_authority == NULL) {
967 AWS_LOGF_ERROR(
968 AWS_LS_S3_CLIENT,
969 "id=%p Cannot create meta s3 request; message provided in options does not have either 'Host' header "
970 "set or endpoint override.",
971 (void *)client);
972 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
973 }
974
975 if (aws_http_headers_set(message_headers, g_host_header_name, *endpoint_authority)) {
976 AWS_LOGF_ERROR(
977 AWS_LS_S3_CLIENT,
978 "id=%p Cannot create meta s3 request; failed to set 'Host' header based on endpoint override.",
979 (void *)client);
980 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
981 }
982 }
983
984 struct aws_byte_cursor host_value;
985 AWS_FATAL_ASSERT(aws_http_headers_get(message_headers, g_host_header_name, &host_value) == AWS_OP_SUCCESS);
986
987 if (endpoint_authority != NULL && !aws_byte_cursor_eq(&host_value, endpoint_authority)) {
988 AWS_LOGF_ERROR(
989 AWS_LS_S3_CLIENT,
990 "id=%p Cannot create meta s3 request; host header value " PRInSTR
991 " does not match endpoint override " PRInSTR,
992 (void *)client,
993 AWS_BYTE_CURSOR_PRI(host_value),
994 AWS_BYTE_CURSOR_PRI(*endpoint_authority));
995 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
996 }
997
998 return AWS_OP_SUCCESS;
999 }
1000
1001 /* Public facing make-meta-request function. */
1002 struct aws_s3_meta_request *aws_s3_client_make_meta_request(
1003 struct aws_s3_client *client,
1004 const struct aws_s3_meta_request_options *options) {
1005
1006 AWS_LOGF_INFO(AWS_LS_S3_CLIENT, "id=%p Initiating making of meta request", (void *)client);
1007
1008 AWS_PRECONDITION(client);
1009 AWS_PRECONDITION(client->vtable);
1010 AWS_PRECONDITION(client->vtable->meta_request_factory);
1011 AWS_PRECONDITION(options);
1012
1013 bool use_s3express_signing = false;
1014 if (options->signing_config != NULL) {
1015 use_s3express_signing = options->signing_config->algorithm == AWS_SIGNING_ALGORITHM_V4_S3EXPRESS;
1016 } else if (client->cached_signing_config) {
1017 use_s3express_signing = client->cached_signing_config->config.algorithm == AWS_SIGNING_ALGORITHM_V4_S3EXPRESS;
1018 }
1019
1020 if (options->type >= AWS_S3_META_REQUEST_TYPE_MAX) {
1021 AWS_LOGF_ERROR(
1022 AWS_LS_S3_CLIENT,
1023 "id=%p Cannot create meta s3 request; invalid meta request type specified.",
1024 (void *)client);
1025 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1026 return NULL;
1027 }
1028
1029 if (options->message == NULL) {
1030 AWS_LOGF_ERROR(
1031 AWS_LS_S3_CLIENT,
1032 "id=%p Cannot create meta s3 request; message provided in options is invalid.",
1033 (void *)client);
1034 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1035 return NULL;
1036 }
1037
1038 if (use_s3express_signing && client->s3express_provider_factory == NULL) {
1039 AWS_LOGF_ERROR(
1040 AWS_LS_S3_CLIENT,
1041 "id=%p Cannot create meta s3 request; client doesn't support S3 Express signing.",
1042 (void *)client);
1043 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1044 return NULL;
1045 }
1046
1047 struct aws_http_headers *message_headers = aws_http_message_get_headers(options->message);
1048
1049 if (message_headers == NULL) {
1050 AWS_LOGF_ERROR(
1051 AWS_LS_S3_CLIENT,
1052 "id=%p Cannot create meta s3 request; message provided in options does not contain headers.",
1053 (void *)client);
1054 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1055 return NULL;
1056 }
1057
1058 if (s_apply_endpoint_override(client, message_headers, options->endpoint)) {
1059 return NULL;
1060 }
1061
1062 struct aws_byte_cursor host_header_value;
1063 /* The Host header must be set from s_apply_endpoint_override, if not errored out */
1064 AWS_FATAL_ASSERT(aws_http_headers_get(message_headers, g_host_header_name, &host_header_value) == AWS_OP_SUCCESS);
1065
1066 bool is_https = true;
1067 uint32_t port = 0;
1068
1069 if (options->endpoint != NULL) {
1070 struct aws_byte_cursor https_scheme = aws_byte_cursor_from_c_str("https");
1071 struct aws_byte_cursor http_scheme = aws_byte_cursor_from_c_str("http");
1072
1073 const struct aws_byte_cursor *scheme = aws_uri_scheme(options->endpoint);
1074
1075 is_https = aws_byte_cursor_eq_ignore_case(scheme, &https_scheme);
1076
1077 if (!is_https && !aws_byte_cursor_eq_ignore_case(scheme, &http_scheme)) {
1078 AWS_LOGF_ERROR(
1079 AWS_LS_S3_CLIENT,
1080 "id=%p Cannot create meta s3 request; unexpected scheme '" PRInSTR "' in endpoint override.",
1081 (void *)client,
1082 AWS_BYTE_CURSOR_PRI(*scheme));
1083 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1084 return NULL;
1085 }
1086
1087 port = aws_uri_port(options->endpoint);
1088 }
1089
1090 struct aws_s3_meta_request *meta_request = client->vtable->meta_request_factory(client, options);
1091
1092 if (meta_request == NULL) {
1093 AWS_LOGF_ERROR(AWS_LS_S3_CLIENT, "id=%p: Could not create new meta request.", (void *)client);
1094 return NULL;
1095 }
1096 meta_request->is_express = use_s3express_signing;
1097
1098 bool error_occurred = false;
1099
1100 /* BEGIN CRITICAL SECTION */
1101 {
1102 aws_s3_client_lock_synced_data(client);
1103
1104 if (use_s3express_signing && !client->synced_data.s3express_provider_active) {
1105
1106 AWS_LOGF_TRACE(AWS_LS_S3_CLIENT, "id=%p Create S3 Express provider for the client.", (void *)client);
1107 /**
1108 * Invoke the factory within the lock. We WARNED people uses their own factory to not use ANY client related
1109 * api during the factory.
1110 *
1111 * We cannot just release the lock and invoke the factory, because it can lead to the other request assume
1112 * the provider is active, and not waiting for the provider to be created. And lead to unexpected behavior.
1113 */
1114 client->s3express_provider = client->s3express_provider_factory(
1115 client->allocator, client, s_s3express_provider_finish_destroy, client, client->factory_user_data);
1116
1117 /* Provider is related to client, we don't need to clean it up if meta request failed. But, if provider
1118 * failed to be created, let's bail out earlier. */
1119 if (!client->s3express_provider) {
1120 AWS_LOGF_ERROR(
1121 AWS_LS_S3_CLIENT,
1122 "id=%p Failed to create S3 Express provider for client due to error %d (%s)",
1123 (void *)client,
1124 aws_last_error_or_unknown(),
1125 aws_error_str(aws_last_error_or_unknown()));
1126 error_occurred = true;
1127 goto unlock;
1128 }
1129 client->synced_data.s3express_provider_active = true;
1130 }
1131
1132 struct aws_string *endpoint_host_name = NULL;
1133
1134 if (options->endpoint != NULL) {
1135 endpoint_host_name = aws_string_new_from_cursor(client->allocator, aws_uri_host_name(options->endpoint));
1136 } else {
1137 struct aws_uri host_uri;
1138 if (aws_uri_init_parse(&host_uri, client->allocator, &host_header_value)) {
1139 error_occurred = true;
1140 goto unlock;
1141 }
1142
1143 endpoint_host_name = aws_string_new_from_cursor(client->allocator, aws_uri_host_name(&host_uri));
1144 port = aws_uri_port(&host_uri);
1145 aws_uri_clean_up(&host_uri);
1146 }
1147
1148 struct aws_s3_endpoint *endpoint = NULL;
1149 struct aws_hash_element *endpoint_hash_element = NULL;
1150
1151 if (use_s3express_signing) {
1152 meta_request->s3express_session_host = aws_string_new_from_string(client->allocator, endpoint_host_name);
1153 }
1154
1155 int was_created = 0;
1156 if (aws_hash_table_create(
1157 &client->synced_data.endpoints, endpoint_host_name, &endpoint_hash_element, &was_created)) {
1158 aws_string_destroy(endpoint_host_name);
1159 error_occurred = true;
1160 goto unlock;
1161 }
1162
1163 if (was_created) {
1164 struct aws_s3_endpoint_options endpoint_options = {
1165 .host_name = endpoint_host_name,
1166 .client_bootstrap = client->client_bootstrap,
1167 .tls_connection_options = is_https ? client->tls_connection_options : NULL,
1168 .dns_host_address_ttl_seconds = s_dns_host_address_ttl_seconds,
1169 .client = client,
1170 .max_connections = aws_s3_client_get_max_active_connections(client, NULL),
1171 .port = port,
1172 .proxy_config = client->proxy_config,
1173 .proxy_ev_settings = client->proxy_ev_settings,
1174 .connect_timeout_ms = client->connect_timeout_ms,
1175 .tcp_keep_alive_options = client->tcp_keep_alive_options,
1176 .monitoring_options = &client->monitoring_options,
1177 .network_interface_names_array = client->network_interface_names_cursor_array,
1178 .num_network_interface_names = client->num_network_interface_names,
1179 };
1180
1181 endpoint = aws_s3_endpoint_new(client->allocator, &endpoint_options);
1182
1183 if (endpoint == NULL) {
1184 aws_hash_table_remove(&client->synced_data.endpoints, endpoint_host_name, NULL, NULL);
1185 aws_string_destroy(endpoint_host_name);
1186 error_occurred = true;
1187 goto unlock;
1188 }
1189 endpoint_hash_element->value = endpoint;
1190 ++client->synced_data.num_endpoints_allocated;
1191 } else {
1192 endpoint = endpoint_hash_element->value;
1193
1194 aws_s3_endpoint_acquire(endpoint, true /*already_holding_lock*/);
1195
1196 aws_string_destroy(endpoint_host_name);
1197 endpoint_host_name = NULL;
1198 }
1199
1200 meta_request->endpoint = endpoint;
1201 /**
1202 * shutdown_callback must be the last thing that gets set on the meta_request so that we don’t return NULL and
1203 * trigger the shutdown_callback.
1204 */
1205 meta_request->shutdown_callback = options->shutdown_callback;
1206
1207 s_s3_client_push_meta_request_synced(client, meta_request);
1208 s_s3_client_schedule_process_work_synced(client);
1209
1210 unlock:
1211 aws_s3_client_unlock_synced_data(client);
1212 }
1213 /* END CRITICAL SECTION */
1214
1215 if (error_occurred) {
1216 AWS_LOGF_ERROR(
1217 AWS_LS_S3_CLIENT,
1218 "id=%p Could not create meta request due to error %d (%s)",
1219 (void *)client,
1220 aws_last_error(),
1221 aws_error_str(aws_last_error()));
1222
1223 meta_request = aws_s3_meta_request_release(meta_request);
1224 } else {
1225 AWS_LOGF_INFO(AWS_LS_S3_CLIENT, "id=%p: Created meta request %p", (void *)client, (void *)meta_request);
1226 }
1227
1228 return meta_request;
1229 }
1230
1231 static void s_s3_client_endpoint_shutdown_callback(struct aws_s3_client *client) {
1232 AWS_PRECONDITION(client);
1233
1234 /* BEGIN CRITICAL SECTION */
1235 {
1236 aws_s3_client_lock_synced_data(client);
1237 --client->synced_data.num_endpoints_allocated;
1238 s_s3_client_schedule_process_work_synced(client);
1239 aws_s3_client_unlock_synced_data(client);
1240 }
1241 /* END CRITICAL SECTION */
1242 }
1243
1244 static struct aws_s3_meta_request *s_s3_client_meta_request_factory_default(
1245 struct aws_s3_client *client,
1246 const struct aws_s3_meta_request_options *options) {
1247 AWS_PRECONDITION(client);
1248 AWS_PRECONDITION(options);
1249
1250 const struct aws_http_headers *initial_message_headers = aws_http_message_get_headers(options->message);
1251 AWS_ASSERT(initial_message_headers);
1252
1253 uint64_t content_length = 0;
1254 struct aws_byte_cursor content_length_cursor;
1255 bool content_length_found = false;
1256
1257 if (!aws_http_headers_get(initial_message_headers, g_content_length_header_name, &content_length_cursor)) {
1258 if (aws_byte_cursor_utf8_parse_u64(content_length_cursor, &content_length)) {
1259 AWS_LOGF_ERROR(
1260 AWS_LS_S3_META_REQUEST,
1261 "Could not parse Content-Length header. header value is:" PRInSTR "",
1262 AWS_BYTE_CURSOR_PRI(content_length_cursor));
1263 aws_raise_error(AWS_ERROR_S3_INVALID_CONTENT_LENGTH_HEADER);
1264 return NULL;
1265 }
1266 content_length_found = true;
1267 }
1268
1269 /* There are multiple ways to pass the body in, ensure only 1 was used */
1270 int body_source_count = 0;
1271 if (aws_http_message_get_body_stream(options->message) != NULL) {
1272 ++body_source_count;
1273 }
1274 if (options->send_filepath.len > 0) {
1275 ++body_source_count;
1276 if (!content_length_found) {
1277 /* The content length was not set, but it's a file based upload. Derive the content length from the file
1278 * length */
1279 struct aws_string *file_path = aws_string_new_from_cursor(client->allocator, &options->send_filepath);
1280 struct aws_string *readonly_bytes_mode = aws_string_new_from_c_str(client->allocator, "rb");
1281 FILE *file = aws_fopen_safe(file_path, readonly_bytes_mode);
1282 int error = true;
1283 if (!file) {
1284 AWS_LOGF_ERROR(
1285 AWS_LS_S3_META_REQUEST,
1286 "Could not create meta request."
1287 "the send file path %s is invalid",
1288 aws_string_c_str(file_path));
1289 } else if (aws_file_get_length(file, (int64_t *)&content_length)) {
1290 AWS_LOGF_ERROR(
1291 AWS_LS_S3_META_REQUEST,
1292 "Could not create meta request."
1293 "failed to get the length from the send file path %s",
1294 aws_string_c_str(file_path));
1295 } else {
1296 error = false;
1297 }
1298 if (file) {
1299 fclose(file);
1300 }
1301 aws_string_destroy(file_path);
1302 aws_string_destroy(readonly_bytes_mode);
1303 if (error) {
1304 return NULL;
1305 }
1306 content_length_found = true;
1307 }
1308 }
1309 if (options->send_using_async_writes == true) {
1310 if (options->type != AWS_S3_META_REQUEST_TYPE_PUT_OBJECT) {
1311 /* TODO: we could support async-writes for DEFAULT type too, just takes work & testing */
1312 AWS_LOGF_ERROR(
1313 AWS_LS_S3_META_REQUEST,
1314 "Could not create meta request."
1315 "send-using-data-writes can only be used with auto-ranged-put.");
1316 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1317 return NULL;
1318 }
1319 if (content_length_found) {
1320 /* TODO: we could support async-writes with content-length, just takes work & testing */
1321 AWS_LOGF_ERROR(
1322 AWS_LS_S3_META_REQUEST,
1323 "Could not create meta request."
1324 "send-using-data-writes can only be used when Content-Length is unknown.");
1325 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1326 return NULL;
1327 }
1328 ++body_source_count;
1329 }
1330 if (options->send_async_stream != NULL) {
1331 ++body_source_count;
1332 }
1333 if (!aws_byte_cursor_is_valid(&options->request_body)) {
1334 AWS_LOGF_ERROR(
1335 AWS_LS_S3_META_REQUEST,
1336 "Could not create meta request."
1337 " request_body has a NULL pointer with a non-zero length.");
1338 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1339 return NULL;
1340 }
1341 if (options->request_body.ptr != NULL) {
1342 if (options->type != AWS_S3_META_REQUEST_TYPE_DEFAULT) {
1343 AWS_LOGF_ERROR(
1344 AWS_LS_S3_META_REQUEST,
1345 "Could not create meta request."
1346 " request_body is only supported for DEFAULT meta requests.");
1347 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1348 return NULL;
1349 }
1350 if (!content_length_found) {
1351 content_length = options->request_body.len;
1352 content_length_found = true;
1353 } else if (options->request_body.len != content_length) {
1354 AWS_LOGF_ERROR(
1355 AWS_LS_S3_META_REQUEST,
1356 "Could not create meta request."
1357 " request_body length (%zu) does not match the Content-Length header (%" PRIu64 ").",
1358 options->request_body.len,
1359 content_length);
1360 aws_raise_error(AWS_ERROR_S3_INCORRECT_CONTENT_LENGTH);
1361 return NULL;
1362 }
1363 ++body_source_count;
1364 }
1365 if (body_source_count > 1) {
1366 AWS_LOGF_ERROR(
1367 AWS_LS_S3_META_REQUEST,
1368 "Could not create meta request."
1369 " More than one data source is set (filepath, async stream, body stream, data writes, request_body).");
1370 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1371 return NULL;
1372 }
1373 size_t part_size = client->part_size;
1374 bool part_size_set = false;
1375 if (options->part_size != 0) {
1376 if (options->part_size > SIZE_MAX) {
1377 part_size = SIZE_MAX;
1378 } else {
1379 part_size = (size_t)options->part_size;
1380 }
1381 part_size_set = true;
1382 }
1383
1384 /* Call the appropriate meta-request new function. */
1385 switch (options->type) {
1386 case AWS_S3_META_REQUEST_TYPE_GET_OBJECT: {
1387 struct aws_byte_cursor path_and_query;
1388
1389 if (aws_http_message_get_request_path(options->message, &path_and_query) == AWS_OP_SUCCESS) {
1390 /* If the initial request already has partNumber, the request is not
1391 * splittable(?). Treat it as a Default request.
1392 * TODO: Still need tests to verify that the request of a part is
1393 * splittable or not */
1394 struct aws_byte_cursor sub_string;
1395 AWS_ZERO_STRUCT(sub_string);
1396 /* The first split on '?' for path and query is path, the second is query */
1397 if (aws_byte_cursor_next_split(&path_and_query, '?', &sub_string) == true) {
1398 aws_byte_cursor_next_split(&path_and_query, '?', &sub_string);
1399 struct aws_uri_param param;
1400 AWS_ZERO_STRUCT(param);
1401 struct aws_byte_cursor part_number_query_str = aws_byte_cursor_from_c_str("partNumber");
1402 while (aws_query_string_next_param(sub_string, &param)) {
1403 if (aws_byte_cursor_eq(&param.key, &part_number_query_str)) {
1404 return aws_s3_meta_request_default_new(
1405 client->allocator,
1406 client,
1407 AWS_S3_REQUEST_TYPE_GET_OBJECT,
1408 0, /* Content length for request */
1409 false /*should_compute_content_md5*/,
1410 options);
1411 }
1412 }
1413 }
1414 }
1415 return aws_s3_meta_request_auto_ranged_get_new(
1416 client->allocator, client, part_size, part_size_set, options);
1417 }
1418 case AWS_S3_META_REQUEST_TYPE_PUT_OBJECT: {
1419 if (body_source_count == 0) {
1420 AWS_LOGF_ERROR(
1421 AWS_LS_S3_META_REQUEST,
1422 "Could not create auto-ranged-put meta request."
1423 " Body must be set via filepath, async stream, or body stream.");
1424 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1425 return NULL;
1426 }
1427
1428 if (options->resume_token == NULL) {
1429 uint64_t client_max_part_size = client->max_part_size;
1430
1431 if (part_size < g_s3_min_upload_part_size) {
1432 AWS_LOGF_WARN(
1433 AWS_LS_S3_META_REQUEST,
1434 "Config part size of %" PRIu64 " is less than the minimum upload part size of %" PRIu64
1435 ". Using to the minimum part-size for upload.",
1436 (uint64_t)part_size,
1437 (uint64_t)g_s3_min_upload_part_size);
1438
1439 part_size = g_s3_min_upload_part_size;
1440 }
1441
1442 if (client_max_part_size < (uint64_t)g_s3_min_upload_part_size) {
1443 AWS_LOGF_WARN(
1444 AWS_LS_S3_META_REQUEST,
1445 "Client config max part size of %" PRIu64
1446 " is less than the minimum upload part size of %" PRIu64
1447 ". Clamping to the minimum part-size for upload.",
1448 (uint64_t)client_max_part_size,
1449 (uint64_t)g_s3_min_upload_part_size);
1450
1451 client_max_part_size = (uint64_t)g_s3_min_upload_part_size;
1452 }
1453
1454 uint32_t num_parts = 0;
1455 if (content_length_found) {
1456 size_t out_part_size = 0;
1457 if (aws_s3_calculate_optimal_mpu_part_size_and_num_parts(
1458 content_length, part_size, client_max_part_size, &out_part_size, &num_parts)) {
1459 return NULL;
1460 }
1461 part_size = out_part_size;
1462 if (part_size != options->part_size && part_size != client->part_size) {
1463 /* If we already adjusted the part size, let's align the part size with expected alignment from
1464 * buffer pool. */
1465 if (num_parts > 2) {
1466 uint64_t aligned_part_size =
1467 aws_s3_buffer_pool_derive_aligned_buffer_size(client->buffer_pool, part_size);
1468 /* Incase of overflow, fallback to no alignment. */
1469 aligned_part_size = aligned_part_size > SIZE_MAX ? part_size : aligned_part_size;
1470 part_size = (size_t)aligned_part_size;
1471 /* update the number of parts as well. */
1472 num_parts = (uint32_t)(content_length / part_size);
1473 if ((content_length % part_size) > 0) {
1474 ++num_parts;
1475 }
1476 }
1477 AWS_LOGF_DEBUG(
1478 AWS_LS_S3_META_REQUEST,
1479 "The multipart upload part size has been adjusted to %zu",
1480 part_size);
1481 }
1482 }
1483
1484 /* Default to client level setting */
1485 uint64_t multipart_upload_threshold = client->multipart_upload_threshold;
1486 if (options->multipart_upload_threshold != 0) {
1487 /* If the threshold is set for the meta request, use it */
1488 multipart_upload_threshold = options->multipart_upload_threshold;
1489 } else if (options->part_size != 0) {
1490 /* If the threshold is not set, but the part size is set for the meta request, use it */
1491 multipart_upload_threshold = part_size;
1492 }
1493
1494 if (content_length_found && content_length <= multipart_upload_threshold) {
1495 return aws_s3_meta_request_default_new(
1496 client->allocator,
1497 client,
1498 AWS_S3_REQUEST_TYPE_PUT_OBJECT,
1499 content_length,
1500 client->compute_content_md5 == AWS_MR_CONTENT_MD5_ENABLED &&
1501 !aws_http_headers_has(initial_message_headers, g_content_md5_header_name),
1502 options);
1503 }
1504 return aws_s3_meta_request_auto_ranged_put_new(
1505 client->allocator, client, part_size, content_length_found, content_length, num_parts, options);
1506 } else { /* else using resume token */
1507 if (!content_length_found) {
1508 AWS_LOGF_ERROR(
1509 AWS_LS_S3_META_REQUEST,
1510 "Could not create auto-ranged-put resume meta request; content_length must be specified.");
1511 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1512 return NULL;
1513 }
1514
1515 /* don't pass part size and total num parts. constructor will pick it up from token */
1516 return aws_s3_meta_request_auto_ranged_put_new(
1517 client->allocator, client, 0, true, content_length, 0, options);
1518 }
1519 }
1520 case AWS_S3_META_REQUEST_TYPE_COPY_OBJECT: {
1521 return aws_s3_meta_request_copy_object_new(client->allocator, client, options);
1522 }
1523 case AWS_S3_META_REQUEST_TYPE_DEFAULT:
1524 if (options->operation_name.len == 0) {
1525 AWS_LOGF_ERROR(
1526 AWS_LS_S3_META_REQUEST, "Could not create Default Meta Request; operation name is required");
1527 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1528 return NULL;
1529 }
1530
1531 return aws_s3_meta_request_default_new(
1532 client->allocator,
1533 client,
1534 AWS_S3_REQUEST_TYPE_UNKNOWN,
1535 content_length,
1536 false /*should_compute_content_md5*/,
1537 options);
1538 default:
1539 AWS_FATAL_ASSERT(false);
1540 }
1541
1542 return NULL;
1543 }
1544
1545 static void s_s3_client_push_meta_request_synced(
1546 struct aws_s3_client *client,
1547 struct aws_s3_meta_request *meta_request) {
1548 AWS_PRECONDITION(client);
1549 AWS_PRECONDITION(meta_request);
1550 ASSERT_SYNCED_DATA_LOCK_HELD(client);
1551
1552 struct aws_s3_meta_request_work *meta_request_work =
1553 aws_mem_calloc(client->allocator, 1, sizeof(struct aws_s3_meta_request_work));
1554
1555 meta_request_work->meta_request = aws_s3_meta_request_acquire(meta_request);
1556 aws_linked_list_push_back(&client->synced_data.pending_meta_request_work, &meta_request_work->node);
1557 }
1558
1559 static void s_s3_client_schedule_process_work_synced(struct aws_s3_client *client) {
1560 AWS_PRECONDITION(client);
1561 AWS_PRECONDITION(client->vtable);
1562 AWS_PRECONDITION(client->vtable->schedule_process_work_synced);
1563
1564 ASSERT_SYNCED_DATA_LOCK_HELD(client);
1565
1566 client->vtable->schedule_process_work_synced(client);
1567 }
1568
1569 static void s_s3_client_schedule_process_work_synced_default(struct aws_s3_client *client) {
1570 ASSERT_SYNCED_DATA_LOCK_HELD(client);
1571
1572 if (client->synced_data.process_work_task_scheduled) {
1573 return;
1574 }
1575
1576 aws_task_init(
1577 &client->synced_data.process_work_task, s_s3_client_process_work_task, client, "s3_client_process_work_task");
1578
1579 aws_event_loop_schedule_task_now(client->process_work_event_loop, &client->synced_data.process_work_task);
1580
1581 client->synced_data.process_work_task_scheduled = true;
1582 }
1583
1584 /* Task function for trying to find a request that can be processed. */
1585 static void s_s3_client_trim_buffer_pool_task(struct aws_task *task, void *arg, enum aws_task_status task_status) {
1586 AWS_PRECONDITION(task);
1587 (void)task;
1588 (void)task_status;
1589
1590 if (task_status != AWS_TASK_STATUS_RUN_READY) {
1591 return;
1592 }
1593
1594 struct aws_s3_client *client = arg;
1595 AWS_PRECONDITION(client);
1596
1597 client->threaded_data.trim_buffer_pool_task_scheduled = false;
1598
1599 uint32_t num_reqs_in_flight = (uint32_t)aws_atomic_load_int(&client->stats.num_requests_in_flight);
1600
1601 if (num_reqs_in_flight == 0) {
1602 aws_s3_buffer_pool_trim(client->buffer_pool);
1603 }
1604 }
1605
1606 static void s_s3_client_schedule_buffer_pool_trim_synced(struct aws_s3_client *client) {
1607 ASSERT_SYNCED_DATA_LOCK_HELD(client);
1608
1609 if (client->threaded_data.trim_buffer_pool_task_scheduled) {
1610 return;
1611 }
1612
1613 uint32_t num_reqs_in_flight = (uint32_t)aws_atomic_load_int(&client->stats.num_requests_in_flight);
1614 if (num_reqs_in_flight > 0) {
1615 return;
1616 }
1617
1618 aws_task_init(
1619 &client->synced_data.trim_buffer_pool_task,
1620 s_s3_client_trim_buffer_pool_task,
1621 client,
1622 "s3_client_buffer_pool_trim_task");
1623
1624 uint64_t trim_time = 0;
1625 aws_event_loop_current_clock_time(client->process_work_event_loop, &trim_time);
1626 trim_time +=
1627 aws_timestamp_convert(s_buffer_pool_trim_time_offset_in_s, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL);
1628
1629 aws_event_loop_schedule_task_future(
1630 client->process_work_event_loop, &client->synced_data.trim_buffer_pool_task, trim_time);
1631
1632 client->threaded_data.trim_buffer_pool_task_scheduled = true;
1633 }
1634
1635 static void s_s3_endpoints_cleanup_task(struct aws_task *task, void *arg, enum aws_task_status task_status) {
1636 (void)task;
1637 (void)task_status;
1638
1639 struct aws_s3_client *client = arg;
1640 struct aws_array_list endpoints_to_release;
1641 aws_array_list_init_dynamic(&endpoints_to_release, client->allocator, 5, sizeof(struct aws_s3_endpoint *));
1642
1643 /* BEGIN CRITICAL SECTION */
1644 aws_s3_client_lock_synced_data(client);
1645 client->synced_data.endpoints_cleanup_task_scheduled = false;
1646
1647 for (struct aws_hash_iter iter = aws_hash_iter_begin(&client->synced_data.endpoints); !aws_hash_iter_done(&iter);
1648 aws_hash_iter_next(&iter)) {
1649 struct aws_s3_endpoint *endpoint = (struct aws_s3_endpoint *)iter.element.value;
1650 if (endpoint->client_synced_data.ref_count == 0) {
1651 aws_array_list_push_back(&endpoints_to_release, &endpoint);
1652 aws_hash_iter_delete(&iter, true);
1653 }
1654 }
1655
1656 /* END CRITICAL SECTION */
1657 aws_s3_client_unlock_synced_data(client);
1658
1659 /* now destroy all endpoints without holding the lock */
1660 size_t list_size = aws_array_list_length(&endpoints_to_release);
1661 for (size_t i = 0; i < list_size; ++i) {
1662 struct aws_s3_endpoint *endpoint;
1663 aws_array_list_get_at(&endpoints_to_release, &endpoint, i);
1664 aws_s3_endpoint_destroy(endpoint);
1665 }
1666
1667 /* Clean up the array list */
1668 aws_array_list_clean_up(&endpoints_to_release);
1669
1670 aws_s3_client_schedule_process_work(client);
1671 }
1672
1673 static void s_s3_client_schedule_endpoints_cleanup_synced(struct aws_s3_client *client) {
1674 ASSERT_SYNCED_DATA_LOCK_HELD(client);
1675 if (client->synced_data.endpoints_cleanup_task_scheduled) {
1676 return;
1677 }
1678 client->synced_data.endpoints_cleanup_task_scheduled = true;
1679 uint64_t now_ns = 0;
1680 aws_event_loop_current_clock_time(client->process_work_event_loop, &now_ns);
1681 aws_event_loop_schedule_task_future(
1682 client->process_work_event_loop,
1683 &client->synced_data.endpoints_cleanup_task,
1684 now_ns +
1685 aws_timestamp_convert(s_endpoints_cleanup_time_offset_in_s, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL));
1686 }
1687
1688 void aws_s3_client_schedule_process_work(struct aws_s3_client *client) {
1689 AWS_PRECONDITION(client);
1690
1691 /* BEGIN CRITICAL SECTION */
1692 {
1693 aws_s3_client_lock_synced_data(client);
1694 s_s3_client_schedule_process_work_synced(client);
1695 aws_s3_client_unlock_synced_data(client);
1696 }
1697 /* END CRITICAL SECTION */
1698 }
1699
1700 static void s_s3_client_remove_meta_request_threaded(
1701 struct aws_s3_client *client,
1702 struct aws_s3_meta_request *meta_request) {
1703 AWS_PRECONDITION(client);
1704 AWS_PRECONDITION(meta_request);
1705 (void)client;
1706
1707 aws_linked_list_remove(&meta_request->client_process_work_threaded_data.node);
1708 meta_request->client_process_work_threaded_data.scheduled = false;
1709 aws_s3_meta_request_release(meta_request);
1710 }
1711
1712 /* Task function for trying to find a request that can be processed. */
1713 static void s_s3_client_process_work_task(struct aws_task *task, void *arg, enum aws_task_status task_status) {
1714 AWS_PRECONDITION(task);
1715 (void)task;
1716 (void)task_status;
1717
1718 /* Client keeps a reference to the event loop group; a 'canceled' status should not happen.*/
1719 AWS_ASSERT(task_status == AWS_TASK_STATUS_RUN_READY);
1720
1721 struct aws_s3_client *client = arg;
1722 AWS_PRECONDITION(client);
1723 AWS_PRECONDITION(client->vtable);
1724 AWS_PRECONDITION(client->vtable->process_work);
1725
1726 client->vtable->process_work(client);
1727 }
1728
1729 static void s_s3_client_process_work_default(struct aws_s3_client *client) {
1730 AWS_PRECONDITION(client);
1731 AWS_PRECONDITION(client->vtable);
1732 AWS_PRECONDITION(client->vtable->finish_destroy);
1733
1734 struct aws_linked_list meta_request_work_list;
1735 aws_linked_list_init(&meta_request_work_list);
1736
1737 /*******************/
1738 /* Step 1: Move relevant data into thread local memory and schedule cleanups */
1739 /*******************/
1740 AWS_LOGF_DEBUG(
1741 AWS_LS_S3_CLIENT,
1742 "id=%p s_s3_client_process_work_default - Moving relevant synced_data into threaded_data.",
1743 (void *)client);
1744
1745 /* BEGIN CRITICAL SECTION */
1746 aws_s3_client_lock_synced_data(client);
1747 /* Once we exit this mutex, someone can reschedule this task. */
1748 client->synced_data.process_work_task_scheduled = false;
1749 client->synced_data.process_work_task_in_progress = true;
1750
1751 if (client->synced_data.active) {
1752 s_s3_client_schedule_buffer_pool_trim_synced(client);
1753 s_s3_client_schedule_endpoints_cleanup_synced(client);
1754 } else if (client->synced_data.endpoints_cleanup_task_scheduled) {
1755 client->synced_data.endpoints_cleanup_task_scheduled = false;
1756 /* Cancel the task to run it sync */
1757 aws_s3_client_unlock_synced_data(client);
1758 aws_event_loop_cancel_task(client->process_work_event_loop, &client->synced_data.endpoints_cleanup_task);
1759 aws_s3_client_lock_synced_data(client);
1760 }
1761
1762 aws_linked_list_swap_contents(&meta_request_work_list, &client->synced_data.pending_meta_request_work);
1763
1764 uint32_t num_requests_queued =
1765 aws_s3_client_queue_requests_threaded(client, &client->synced_data.prepared_requests, false);
1766
1767 {
1768 int sub_result = aws_sub_u32_checked(
1769 client->threaded_data.num_requests_being_prepared,
1770 num_requests_queued,
1771 &client->threaded_data.num_requests_being_prepared);
1772
1773 AWS_ASSERT(sub_result == AWS_OP_SUCCESS);
1774 (void)sub_result;
1775 }
1776
1777 {
1778 int sub_result = aws_sub_u32_checked(
1779 client->threaded_data.num_requests_being_prepared,
1780 client->synced_data.num_failed_prepare_requests,
1781 &client->threaded_data.num_requests_being_prepared);
1782
1783 client->synced_data.num_failed_prepare_requests = 0;
1784
1785 AWS_ASSERT(sub_result == AWS_OP_SUCCESS);
1786 (void)sub_result;
1787 }
1788
1789 uint32_t num_endpoints_in_table = (uint32_t)aws_hash_table_get_entry_count(&client->synced_data.endpoints);
1790 uint32_t num_endpoints_allocated = client->synced_data.num_endpoints_allocated;
1791
1792 aws_s3_client_unlock_synced_data(client);
1793 /* END CRITICAL SECTION */
1794
1795 /*******************/
1796 /* Step 2: Push meta requests into the thread local list if they haven't already been scheduled. */
1797 /*******************/
1798 AWS_LOGF_DEBUG(
1799 AWS_LS_S3_CLIENT, "id=%p s_s3_client_process_work_default - Processing any new meta requests.", (void *)client);
1800
1801 while (!aws_linked_list_empty(&meta_request_work_list)) {
1802 struct aws_linked_list_node *node = aws_linked_list_pop_back(&meta_request_work_list);
1803 struct aws_s3_meta_request_work *meta_request_work =
1804 AWS_CONTAINER_OF(node, struct aws_s3_meta_request_work, node);
1805
1806 AWS_FATAL_ASSERT(meta_request_work != NULL);
1807 AWS_FATAL_ASSERT(meta_request_work->meta_request != NULL);
1808
1809 struct aws_s3_meta_request *meta_request = meta_request_work->meta_request;
1810
1811 if (!meta_request->client_process_work_threaded_data.scheduled) {
1812 aws_linked_list_push_back(
1813 &client->threaded_data.meta_requests, &meta_request->client_process_work_threaded_data.node);
1814
1815 meta_request->client_process_work_threaded_data.scheduled = true;
1816 } else {
1817 meta_request = aws_s3_meta_request_release(meta_request);
1818 }
1819
1820 aws_mem_release(client->allocator, meta_request_work);
1821 }
1822
1823 /*******************/
1824 /* Step 3: Update relevant meta requests and connections. */
1825 /*******************/
1826 {
1827 AWS_LOGF_DEBUG(AWS_LS_S3_CLIENT, "id=%p Updating meta requests.", (void *)client);
1828 aws_s3_client_update_meta_requests_threaded(client);
1829
1830 AWS_LOGF_DEBUG(
1831 AWS_LS_S3_CLIENT, "id=%p Updating connections, assigning requests where possible.", (void *)client);
1832 aws_s3_client_update_connections_threaded(client);
1833 }
1834
1835 /*******************/
1836 /* Step 4: Log client stats. */
1837 /*******************/
1838 {
1839 uint32_t num_requests_tracked_requests = (uint32_t)aws_atomic_load_int(&client->stats.num_requests_in_flight);
1840
1841 uint32_t num_auto_ranged_get_network_io =
1842 s_s3_client_get_num_requests_network_io(client, AWS_S3_META_REQUEST_TYPE_GET_OBJECT);
1843 uint32_t num_auto_ranged_put_network_io =
1844 s_s3_client_get_num_requests_network_io(client, AWS_S3_META_REQUEST_TYPE_PUT_OBJECT);
1845 uint32_t num_auto_default_network_io =
1846 s_s3_client_get_num_requests_network_io(client, AWS_S3_META_REQUEST_TYPE_DEFAULT);
1847
1848 uint32_t num_requests_network_io =
1849 s_s3_client_get_num_requests_network_io(client, AWS_S3_META_REQUEST_TYPE_MAX);
1850
1851 uint32_t num_requests_stream_queued_waiting =
1852 (uint32_t)aws_atomic_load_int(&client->stats.num_requests_stream_queued_waiting);
1853
1854 uint32_t num_requests_being_prepared = client->threaded_data.num_requests_being_prepared;
1855
1856 uint32_t num_requests_streaming_response =
1857 (uint32_t)aws_atomic_load_int(&client->stats.num_requests_streaming_response);
1858
1859 uint32_t total_approx_requests = num_requests_network_io + num_requests_stream_queued_waiting +
1860 num_requests_streaming_response + num_requests_being_prepared +
1861 client->threaded_data.request_queue_size;
1862 AWS_LOGF(
1863 s_log_level_client_stats,
1864 AWS_LS_S3_CLIENT_STATS,
1865 "id=%p Requests-in-flight(approx/exact):%d/%d Requests-preparing:%d Requests-queued:%d "
1866 "Requests-network(get/put/default/total):%d/%d/%d/%d Requests-streaming-waiting:%d "
1867 "Requests-streaming-response:%d "
1868 " Endpoints(in-table/allocated):%d/%d",
1869 (void *)client,
1870 total_approx_requests,
1871 num_requests_tracked_requests,
1872 num_requests_being_prepared,
1873 client->threaded_data.request_queue_size,
1874 num_auto_ranged_get_network_io,
1875 num_auto_ranged_put_network_io,
1876 num_auto_default_network_io,
1877 num_requests_network_io,
1878 num_requests_stream_queued_waiting,
1879 num_requests_streaming_response,
1880 num_endpoints_in_table,
1881 num_endpoints_allocated);
1882 }
1883
1884 /*******************/
1885 /* Step 5: Check for client shutdown. */
1886 /*******************/
1887 {
1888 /* BEGIN CRITICAL SECTION */
1889 aws_s3_client_lock_synced_data(client);
1890 client->synced_data.process_work_task_in_progress = false;
1891
1892 /* This flag should never be set twice. If it was, that means a double-free could occur.*/
1893 AWS_ASSERT(!client->synced_data.finish_destroy);
1894
1895 bool finish_destroy =
1896 client->synced_data.active == false && client->synced_data.start_destroy_executing == false &&
1897 client->synced_data.body_streaming_elg_allocated == false &&
1898 client->synced_data.process_work_task_scheduled == false &&
1899 client->synced_data.process_work_task_in_progress == false &&
1900 client->synced_data.s3express_provider_active == false && client->synced_data.num_endpoints_allocated == 0;
1901
1902 client->synced_data.finish_destroy = finish_destroy;
1903
1904 if (!client->synced_data.active) {
1905 AWS_LOGF_DEBUG(
1906 AWS_LS_S3_CLIENT,
1907 "id=%p Client shutdown progress: starting_destroy_executing=%d body_streaming_elg_allocated=%d "
1908 "process_work_task_scheduled=%d process_work_task_in_progress=%d num_endpoints_allocated=%d "
1909 "s3express_provider_active=%d finish_destroy=%d",
1910 (void *)client,
1911 (int)client->synced_data.start_destroy_executing,
1912 (int)client->synced_data.body_streaming_elg_allocated,
1913 (int)client->synced_data.process_work_task_scheduled,
1914 (int)client->synced_data.process_work_task_in_progress,
1915 (int)client->synced_data.num_endpoints_allocated,
1916 (int)client->synced_data.s3express_provider_active,
1917 (int)client->synced_data.finish_destroy);
1918 }
1919
1920 aws_s3_client_unlock_synced_data(client);
1921 /* END CRITICAL SECTION */
1922
1923 if (finish_destroy) {
1924 client->vtable->finish_destroy(client);
1925 }
1926 }
1927 }
1928
1929 static void s_s3_client_prepare_callback_queue_request(
1930 struct aws_s3_meta_request *meta_request,
1931 struct aws_s3_request *request,
1932 int error_code,
1933 void *user_data);
1934
1935 static bool s_s3_client_should_update_meta_request(
1936 struct aws_s3_client *client,
1937 struct aws_s3_meta_request *meta_request,
1938 uint32_t num_requests_in_flight,
1939 uint32_t num_requests_streaming,
1940 const uint32_t max_requests_in_flight,
1941 const uint32_t max_requests_prepare) {
1942
1943 /* CreateSession has high priority to bypass the checks. */
1944 if (meta_request->type == AWS_S3_META_REQUEST_TYPE_DEFAULT) {
1945 struct aws_s3_meta_request_default *meta_request_default = meta_request->impl;
1946 if (meta_request_default->request_type == AWS_S3_REQUEST_TYPE_CREATE_SESSION) {
1947 return true;
1948 }
1949 }
1950
1951 /**
1952 * If number of being-prepared + already-prepared-and-queued + num-requests-streaming-request-body requests is more
1953 * than the max that can be in the preparation stage.
1954 *
1955 * num-requests-streaming-request-body tracks the requests streaming the request body after the request starts.
1956 * Limit the number of request preparing based on it because the requests are also reading from the source. Avoiding
1957 * more than expected requests to read from the source.
1958 *
1959 * Or total number of requests tracked by the client is more than the max tracked ("in flight") requests.
1960 *
1961 * We cannot create more requests for this meta request.
1962 */
1963 if ((client->threaded_data.num_requests_being_prepared + client->threaded_data.request_queue_size +
1964 num_requests_streaming) >= max_requests_prepare) {
1965 return false;
1966 }
1967 if (num_requests_in_flight >= max_requests_in_flight) {
1968 return false;
1969 }
1970
1971 /* If this particular endpoint doesn't have any known addresses yet, then we don't want to go full speed in
1972 * ramping up requests just yet. If there is already enough in the queue for one address (even if those
1973 * aren't for this particular endpoint) we skip over this meta request for now. */
1974 struct aws_s3_endpoint *endpoint = meta_request->endpoint;
1975 AWS_ASSERT(endpoint != NULL);
1976 AWS_ASSERT(client->vtable->get_host_address_count);
1977 size_t num_known_vips = client->vtable->get_host_address_count(
1978 client->client_bootstrap->host_resolver, endpoint->host_name, AWS_GET_HOST_ADDRESS_COUNT_RECORD_TYPE_A);
1979 if (num_known_vips == 0 && (client->threaded_data.num_requests_being_prepared +
1980 client->threaded_data.request_queue_size) >= g_min_num_connections) {
1981 return false;
1982 }
1983
1984 /* This is not 100% thread safe, but prepare a bit more for the meta request level won't actually hurt. */
1985 size_t specific_request_being_prepared = aws_atomic_load_int(&meta_request->num_request_being_prepared);
1986 if (specific_request_being_prepared >= aws_s3_client_get_max_active_connections(client, meta_request)) {
1987 /* Don't prepare more than it's allowed for the meta request */
1988 return false;
1989 }
1990
1991 /* Nothing blocks the meta request to create more requests */
1992 return true;
1993 }
1994
1995 struct aws_s3_reserve_memory_payload {
1996 struct aws_allocator *allocator;
1997 struct aws_s3_request *request;
1998 struct aws_future_s3_buffer_ticket *buffer_future;
1999 aws_s3_meta_request_prepare_request_callback_fn *callback;
2000 void *user_data;
2001 };
2002
2003 static void s_s3_prepare_acquire_mem_callback_and_destroy(
2004 struct aws_s3_reserve_memory_payload *payload,
2005 int error_code) {
2006 AWS_PRECONDITION(payload);
2007 AWS_PRECONDITION(payload->request);
2008
2009 struct aws_s3_meta_request *meta_request = payload->request->meta_request;
2010 AWS_PRECONDITION(meta_request);
2011
2012 if (error_code) {
2013 AWS_LOGF_ERROR(
2014 AWS_LS_S3_META_REQUEST,
2015 "id=%p Could not prepare request %p due to error %d (%s).",
2016 (void *)meta_request,
2017 (void *)payload->request,
2018 error_code,
2019 aws_error_str(error_code));
2020
2021 /* BEGIN CRITICAL SECTION */
2022 aws_s3_meta_request_lock_synced_data(meta_request);
2023 aws_linked_list_remove(&payload->request->pending_buffer_future_list_node);
2024 payload->request->synced_data.buffer_future =
2025 aws_future_s3_buffer_ticket_release(payload->request->synced_data.buffer_future);
2026 aws_s3_meta_request_set_fail_synced(meta_request, payload->request, error_code);
2027 aws_s3_meta_request_unlock_synced_data(meta_request);
2028 /* END CRITICAL SECTION */
2029 }
2030
2031 if (payload->callback != NULL) {
2032 payload->callback(meta_request, payload->request, error_code, payload->user_data);
2033 }
2034
2035 aws_future_s3_buffer_ticket_release(payload->buffer_future);
2036 aws_mem_release(payload->allocator, payload);
2037 }
2038
2039 /* Drain the pending_put_prepare_queue in part-number order. Only dispatches requests
2040 * whose part_number matches next_part_to_prepare. Called on io_event_loop thread. */
2041 static void s_drain_pending_put_prepare_queue(struct aws_s3_meta_request *meta_request) {
2042 struct aws_priority_queue *queue = &meta_request->io_threaded_data.pending_put_prepare_queue;
2043
2044 while (aws_priority_queue_size(queue) > 0) {
2045
2046 struct aws_s3_pending_prepare_entry *top = NULL;
2047 aws_priority_queue_top(queue, (void **)&top);
2048
2049 if (top->request->part_number != meta_request->io_threaded_data.next_put_part_to_prepare) {
2050 AWS_LOGF_TRACE(
2051 AWS_LS_S3_META_REQUEST,
2052 "id=%p Exiting put prepare queue drain early because top part number %" PRIu32
2053 " is different from next part %" PRIu32 ".",
2054 (void *)meta_request,
2055 top->request->part_number,
2056 meta_request->io_threaded_data.next_put_part_to_prepare);
2057
2058 break;
2059 }
2060
2061 struct aws_s3_pending_prepare_entry entry;
2062 aws_priority_queue_pop(queue, &entry);
2063 ++meta_request->io_threaded_data.next_put_part_to_prepare;
2064
2065 aws_s3_meta_request_prepare_request(meta_request, entry.request, entry.callback, entry.user_data);
2066 }
2067 }
2068
2069 /* Force-drain all entries from pending_put_prepare_queue regardless of ordering.
2070 * Called when a buffer reservation fails and the missing part will never arrive,
2071 * which would otherwise leave queued requests stuck forever. Releases tickets and
2072 * fails each request through the normal callback. */
2073 static void s_force_drain_pending_put_prepare_queue(struct aws_s3_meta_request *meta_request, int error_code) {
2074 struct aws_priority_queue *queue = &meta_request->io_threaded_data.pending_put_prepare_queue;
2075
2076 while (aws_priority_queue_size(queue) > 0) {
2077 struct aws_s3_pending_prepare_entry entry;
2078 aws_priority_queue_pop(queue, &entry);
2079
2080 aws_s3_buffer_ticket_release(entry.request->ticket);
2081 entry.request->ticket = NULL;
2082
2083 entry.callback(meta_request, entry.request, error_code, entry.user_data);
2084 }
2085 }
2086
2087 static void s_on_pool_buffer_reserved(void *user_data) {
2088 struct aws_s3_reserve_memory_payload *payload = user_data;
2089 AWS_PRECONDITION(payload);
2090
2091 struct aws_s3_request *request = payload->request;
2092 AWS_PRECONDITION(request);
2093
2094 struct aws_s3_meta_request *meta_request = request->meta_request;
2095 AWS_PRECONDITION(meta_request);
2096
2097 if (request->send_data.metrics) {
2098 struct aws_s3_request_metrics *metric = request->send_data.metrics;
2099 aws_high_res_clock_get_ticks((uint64_t *)&metric->time_metrics.mem_acquire_end_timestamp_ns);
2100 AWS_ASSERT(metric->time_metrics.mem_acquire_start_timestamp_ns != 0);
2101 metric->time_metrics.mem_acquire_duration_ns =
2102 metric->time_metrics.mem_acquire_end_timestamp_ns - metric->time_metrics.mem_acquire_start_timestamp_ns;
2103 }
2104
2105 struct aws_future_s3_buffer_ticket *future_ticket = payload->buffer_future;
2106
2107 int error_code = aws_future_s3_buffer_ticket_get_error(future_ticket);
2108 if (error_code != AWS_ERROR_SUCCESS) {
2109 AWS_LOGF_ERROR(
2110 AWS_LS_S3_META_REQUEST,
2111 "id=%p Could not allocate buffer for request with tag %d for the meta request.",
2112 (void *)meta_request,
2113 request->request_tag);
2114
2115 s_s3_prepare_acquire_mem_callback_and_destroy(payload, AWS_ERROR_S3_BUFFER_ALLOCATION_FAILED);
2116 s_force_drain_pending_put_prepare_queue(meta_request, AWS_ERROR_S3_CANCELED);
2117 return;
2118 }
2119
2120 request->ticket = aws_future_s3_buffer_ticket_get_result_by_move(future_ticket);
2121
2122 /* BEGIN CRITICAL SECTION */
2123 {
2124 aws_s3_meta_request_lock_synced_data(meta_request);
2125 AWS_FATAL_ASSERT(request->synced_data.buffer_future);
2126 aws_linked_list_remove(&request->pending_buffer_future_list_node);
2127 request->synced_data.buffer_future = aws_future_s3_buffer_ticket_release(request->synced_data.buffer_future);
2128 aws_s3_meta_request_unlock_synced_data(meta_request);
2129 }
2130 /* END CRITICAL SECTION */
2131
2132 /*
2133 * Note: on why following check excludes everything, but put object type.
2134 * Specific problem is with get object, which has complex logic of sometimes trying with bad range and
2135 * if that fails trying with part number, etc... that can throw off the counter for which part num is expected next
2136 * and hang the meta request.
2137 * Lets play safe for now and only include puts in this logic.
2138 * We can revisit whether it makes sense for get and add it later.
2139 */
2140
2141 bool needs_ordered_prepare = request->part_number > 0 &&
2142 meta_request->type == AWS_S3_META_REQUEST_TYPE_PUT_OBJECT &&
2143 !meta_request->request_body_parallel_stream;
2144
2145 if (needs_ordered_prepare) {
2146 /* Insert into priority queue and drain in order to ensure sequential
2147 * stream reads happen in part-number order. */
2148 struct aws_s3_pending_prepare_entry entry = {
2149 .request = request,
2150 .callback = payload->callback,
2151 .user_data = payload->user_data,
2152 };
2153 aws_priority_queue_push(&meta_request->io_threaded_data.pending_put_prepare_queue, &entry);
2154
2155 aws_future_s3_buffer_ticket_release(payload->buffer_future);
2156 aws_mem_release(payload->allocator, payload);
2157
2158 s_drain_pending_put_prepare_queue(meta_request);
2159 } else {
2160 aws_s3_meta_request_prepare_request(request->meta_request, request, payload->callback, payload->user_data);
2161 aws_future_s3_buffer_ticket_release(payload->buffer_future);
2162 aws_mem_release(payload->allocator, payload);
2163 }
2164
2165 return;
2166 }
2167
2168 void s_acquire_mem_and_prepare_request(
2169 struct aws_s3_client *client,
2170 struct aws_s3_request *request,
2171 aws_s3_meta_request_prepare_request_callback_fn *callback,
2172 void *user_data) {
2173
2174 size_t request_size = (size_t)aws_s3_request_get_payload_size(request);
2175 AWS_ASSERT(request_size != 0); /* Note: 0 request size is invalid in all cases. */
2176
2177 if (request->ticket == NULL && request->should_allocate_buffer_from_pool && request_size > 0) {
2178
2179 if (request->send_data.metrics) {
2180 struct aws_s3_request_metrics *metric = request->send_data.metrics;
2181 metric->crt_info_metrics.memory_allocated_from_pool = true;
2182 aws_high_res_clock_get_ticks((uint64_t *)&metric->time_metrics.mem_acquire_start_timestamp_ns);
2183 }
2184
2185 struct aws_allocator *allocator = request->allocator;
2186 struct aws_s3_meta_request *meta_request = request->meta_request;
2187
2188 struct aws_s3_buffer_pool_reserve_meta meta = {
2189 .client = client,
2190 .meta_request = meta_request,
2191 .size = request_size,
2192 };
2193
2194 struct aws_s3_reserve_memory_payload *payload =
2195 aws_mem_calloc(allocator, 1, sizeof(struct aws_s3_reserve_memory_payload));
2196
2197 payload->allocator = allocator;
2198 payload->request = request;
2199 payload->callback = callback;
2200 payload->user_data = user_data;
2201 payload->buffer_future = aws_s3_buffer_pool_reserve(request->meta_request->client->buffer_pool, meta);
2202
2203 /* BEGIN CRITICAL SECTION */
2204 {
2205 aws_s3_meta_request_lock_synced_data(meta_request);
2206 aws_linked_list_push_back(
2207 &meta_request->synced_data.pending_buffer_futures, &request->pending_buffer_future_list_node);
2208 request->synced_data.buffer_future = aws_future_s3_buffer_ticket_acquire(payload->buffer_future);
2209 aws_s3_meta_request_unlock_synced_data(meta_request);
2210 }
2211 /* END CRITICAL SECTION */
2212
2213 /* Note: run callback async on event loop. this is done to avoid any deadlocks between cancelling
2214 which requires a lock on meta request and buffer acquire callback which also requires a lock. */
2215 aws_future_s3_buffer_ticket_register_event_loop_callback(
2216 payload->buffer_future, meta_request->io_event_loop, s_on_pool_buffer_reserved, payload);
2217 return;
2218 }
2219
2220 aws_s3_meta_request_prepare_request(request->meta_request, request, callback, user_data);
2221 }
2222
2223 void aws_s3_client_update_meta_requests_threaded(struct aws_s3_client *client) {
2224 AWS_PRECONDITION(client);
2225
2226 const uint32_t max_requests_in_flight = aws_s3_client_get_max_requests_in_flight(client);
2227 const uint32_t max_requests_prepare = aws_s3_client_get_max_requests_prepare(client);
2228
2229 struct aws_linked_list meta_requests_work_remaining;
2230 aws_linked_list_init(&meta_requests_work_remaining);
2231
2232 uint32_t num_requests_in_flight = (uint32_t)aws_atomic_load_int(&client->stats.num_requests_in_flight);
2233 uint32_t num_requests_streaming = (uint32_t)aws_atomic_load_int(&client->stats.num_requests_streaming_request_body);
2234
2235 const uint32_t pass_flags[] = {
2236 AWS_S3_META_REQUEST_UPDATE_FLAG_CONSERVATIVE,
2237 0,
2238 };
2239
2240 const uint32_t num_passes = AWS_ARRAY_SIZE(pass_flags);
2241
2242 for (uint32_t pass_index = 0; pass_index < num_passes; ++pass_index) {
2243
2244 /**
2245 * Iterate through the meta requests to update meta requests and get new requests that can then be prepared
2246 * (reading from any streams, signing, etc.) for sending.
2247 */
2248 while (!aws_linked_list_empty(&client->threaded_data.meta_requests)) {
2249
2250 struct aws_linked_list_node *meta_request_node =
2251 aws_linked_list_begin(&client->threaded_data.meta_requests);
2252 struct aws_s3_meta_request *meta_request =
2253 AWS_CONTAINER_OF(meta_request_node, struct aws_s3_meta_request, client_process_work_threaded_data);
2254
2255 if (!s_s3_client_should_update_meta_request(
2256 client,
2257 meta_request,
2258 num_requests_in_flight,
2259 num_requests_streaming,
2260 max_requests_in_flight,
2261 max_requests_prepare)) {
2262
2263 /* Move the meta request to be processed from next loop. */
2264 aws_linked_list_remove(&meta_request->client_process_work_threaded_data.node);
2265 aws_linked_list_push_back(
2266 &meta_requests_work_remaining, &meta_request->client_process_work_threaded_data.node);
2267 continue;
2268 }
2269
2270 struct aws_s3_request *request = NULL;
2271
2272 /* Try to grab the next request from the meta request. */
2273 bool work_remaining = aws_s3_meta_request_update(meta_request, pass_flags[pass_index], &request);
2274
2275 if (work_remaining) {
2276 /* If there is work remaining, but we didn't get a request back, take the meta request out of the
2277 * list so that we don't use it again during this function, with the intention of putting it back in
2278 * the list before this function ends. */
2279 if (request == NULL) {
2280 aws_linked_list_remove(&meta_request->client_process_work_threaded_data.node);
2281 aws_linked_list_push_back(
2282 &meta_requests_work_remaining, &meta_request->client_process_work_threaded_data.node);
2283 } else {
2284 request->tracked_by_client = true;
2285
2286 ++client->threaded_data.num_requests_being_prepared;
2287 aws_atomic_fetch_add(&meta_request->num_request_being_prepared, 1);
2288
2289 num_requests_in_flight =
2290 (uint32_t)aws_atomic_fetch_add(&client->stats.num_requests_in_flight, 1) + 1;
2291
2292 /**
2293 * When upload with streaming, the prepare stage will not read into buffer.
2294 * But it should prevent more requests to be preapred so that the request will not staying in the
2295 * queue to wait for the connection available. Prevents the credentials to be expired during waiting
2296 * for too long.
2297 */
2298 if (meta_request->fio_opts.should_stream) {
2299 /* If the request is a streaming request, update the states to track the request that is
2300 * streaming request body. */
2301 aws_atomic_fetch_add(&client->stats.num_requests_streaming_request_body, 1);
2302 }
2303
2304 s_acquire_mem_and_prepare_request(
2305 client, request, s_s3_client_prepare_callback_queue_request, client);
2306 }
2307 } else {
2308 s_s3_client_remove_meta_request_threaded(client, meta_request);
2309 }
2310 }
2311
2312 aws_linked_list_move_all_front(&client->threaded_data.meta_requests, &meta_requests_work_remaining);
2313 }
2314 }
2315
2316 static void s_s3_client_meta_request_finished_request(
2317 struct aws_s3_client *client,
2318 struct aws_s3_meta_request *meta_request,
2319 struct aws_s3_request *request,
2320 int error_code) {
2321 AWS_PRECONDITION(client);
2322 AWS_PRECONDITION(request);
2323
2324 if (request->tracked_by_client) {
2325 /* BEGIN CRITICAL SECTION */
2326 aws_s3_client_lock_synced_data(client);
2327 aws_atomic_fetch_sub(&client->stats.num_requests_in_flight, 1);
2328 if (meta_request->fio_opts.should_stream) {
2329 aws_atomic_fetch_sub(&client->stats.num_requests_streaming_request_body, 1);
2330 }
2331 s_s3_client_schedule_process_work_synced(client);
2332 aws_s3_client_unlock_synced_data(client);
2333 /* END CRITICAL SECTION */
2334 }
2335 aws_s3_meta_request_finished_request(meta_request, request, error_code);
2336 }
2337
2338 static void s_s3_client_prepare_callback_queue_request(
2339 struct aws_s3_meta_request *meta_request,
2340 struct aws_s3_request *request,
2341 int error_code,
2342 void *user_data) {
2343 AWS_PRECONDITION(meta_request);
2344 AWS_PRECONDITION(request);
2345
2346 struct aws_s3_client *client = user_data;
2347 AWS_PRECONDITION(client);
2348
2349 if (error_code != AWS_ERROR_SUCCESS) {
2350 s_s3_client_meta_request_finished_request(client, meta_request, request, error_code);
2351 request = aws_s3_request_release(request);
2352 }
2353
2354 aws_atomic_fetch_sub(&meta_request->num_request_being_prepared, 1);
2355 /* BEGIN CRITICAL SECTION */
2356 {
2357 aws_s3_client_lock_synced_data(client);
2358
2359 if (error_code == AWS_ERROR_SUCCESS) {
2360 aws_linked_list_push_back(&client->synced_data.prepared_requests, &request->node);
2361 } else {
2362 ++client->synced_data.num_failed_prepare_requests;
2363 }
2364
2365 s_s3_client_schedule_process_work_synced(client);
2366 aws_s3_client_unlock_synced_data(client);
2367 }
2368 /* END CRITICAL SECTION */
2369 }
2370
2371 void aws_s3_client_update_connections_threaded(struct aws_s3_client *client) {
2372 AWS_PRECONDITION(client);
2373 AWS_PRECONDITION(client->vtable);
2374
2375 struct aws_linked_list left_over_requests;
2376 aws_linked_list_init(&left_over_requests);
2377 uint32_t client_max_active_connections = aws_s3_client_get_max_active_connections(client, NULL);
2378 uint32_t num_requests_network_io = s_s3_client_get_num_requests_network_io(client, AWS_S3_META_REQUEST_TYPE_MAX);
2379 bool queue_is_empty = aws_linked_list_empty(&client->threaded_data.request_queue);
2380
2381 while (num_requests_network_io < client_max_active_connections && !queue_is_empty) {
2382
2383 struct aws_s3_request *request = aws_s3_client_dequeue_request_threaded(client);
2384 struct aws_s3_meta_request *meta_request = request->meta_request;
2385 const uint32_t max_active_connections = aws_s3_client_get_max_active_connections(client, meta_request);
2386 if (request->is_noop) {
2387 /* If request is no-op, finishes and cleans up the request */
2388 s_s3_client_meta_request_finished_request(client, meta_request, request, AWS_ERROR_SUCCESS);
2389 request = aws_s3_request_release(request);
2390 } else if (!request->always_send && aws_s3_meta_request_has_finish_result(meta_request)) {
2391 /* Unless the request is marked "always send", if this meta request has a finish result, then finish the
2392 * request now and release it. */
2393 /* Update the error code for the metrics of the request here since we never acquire/release a connection */
2394 request->send_data.metrics->crt_info_metrics.error_code = AWS_ERROR_S3_CANCELED;
2395
2396 /* Record end times as well */
2397 aws_high_res_clock_get_ticks(
2398 (uint64_t *)&request->send_data.metrics->time_metrics.s3_request_last_attempt_end_timestamp_ns);
2399 request->send_data.metrics->time_metrics.s3_request_total_duration_ns =
2400 request->send_data.metrics->time_metrics.s3_request_last_attempt_end_timestamp_ns -
2401 request->send_data.metrics->time_metrics.s3_request_first_attempt_start_timestamp_ns;
2402
2403 s_s3_client_meta_request_finished_request(client, meta_request, request, AWS_ERROR_S3_CANCELED);
2404 request = aws_s3_request_release(request);
2405 } else if ((uint32_t)aws_atomic_load_int(&meta_request->num_requests_network) < max_active_connections) {
2406 /* Make sure it's above the max request level limitation. */
2407 s_s3_client_create_connection_for_request(client, request);
2408 } else {
2409 /* Push the request into the left-over list to be used in a future call of this function. */
2410 aws_linked_list_push_back(&left_over_requests, &request->node);
2411 }
2412 client_max_active_connections = aws_s3_client_get_max_active_connections(client, NULL);
2413 num_requests_network_io = s_s3_client_get_num_requests_network_io(client, AWS_S3_META_REQUEST_TYPE_MAX);
2414 queue_is_empty = aws_linked_list_empty(&client->threaded_data.request_queue);
2415 }
2416
2417 aws_s3_client_queue_requests_threaded(client, &left_over_requests, true);
2418 }
2419
2420 static void s_s3_client_acquired_retry_token(
2421 struct aws_retry_strategy *retry_strategy,
2422 int error_code,
2423 struct aws_retry_token *token,
2424 void *user_data);
2425
2426 static void s_s3_client_retry_ready(struct aws_retry_token *token, int error_code, void *user_data);
2427
2428 static void s_s3_client_create_connection_for_request_default(
2429 struct aws_s3_client *client,
2430 struct aws_s3_request *request);
2431
2432 static void s_s3_client_create_connection_for_request(struct aws_s3_client *client, struct aws_s3_request *request) {
2433 AWS_PRECONDITION(client);
2434 AWS_PRECONDITION(client->vtable);
2435
2436 if (client->vtable->create_connection_for_request) {
2437 client->vtable->create_connection_for_request(client, request);
2438 return;
2439 }
2440
2441 s_s3_client_create_connection_for_request_default(client, request);
2442 }
2443
2444 static void s_s3_client_create_connection_for_request_default(
2445 struct aws_s3_client *client,
2446 struct aws_s3_request *request) {
2447 AWS_PRECONDITION(client);
2448 AWS_PRECONDITION(request);
2449
2450 struct aws_s3_meta_request *meta_request = request->meta_request;
2451 AWS_PRECONDITION(meta_request);
2452
2453 aws_atomic_fetch_add(&meta_request->num_requests_network, 1);
2454 aws_atomic_fetch_add(&client->stats.num_requests_network_io[meta_request->type], 1);
2455
2456 struct aws_s3_connection *connection = aws_mem_calloc(client->allocator, 1, sizeof(struct aws_s3_connection));
2457
2458 connection->endpoint = aws_s3_endpoint_acquire(meta_request->endpoint, false /*already_holding_lock*/);
2459 connection->request = request;
2460
2461 struct aws_byte_cursor host_header_value;
2462 AWS_ZERO_STRUCT(host_header_value);
2463
2464 struct aws_http_headers *message_headers = aws_http_message_get_headers(meta_request->initial_request_message);
2465 AWS_ASSERT(message_headers);
2466
2467 int result = aws_http_headers_get(message_headers, g_host_header_name, &host_header_value);
2468 AWS_ASSERT(result == AWS_OP_SUCCESS);
2469 (void)result;
2470
2471 if (aws_retry_strategy_acquire_retry_token(
2472 client->retry_strategy, &host_header_value, s_s3_client_acquired_retry_token, connection, 0)) {
2473
2474 AWS_LOGF_ERROR(
2475 AWS_LS_S3_CLIENT,
2476 "id=%p Client could not acquire retry token for request %p due to error %d (%s)",
2477 (void *)client,
2478 (void *)request,
2479 aws_last_error_or_unknown(),
2480 aws_error_str(aws_last_error_or_unknown()));
2481
2482 goto reset_connection;
2483 }
2484
2485 return;
2486
2487 reset_connection:
2488
2489 aws_s3_client_notify_connection_finished(
2490 client, connection, aws_last_error_or_unknown(), AWS_S3_CONNECTION_FINISH_CODE_FAILED);
2491 }
2492
2493 static void s_s3_client_acquired_retry_token(
2494 struct aws_retry_strategy *retry_strategy,
2495 int error_code,
2496 struct aws_retry_token *token,
2497 void *user_data) {
2498
2499 AWS_PRECONDITION(retry_strategy);
2500 (void)retry_strategy;
2501
2502 struct aws_s3_connection *connection = user_data;
2503 AWS_PRECONDITION(connection);
2504
2505 struct aws_s3_request *request = connection->request;
2506 AWS_PRECONDITION(request);
2507
2508 struct aws_s3_meta_request *meta_request = request->meta_request;
2509 AWS_PRECONDITION(meta_request);
2510
2511 struct aws_s3_endpoint *endpoint = meta_request->endpoint;
2512 AWS_ASSERT(endpoint != NULL);
2513
2514 struct aws_s3_client *client = endpoint->client;
2515 AWS_ASSERT(client != NULL);
2516
2517 if (error_code != AWS_ERROR_SUCCESS) {
2518 AWS_LOGF_ERROR(
2519 AWS_LS_S3_CLIENT,
2520 "id=%p Client could not get retry token for connection %p processing request %p due to error %d (%s)",
2521 (void *)client,
2522 (void *)connection,
2523 (void *)request,
2524 error_code,
2525 aws_error_str(error_code));
2526
2527 goto error_clean_up;
2528 }
2529
2530 AWS_ASSERT(token);
2531
2532 connection->retry_token = token;
2533
2534 AWS_ASSERT(client->vtable->acquire_http_connection);
2535
2536 /* client needs to be kept alive until s_s3_client_on_acquire_http_connection completes */
2537 /* TODO: not a blocker, consider managing the life time of aws_s3_client from aws_s3_endpoint to simplify usage */
2538 aws_s3_client_acquire(client);
2539
2540 aws_high_res_clock_get_ticks((uint64_t *)&request->send_data.metrics->time_metrics.conn_acquire_start_timestamp_ns);
2541
2542 client->vtable->acquire_http_connection(
2543 endpoint->http_connection_manager, s_s3_client_on_acquire_http_connection, connection);
2544
2545 return;
2546
2547 error_clean_up:
2548
2549 aws_s3_client_notify_connection_finished(client, connection, error_code, AWS_S3_CONNECTION_FINISH_CODE_FAILED);
2550 }
2551
2552 static void s_s3_client_on_acquire_http_connection(
2553 struct aws_http_connection *incoming_http_connection,
2554 int error_code,
2555 void *user_data) {
2556
2557 struct aws_s3_connection *connection = user_data;
2558 AWS_PRECONDITION(connection);
2559
2560 struct aws_s3_request *request = connection->request;
2561 AWS_PRECONDITION(request);
2562
2563 struct aws_s3_meta_request *meta_request = request->meta_request;
2564 AWS_PRECONDITION(meta_request);
2565
2566 struct aws_s3_endpoint *endpoint = meta_request->endpoint;
2567 AWS_ASSERT(endpoint != NULL);
2568
2569 struct aws_s3_client *client = endpoint->client;
2570 AWS_ASSERT(client != NULL);
2571
2572 if (error_code != AWS_ERROR_SUCCESS) {
2573 AWS_LOGF_ERROR(
2574 AWS_LS_S3_ENDPOINT,
2575 "id=%p: Could not acquire connection due to error code %d (%s)",
2576 (void *)endpoint,
2577 error_code,
2578 aws_error_str(error_code));
2579
2580 if (error_code == AWS_IO_DNS_INVALID_NAME || error_code == AWS_ERROR_PLATFORM_NOT_SUPPORTED ||
2581 error_code == AWS_IO_SOCKET_INVALID_OPTIONS) {
2582 /**
2583 * Fail fast without retry
2584 * - Invalid DNS name will not change after retry.
2585 */
2586 AWS_LOGF_ERROR(
2587 AWS_LS_S3_META_REQUEST,
2588 "id=%p Meta request cannot recover from error %d (%s) while acquiring HTTP connection. (request=%p)",
2589 (void *)meta_request,
2590 error_code,
2591 aws_error_str(error_code),
2592 (void *)request);
2593 goto error_fail;
2594 }
2595
2596 goto error_retry;
2597 }
2598
2599 aws_high_res_clock_get_ticks((uint64_t *)&request->send_data.metrics->time_metrics.conn_acquire_end_timestamp_ns);
2600 request->send_data.metrics->time_metrics.conn_acquire_duration_ns =
2601 request->send_data.metrics->time_metrics.conn_acquire_end_timestamp_ns -
2602 request->send_data.metrics->time_metrics.conn_acquire_start_timestamp_ns;
2603
2604 connection->http_connection = incoming_http_connection;
2605 aws_s3_meta_request_send_request(meta_request, connection);
2606 aws_s3_client_release(client); /* kept since this callback was registered */
2607 return;
2608
2609 error_retry:
2610
2611 aws_s3_client_notify_connection_finished(client, connection, error_code, AWS_S3_CONNECTION_FINISH_CODE_RETRY);
2612 aws_s3_client_release(client); /* kept since this callback was registered */
2613 return;
2614
2615 error_fail:
2616
2617 aws_s3_client_notify_connection_finished(client, connection, error_code, AWS_S3_CONNECTION_FINISH_CODE_FAILED);
2618 aws_s3_client_release(client); /* kept since this callback was registered */
2619 }
2620
2621 /* Called by aws_s3_meta_request when it has finished using this connection for a single request. */
2622 void aws_s3_client_notify_connection_finished(
2623 struct aws_s3_client *client,
2624 struct aws_s3_connection *connection,
2625 int error_code,
2626 enum aws_s3_connection_finish_code finish_code) {
2627 AWS_PRECONDITION(client);
2628 AWS_PRECONDITION(connection);
2629
2630 struct aws_s3_request *request = connection->request;
2631 AWS_PRECONDITION(request);
2632
2633 struct aws_s3_meta_request *meta_request = request->meta_request;
2634
2635 AWS_PRECONDITION(meta_request);
2636 AWS_PRECONDITION(meta_request->initial_request_message);
2637
2638 struct aws_s3_endpoint *endpoint = meta_request->endpoint;
2639 AWS_PRECONDITION(endpoint);
2640 if (request->send_data.metrics) {
2641 request->send_data.metrics->crt_info_metrics.error_code = error_code;
2642 }
2643
2644 /* If we're trying to set up a retry... */
2645 if (finish_code == AWS_S3_CONNECTION_FINISH_CODE_RETRY) {
2646
2647 if (connection->retry_token == NULL) {
2648 AWS_LOGF_ERROR(
2649 AWS_LS_S3_CLIENT,
2650 "id=%p Client could not schedule retry of request %p for meta request %p, as retry token is NULL.",
2651 (void *)client,
2652 (void *)request,
2653 (void *)meta_request);
2654
2655 goto reset_connection;
2656 }
2657
2658 if (aws_s3_meta_request_is_finished(meta_request)) {
2659 AWS_LOGF_DEBUG(
2660 AWS_LS_S3_CLIENT,
2661 "id=%p Client not scheduling retry of request %p for meta request %p with token %p because meta "
2662 "request has been flagged as finished.",
2663 (void *)client,
2664 (void *)request,
2665 (void *)meta_request,
2666 (void *)connection->retry_token);
2667
2668 goto reset_connection;
2669 }
2670
2671 AWS_LOGF_DEBUG(
2672 AWS_LS_S3_CLIENT,
2673 "id=%p Client scheduling retry of request %p for meta request %p with token %p with error code %d (%s).",
2674 (void *)client,
2675 (void *)request,
2676 (void *)meta_request,
2677 (void *)connection->retry_token,
2678 error_code,
2679 aws_error_str(error_code));
2680
2681 enum aws_retry_error_type error_type = AWS_RETRY_ERROR_TYPE_TRANSIENT;
2682
2683 switch (error_code) {
2684 case AWS_ERROR_S3_INTERNAL_ERROR:
2685 error_type = AWS_RETRY_ERROR_TYPE_SERVER_ERROR;
2686 break;
2687
2688 case AWS_ERROR_S3_SLOW_DOWN:
2689 error_type = AWS_RETRY_ERROR_TYPE_THROTTLING;
2690 break;
2691 }
2692
2693 if (connection->http_connection != NULL) {
2694 AWS_ASSERT(endpoint->http_connection_manager);
2695
2696 aws_http_connection_manager_release_connection(
2697 endpoint->http_connection_manager, connection->http_connection);
2698
2699 connection->http_connection = NULL;
2700 }
2701
2702 /* Ask the retry strategy to schedule a retry of the request. */
2703 aws_high_res_clock_get_ticks((uint64_t *)&request->retry_start_timestamp_ns);
2704 if (aws_retry_strategy_schedule_retry(
2705 connection->retry_token, error_type, s_s3_client_retry_ready, connection)) {
2706
2707 AWS_LOGF_ERROR(
2708 AWS_LS_S3_CLIENT,
2709 "id=%p Client could not retry request %p for meta request %p with token %p due to error %d (%s)",
2710 (void *)client,
2711 (void *)request,
2712 (void *)meta_request,
2713 (void *)connection->retry_token,
2714 aws_last_error_or_unknown(),
2715 aws_error_str(aws_last_error_or_unknown()));
2716
2717 goto reset_connection;
2718 }
2719
2720 return;
2721 }
2722
2723 reset_connection:
2724
2725 aws_high_res_clock_get_ticks(
2726 (uint64_t *)&request->send_data.metrics->time_metrics.s3_request_last_attempt_end_timestamp_ns);
2727 request->send_data.metrics->time_metrics.s3_request_total_duration_ns =
2728 request->send_data.metrics->time_metrics.s3_request_last_attempt_end_timestamp_ns -
2729 request->send_data.metrics->time_metrics.s3_request_first_attempt_start_timestamp_ns;
2730
2731 if (connection->retry_token != NULL) {
2732 /* If we have a retry token and successfully finished, record that success. */
2733 if (finish_code == AWS_S3_CONNECTION_FINISH_CODE_SUCCESS) {
2734 aws_retry_token_record_success(connection->retry_token);
2735 }
2736
2737 aws_retry_token_release(connection->retry_token);
2738 connection->retry_token = NULL;
2739 }
2740
2741 aws_atomic_fetch_sub(&meta_request->num_requests_network, 1);
2742 aws_atomic_fetch_sub(&client->stats.num_requests_network_io[meta_request->type], 1);
2743
2744 s_s3_client_meta_request_finished_request(client, meta_request, request, error_code);
2745
2746 if (connection->http_connection != NULL) {
2747 AWS_ASSERT(endpoint->http_connection_manager);
2748
2749 aws_http_connection_manager_release_connection(endpoint->http_connection_manager, connection->http_connection);
2750
2751 connection->http_connection = NULL;
2752 }
2753
2754 if (connection->request != NULL) {
2755 connection->request = aws_s3_request_release(connection->request);
2756 }
2757
2758 aws_retry_token_release(connection->retry_token);
2759 connection->retry_token = NULL;
2760
2761 aws_s3_endpoint_release(connection->endpoint);
2762 connection->endpoint = NULL;
2763
2764 aws_mem_release(client->allocator, connection);
2765 connection = NULL;
2766
2767 /* BEGIN CRITICAL SECTION */
2768 {
2769 aws_s3_client_lock_synced_data(client);
2770 s_s3_client_schedule_process_work_synced(client);
2771 aws_s3_client_unlock_synced_data(client);
2772 }
2773 /* END CRITICAL SECTION */
2774 }
2775
2776 static void s_s3_client_prepare_request_callback_retry_request(
2777 struct aws_s3_meta_request *meta_request,
2778 struct aws_s3_request *request,
2779 int error_code,
2780 void *user_data);
2781
2782 static void s_s3_client_retry_ready(struct aws_retry_token *token, int error_code, void *user_data) {
2783 AWS_PRECONDITION(token);
2784 (void)token;
2785
2786 struct aws_s3_connection *connection = user_data;
2787 AWS_PRECONDITION(connection);
2788
2789 struct aws_s3_request *request = connection->request;
2790 AWS_PRECONDITION(request);
2791
2792 aws_high_res_clock_get_ticks((uint64_t *)&request->retry_end_timestamp_ns);
2793
2794 struct aws_s3_meta_request *meta_request = request->meta_request;
2795 AWS_PRECONDITION(meta_request);
2796
2797 struct aws_s3_endpoint *endpoint = meta_request->endpoint;
2798 AWS_PRECONDITION(endpoint);
2799
2800 struct aws_s3_client *client = endpoint->client;
2801 AWS_PRECONDITION(client);
2802
2803 /* If we couldn't retry this request, then bail on the entire meta request. */
2804 if (error_code != AWS_ERROR_SUCCESS) {
2805
2806 AWS_LOGF_ERROR(
2807 AWS_LS_S3_CLIENT,
2808 "id=%p Client could not retry request %p for meta request %p due to error %d (%s)",
2809 (void *)client,
2810 (void *)meta_request,
2811 (void *)request,
2812 error_code,
2813 aws_error_str(error_code));
2814
2815 goto error_clean_up;
2816 }
2817
2818 AWS_LOGF_DEBUG(
2819 AWS_LS_S3_META_REQUEST,
2820 "id=%p Client retrying request %p for meta request %p on connection %p with retry token %p",
2821 (void *)client,
2822 (void *)request,
2823 (void *)meta_request,
2824 (void *)connection,
2825 (void *)connection->retry_token);
2826
2827 aws_s3_meta_request_prepare_request(
2828 meta_request, request, s_s3_client_prepare_request_callback_retry_request, connection);
2829
2830 return;
2831
2832 error_clean_up:
2833
2834 aws_s3_client_notify_connection_finished(client, connection, error_code, AWS_S3_CONNECTION_FINISH_CODE_FAILED);
2835 }
2836
2837 static void s_s3_client_prepare_request_callback_retry_request(
2838 struct aws_s3_meta_request *meta_request,
2839 struct aws_s3_request *request,
2840 int error_code,
2841 void *user_data) {
2842 AWS_PRECONDITION(meta_request);
2843 (void)meta_request;
2844
2845 AWS_PRECONDITION(request);
2846 (void)request;
2847
2848 struct aws_s3_connection *connection = user_data;
2849 AWS_PRECONDITION(connection);
2850
2851 struct aws_s3_endpoint *endpoint = meta_request->endpoint;
2852 AWS_ASSERT(endpoint != NULL);
2853
2854 struct aws_s3_client *client = endpoint->client;
2855 AWS_ASSERT(client != NULL);
2856
2857 if (error_code == AWS_ERROR_SUCCESS) {
2858 AWS_ASSERT(connection->retry_token);
2859
2860 s_s3_client_acquired_retry_token(
2861 client->retry_strategy, AWS_ERROR_SUCCESS, connection->retry_token, connection);
2862 } else {
2863 aws_s3_client_notify_connection_finished(client, connection, error_code, AWS_S3_CONNECTION_FINISH_CODE_FAILED);
2864 }
2865 }
2866
2867 static void s_resume_token_ref_count_zero_callback(void *arg) {
2868 struct aws_s3_meta_request_resume_token *token = arg;
2869
2870 aws_string_destroy(token->multipart_upload_id);
2871
2872 aws_mem_release(token->allocator, token);
2873 }
2874
2875 struct aws_s3_meta_request_resume_token *aws_s3_meta_request_resume_token_new(struct aws_allocator *allocator) {
2876 struct aws_s3_meta_request_resume_token *token =
2877 aws_mem_calloc(allocator, 1, sizeof(struct aws_s3_meta_request_resume_token));
2878
2879 token->allocator = allocator;
2880 aws_ref_count_init(&token->ref_count, token, s_resume_token_ref_count_zero_callback);
2881
2882 return token;
2883 }
2884
2885 struct aws_s3_meta_request_resume_token *aws_s3_meta_request_resume_token_new_upload(
2886 struct aws_allocator *allocator,
2887 const struct aws_s3_upload_resume_token_options *options) {
2888 AWS_PRECONDITION(allocator);
2889 AWS_PRECONDITION(options);
2890 if (options->part_size > SIZE_MAX) {
2891 aws_raise_error(AWS_ERROR_OVERFLOW_DETECTED);
2892 return NULL;
2893 }
2894
2895 struct aws_s3_meta_request_resume_token *token = aws_s3_meta_request_resume_token_new(allocator);
2896 token->multipart_upload_id = aws_string_new_from_cursor(allocator, &options->upload_id);
2897 token->part_size = (size_t)options->part_size;
2898 token->total_num_parts = options->total_num_parts;
2899 token->num_parts_completed = options->num_parts_completed;
2900 token->type = AWS_S3_META_REQUEST_TYPE_PUT_OBJECT;
2901 return token;
2902 }
2903
2904 struct aws_s3_meta_request_resume_token *aws_s3_meta_request_resume_token_acquire(
2905 struct aws_s3_meta_request_resume_token *resume_token) {
2906 if (resume_token) {
2907 aws_ref_count_acquire(&resume_token->ref_count);
2908 }
2909 return resume_token;
2910 }
2911
2912 struct aws_s3_meta_request_resume_token *aws_s3_meta_request_resume_token_release(
2913 struct aws_s3_meta_request_resume_token *resume_token) {
2914 if (resume_token) {
2915 aws_ref_count_release(&resume_token->ref_count);
2916 }
2917 return NULL;
2918 }
2919
2920 enum aws_s3_meta_request_type aws_s3_meta_request_resume_token_type(
2921 struct aws_s3_meta_request_resume_token *resume_token) {
2922 AWS_FATAL_PRECONDITION(resume_token);
2923 return resume_token->type;
2924 }
2925
2926 uint64_t aws_s3_meta_request_resume_token_part_size(struct aws_s3_meta_request_resume_token *resume_token) {
2927 AWS_FATAL_PRECONDITION(resume_token);
2928 return (uint64_t)resume_token->part_size;
2929 }
2930
2931 size_t aws_s3_meta_request_resume_token_total_num_parts(struct aws_s3_meta_request_resume_token *resume_token) {
2932 AWS_FATAL_PRECONDITION(resume_token);
2933 return resume_token->total_num_parts;
2934 }
2935
2936 size_t aws_s3_meta_request_resume_token_num_parts_completed(struct aws_s3_meta_request_resume_token *resume_token) {
2937 AWS_FATAL_PRECONDITION(resume_token);
2938 return resume_token->num_parts_completed;
2939 }
2940
2941 struct aws_byte_cursor aws_s3_meta_request_resume_token_upload_id(
2942 struct aws_s3_meta_request_resume_token *resume_token) {
2943 AWS_FATAL_PRECONDITION(resume_token);
2944 if (resume_token->type == AWS_S3_META_REQUEST_TYPE_PUT_OBJECT && resume_token->multipart_upload_id != NULL) {
2945 return aws_byte_cursor_from_string(resume_token->multipart_upload_id);
2946 }
2947
2948 return aws_byte_cursor_from_c_str("");
2949 }
2950
2951 static uint64_t s_upload_timeout_threshold_ns = 5000000000; /* 5 Secs */
2952 const size_t g_expect_timeout_offset_ms =
2953 700; /* 0.7 Secs. From experiments on c5n.18xlarge machine for 30 GiB upload, it gave us best performance. */
2954
2955 static int s_compare_uint64_min_heap(const void *a, const void *b) {
2956 uint64_t arg1 = *(const uint64_t *)a;
2957 uint64_t arg2 = *(const uint64_t *)b;
2958 /* Use a min-heap to get the P90, which will be the min of the largest 10% of data. */
2959 return arg1 > arg2;
2960 }
2961
2962 /**
2963 * The upload timeout optimization: explained.
2964 *
2965 * Sometimes, S3 is extremely slow responding to an upload.
2966 * In these cases, it's much faster to cancel and resend the upload,
2967 * vs waiting 5sec for the slow response.
2968 *
2969 * Typically, S3 responds to an upload in 0.2sec after the request is fully received.
2970 * But occasionally (about 0.1%) it takes 5sec to respond.
2971 * In a large 30GiB file upload, you can expect about 4 parts to suffer from
2972 * a slow response. If one of these parts is near the end of the file,
2973 * then we end up sitting around doing nothing for up to 5sec, waiting
2974 * for this final slow upload to complete.
2975 *
2976 * We use the response_first_byte_timeout HTTP option to cancel uploads
2977 * suffering from a slow response. But how should we set it? A fast 100Gbps
2978 * machine definitely wants it! But a slow computer does not. A slow computer
2979 * would be better off waiting 5sec for the response, vs re-uploading the whole request.
2980 *
2981 * The current algorithm:
2982 * 1. Start without a timeout value. After max(10, # of ideal connections) requests completed, we know the average of
2983 * how long the request takes. We decide if it's worth to set a timeout value or not. (If the average of request
2984 * takes more than 5 secs or not).
2985 * 2. If it is worth to retry, start with a timeout value from max(1 sec, P90 of the initial samples).
2986 * 3. If a request finishes successfully, use the average response_to_first_byte_time + g_expect_timeout_offset_ms as
2987 * our expected timeout value. (TODO: The real expected timeout value should be a P99 of all the requests.)
2988 * 3.1 Adjust the current timeout value against the expected timeout value, via 0.99 * <current timeout> + 0.01 *
2989 * <expected timeout> to get closer to the expected timeout value.
2990 * 4. If request had timed out. We check the timeout rate.
2991 * 4.1 If timeout rate is larger than 0.1%, we increase the timeout value by 100ms (Check the timeout value when the
2992 * request was made, if the updated timeout value is larger than the expected, skip update).
2993 * 4.2 If timeout rate is larger than 1%, we increase the timeout value by 1 secs (If needed). And clear the rate
2994 * to get the exact rate with new timeout value.
2995 * 4.3 Once the timeout value is larger than 5 secs, we stop the process.
2996 *
2997 * Invoked from `s_s3_auto_ranged_put_send_request_finish`.
2998 */
2999 void aws_s3_client_update_upload_part_timeout(
3000 struct aws_s3_client *client,
3001 struct aws_s3_request *finished_upload_part_request,
3002 int finished_error_code) {
3003
3004 aws_s3_client_lock_synced_data(client);
3005 struct aws_s3_upload_part_timeout_stats *stats = &client->synced_data.upload_part_stats;
3006 if (stats->stop_timeout) {
3007 /* Timeout was disabled */
3008 goto unlock;
3009 }
3010
3011 struct aws_s3_request_metrics *metrics = finished_upload_part_request->send_data.metrics;
3012 size_t current_timeout_ms = aws_atomic_load_int(&client->upload_timeout_ms);
3013 uint64_t current_timeout_ns =
3014 aws_timestamp_convert(current_timeout_ms, AWS_TIMESTAMP_MILLIS, AWS_TIMESTAMP_NANOS, NULL);
3015 uint64_t updated_timeout_ns = 0;
3016 uint64_t expect_timeout_offset_ns =
3017 aws_timestamp_convert(g_expect_timeout_offset_ms, AWS_TIMESTAMP_MILLIS, AWS_TIMESTAMP_NANOS, NULL);
3018 // Default to ideal connection count, but at least collect 10 samples.
3019 uint32_t num_samples_to_collect = aws_max_u32(client->ideal_connection_count, 10);
3020
3021 switch (finished_error_code) {
3022 case AWS_ERROR_SUCCESS:
3023 /* We only interested in request succeed */
3024 stats->num_successful_upload_requests = aws_add_u64_saturating(stats->num_successful_upload_requests, 1);
3025 if (stats->num_successful_upload_requests <= num_samples_to_collect) {
3026 /* Gether the data */
3027 uint64_t request_time_ns =
3028 metrics->time_metrics.receive_end_timestamp_ns - metrics->time_metrics.send_start_timestamp_ns;
3029 stats->initial_request_time.sum_ns =
3030 aws_add_u64_saturating(stats->initial_request_time.sum_ns, request_time_ns);
3031 ++stats->initial_request_time.num_samples;
3032 if (!stats->initial_request_time.collecting_p90) {
3033 /* Initialize the priority queue to collect the p90 of the initial requests. */
3034 stats->initial_request_time.collecting_p90 = true;
3035 size_t queue_size = num_samples_to_collect / 10;
3036 AWS_ASSERT(queue_size > 0);
3037 aws_priority_queue_init_dynamic(
3038 &stats->initial_request_time.p90_samples,
3039 client->allocator,
3040 queue_size,
3041 sizeof(uint64_t),
3042 s_compare_uint64_min_heap);
3043 } else {
3044 /* check if the queue is full, if full pop and top and push the next. */
3045 size_t current_size = aws_priority_queue_size(&stats->initial_request_time.p90_samples);
3046 size_t current_capacity = aws_priority_queue_capacity(&stats->initial_request_time.p90_samples);
3047 if (current_size == current_capacity) {
3048 uint64_t *min = NULL;
3049 aws_priority_queue_top(&stats->initial_request_time.p90_samples, (void **)&min);
3050 if (request_time_ns > *min) {
3051 /* Push the data into the queue if it's larger than the min of the queue. */
3052 uint64_t pop_val = 0;
3053 aws_priority_queue_pop(&stats->initial_request_time.p90_samples, &pop_val);
3054 aws_priority_queue_push(&stats->initial_request_time.p90_samples, &request_time_ns);
3055 }
3056 } else {
3057 aws_priority_queue_push(&stats->initial_request_time.p90_samples, &request_time_ns);
3058 }
3059 }
3060
3061 if (stats->num_successful_upload_requests == client->ideal_connection_count) {
3062 /* Decide we need a timeout or not */
3063 uint64_t average_request_time_ns =
3064 stats->initial_request_time.sum_ns / stats->initial_request_time.num_samples;
3065 if (average_request_time_ns >= s_upload_timeout_threshold_ns) {
3066 /* We don't need a timeout, as retry will be slower than just wait for the server to response */
3067 stats->stop_timeout = true;
3068 } else {
3069 /* Start the timeout at th p90 of the initial samples. */
3070 uint64_t *p90_ns = NULL;
3071 aws_priority_queue_top(&stats->initial_request_time.p90_samples, (void **)&p90_ns);
3072 uint64_t p90_ms =
3073 aws_timestamp_convert(*p90_ns, AWS_TIMESTAMP_NANOS, AWS_TIMESTAMP_MILLIS, NULL);
3074 uint64_t init_upload_timeout_ms = aws_max_u64(p90_ms, 1000 /*1sec*/);
3075 aws_atomic_store_int(&client->upload_timeout_ms, (size_t)init_upload_timeout_ms);
3076 /* Clean up the queue now, as not needed anymore. */
3077 aws_priority_queue_clean_up(&stats->initial_request_time.p90_samples);
3078 stats->initial_request_time.collecting_p90 = false;
3079 }
3080 }
3081 goto unlock;
3082 }
3083 /* Starts to update timeout on case of succeed */
3084 stats->timeout_rate_tracking.num_completed =
3085 aws_add_u64_saturating(stats->timeout_rate_tracking.num_completed, 1);
3086 /* Response to first byte is time taken for the first byte data received from the request finished
3087 * sending */
3088 uint64_t response_to_first_byte_time_ns =
3089 metrics->time_metrics.receive_start_timestamp_ns - metrics->time_metrics.send_end_timestamp_ns;
3090 stats->response_to_first_byte_time.sum_ns =
3091 aws_add_u64_saturating(stats->response_to_first_byte_time.sum_ns, response_to_first_byte_time_ns);
3092 stats->response_to_first_byte_time.num_samples =
3093 aws_add_u64_saturating(stats->response_to_first_byte_time.num_samples, 1);
3094
3095 uint64_t average_response_to_first_byte_time_ns =
3096 stats->response_to_first_byte_time.sum_ns / stats->response_to_first_byte_time.num_samples;
3097 uint64_t expected_timeout_ns = average_response_to_first_byte_time_ns + expect_timeout_offset_ns;
3098 double timeout_ns_double = (double)current_timeout_ns * 0.99 + (double)expected_timeout_ns * 0.01;
3099 updated_timeout_ns = (uint64_t)timeout_ns_double;
3100 break;
3101
3102 case AWS_ERROR_HTTP_RESPONSE_FIRST_BYTE_TIMEOUT:
3103 if (stats->num_successful_upload_requests < 10) {
3104 goto unlock;
3105 }
3106
3107 /* Starts to update timeout on case of timed out */
3108 stats->timeout_rate_tracking.num_completed =
3109 aws_add_u64_saturating(stats->timeout_rate_tracking.num_completed, 1);
3110 stats->timeout_rate_tracking.num_failed =
3111 aws_add_u64_saturating(stats->timeout_rate_tracking.num_failed, 1);
3112
3113 uint64_t timeout_threshold = (uint64_t)ceil((double)stats->timeout_rate_tracking.num_completed / 100);
3114 uint64_t warning_threshold = (uint64_t)ceil((double)stats->timeout_rate_tracking.num_completed / 1000);
3115
3116 if (stats->timeout_rate_tracking.num_failed > timeout_threshold) {
3117 /**
3118 * Restore the rate track, as we are larger than 1%, it goes off the record.
3119 */
3120
3121 AWS_LOGF_WARN(
3122 AWS_LS_S3_CLIENT,
3123 "id=%p Client upload part timeout rate is larger than expected, current timeout is %zu, bump it "
3124 "up. Request original timeout is: %zu",
3125 (void *)client,
3126 current_timeout_ms,
3127 finished_upload_part_request->upload_timeout_ms);
3128 stats->timeout_rate_tracking.num_completed = 0;
3129 stats->timeout_rate_tracking.num_failed = 0;
3130 if (finished_upload_part_request->upload_timeout_ms + 1000 > current_timeout_ms) {
3131 /* Update the timeout by adding 1 secs only when it's worth to do so */
3132 updated_timeout_ns = aws_add_u64_saturating(
3133 current_timeout_ns, aws_timestamp_convert(1, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL));
3134 }
3135 } else if (stats->timeout_rate_tracking.num_failed > warning_threshold) {
3136 if (finished_upload_part_request->upload_timeout_ms + 100 > current_timeout_ms) {
3137 /* Only update the timeout by adding 100 ms if the request was made with a longer time out. */
3138 updated_timeout_ns = aws_add_u64_saturating(
3139 current_timeout_ns,
3140 aws_timestamp_convert(100, AWS_TIMESTAMP_MILLIS, AWS_TIMESTAMP_NANOS, NULL));
3141 }
3142 }
3143 break;
3144 default:
3145 break;
3146 }
3147
3148 if (updated_timeout_ns != 0) {
3149 if (updated_timeout_ns > s_upload_timeout_threshold_ns) {
3150 /* Stops timeout, as wait for server to response will be faster to set our own timeout */
3151 stats->stop_timeout = true;
3152 /* Unset the upload_timeout */
3153 updated_timeout_ns = 0;
3154 }
3155 /* Apply the updated timeout */
3156 aws_atomic_store_int(
3157 &client->upload_timeout_ms,
3158 (size_t)aws_timestamp_convert(updated_timeout_ns, AWS_TIMESTAMP_NANOS, AWS_TIMESTAMP_MILLIS, NULL));
3159 }
3160
3161 unlock:
3162 aws_s3_client_unlock_synced_data(client);
3163 }