-
Notifications
You must be signed in to change notification settings - Fork 190
/
orchestrator.rs
1331 lines (1214 loc) · 54.6 KB
/
orchestrator.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
use self::auth::orchestrate_auth;
use crate::client::interceptors::Interceptors;
use crate::client::orchestrator::endpoints::orchestrate_endpoint;
use crate::client::orchestrator::http::{log_response_body, read_body};
use crate::client::timeout::{MaybeTimeout, MaybeTimeoutConfig, TimeoutKind};
use aws_smithy_async::rt::sleep::AsyncSleep;
use aws_smithy_runtime_api::box_error::BoxError;
use aws_smithy_runtime_api::client::http::{HttpClient, HttpConnector, HttpConnectorSettings};
use aws_smithy_runtime_api::client::interceptors::context::{
Error, Input, InterceptorContext, Output, RewindResult,
};
use aws_smithy_runtime_api::client::orchestrator::{
HttpResponse, LoadedRequestBody, OrchestratorError,
};
use aws_smithy_runtime_api::client::result::SdkError;
use aws_smithy_runtime_api::client::retries::{RequestAttempts, RetryStrategy, ShouldAttempt};
use aws_smithy_runtime_api::client::runtime_components::RuntimeComponents;
use aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugins;
use aws_smithy_runtime_api::client::ser_de::{
DeserializeResponse, SerializeRequest, SharedRequestSerializer, SharedResponseDeserializer,
};
use aws_smithy_types::body::SdkBody;
use aws_smithy_types::byte_stream::ByteStream;
use aws_smithy_types::config_bag::ConfigBag;
use aws_smithy_types::timeout::{MergeTimeoutConfig, TimeoutConfig};
use std::mem;
use tracing::{debug, debug_span, instrument, trace, Instrument};
mod auth;
/// Defines types that implement a trait for endpoint resolution
pub mod endpoints;
/// Defines types that work with HTTP types
mod http;
/// Utility for making one-off unmodeled requests with the orchestrator.
pub mod operation;
macro_rules! halt {
([$ctx:ident] => $err:expr) => {{
debug!("encountered orchestrator error; halting");
$ctx.fail($err.into());
return;
}};
}
macro_rules! halt_on_err {
([$ctx:ident] => $expr:expr) => {
match $expr {
Ok(ok) => ok,
Err(err) => halt!([$ctx] => err),
}
};
}
macro_rules! continue_on_err {
([$ctx:ident] => $expr:expr) => {
if let Err(err) = $expr {
debug!(err = ?err, "encountered orchestrator error; continuing");
$ctx.fail(err.into());
}
};
}
macro_rules! run_interceptors {
(continue_on_err: { $($interceptor:ident($ctx:ident, $rc:ident, $cfg:ident);)+ }) => {
$(run_interceptors!(continue_on_err: $interceptor($ctx, $rc, $cfg));)+
};
(continue_on_err: $interceptor:ident($ctx:ident, $rc:ident, $cfg:ident)) => {
continue_on_err!([$ctx] => run_interceptors!(__private $interceptor($ctx, $rc, $cfg)))
};
(halt_on_err: { $($interceptor:ident($ctx:ident, $rc:ident, $cfg:ident);)+ }) => {
$(run_interceptors!(halt_on_err: $interceptor($ctx, $rc, $cfg));)+
};
(halt_on_err: $interceptor:ident($ctx:ident, $rc:ident, $cfg:ident)) => {
halt_on_err!([$ctx] => run_interceptors!(__private $interceptor($ctx, $rc, $cfg)))
};
(__private $interceptor:ident($ctx:ident, $rc:ident, $cfg:ident)) => {
Interceptors::new($rc.interceptors()).$interceptor($ctx, $rc, $cfg)
};
}
/// Orchestrates the execution of a request and handling of a response.
///
/// The given `runtime_plugins` will be used to generate a `ConfigBag` for this request,
/// and then the given `input` will be serialized and transmitted. When a response is
/// received, it will be deserialized and returned.
///
/// This orchestration handles retries, endpoint resolution, identity resolution, and signing.
/// Each of these are configurable via the config and runtime components given by the runtime
/// plugins.
pub async fn invoke(
service_name: &str,
operation_name: &str,
input: Input,
runtime_plugins: &RuntimePlugins,
) -> Result<Output, SdkError<Error, HttpResponse>> {
invoke_with_stop_point(
service_name,
operation_name,
input,
runtime_plugins,
StopPoint::None,
)
.await?
.finalize()
}
/// Allows for returning early at different points during orchestration.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StopPoint {
/// Don't stop orchestration early
None,
/// Stop the orchestrator before transmitting the request
BeforeTransmit,
}
/// Same as [`invoke`], but allows for returning early at different points during orchestration.
///
/// Orchestration will cease at the point specified by `stop_point`. This is useful for orchestrations
/// that don't need to actually transmit requests, such as for generating presigned requests.
///
/// See the docs on [`invoke`] for more details.
pub async fn invoke_with_stop_point(
service_name: &str,
operation_name: &str,
input: Input,
runtime_plugins: &RuntimePlugins,
stop_point: StopPoint,
) -> Result<InterceptorContext, SdkError<Error, HttpResponse>> {
async move {
let mut cfg = ConfigBag::base();
let cfg = &mut cfg;
let mut ctx = InterceptorContext::new(input);
let runtime_components = apply_configuration(&mut ctx, cfg, runtime_plugins)
.map_err(SdkError::construction_failure)?;
trace!(runtime_components = ?runtime_components);
let operation_timeout_config =
MaybeTimeoutConfig::new(&runtime_components, cfg, TimeoutKind::Operation);
trace!(operation_timeout_config = ?operation_timeout_config);
async {
// If running the pre-execution interceptors failed, then we skip running the op and run the
// final interceptors instead.
if !ctx.is_failed() {
try_op(&mut ctx, cfg, &runtime_components, stop_point).await;
}
finally_op(&mut ctx, cfg, &runtime_components).await;
if ctx.is_failed() {
Err(ctx.finalize().expect_err("it is failed"))
} else {
Ok(ctx)
}
}
.maybe_timeout(operation_timeout_config)
.await
}
.instrument(debug_span!("invoke", service = %service_name, operation = %operation_name))
.await
}
/// Apply configuration is responsible for apply runtime plugins to the config bag, as well as running
/// `read_before_execution` interceptors. If a failure occurs due to config construction, `invoke`
/// will raise it to the user. If an interceptor fails, then `invoke`
#[instrument(skip_all, level = "debug")]
fn apply_configuration(
ctx: &mut InterceptorContext,
cfg: &mut ConfigBag,
runtime_plugins: &RuntimePlugins,
) -> Result<RuntimeComponents, BoxError> {
let client_rc_builder = runtime_plugins.apply_client_configuration(cfg)?;
continue_on_err!([ctx] => Interceptors::new(client_rc_builder.interceptors()).read_before_execution(false, ctx, cfg));
let operation_rc_builder = runtime_plugins.apply_operation_configuration(cfg)?;
continue_on_err!([ctx] => Interceptors::new(operation_rc_builder.interceptors()).read_before_execution(true, ctx, cfg));
// The order below is important. Client interceptors must run before operation interceptors.
let components = RuntimeComponents::builder("merged orchestrator components")
.merge_from(&client_rc_builder)
.merge_from(&operation_rc_builder)
.build()?;
// In an ideal world, we'd simply update `cfg.load` to behave this way. Unfortunately, we can't
// do that without a breaking change. By overwriting the value in the config bag with a merged
// version, we can achieve a very similar behavior. `MergeTimeoutConfig`
let resolved_timeout_config = cfg.load::<MergeTimeoutConfig>();
tracing::debug!(
"timeout settings for this operation: {:?}",
resolved_timeout_config
);
cfg.interceptor_state().store_put(resolved_timeout_config);
components.validate_final_config(cfg)?;
Ok(components)
}
#[instrument(skip_all, level = "debug")]
async fn try_op(
ctx: &mut InterceptorContext,
cfg: &mut ConfigBag,
runtime_components: &RuntimeComponents,
stop_point: StopPoint,
) {
// Before serialization
run_interceptors!(halt_on_err: {
read_before_serialization(ctx, runtime_components, cfg);
modify_before_serialization(ctx, runtime_components, cfg);
});
// Serialization
ctx.enter_serialization_phase();
{
let _span = debug_span!("serialization").entered();
let request_serializer = cfg
.load::<SharedRequestSerializer>()
.expect("request serializer must be in the config bag")
.clone();
let input = ctx.take_input().expect("input set at this point");
let request = halt_on_err!([ctx] => request_serializer.serialize_input(input, cfg).map_err(OrchestratorError::other));
ctx.set_request(request);
}
// Load the request body into memory if configured to do so
if let Some(&LoadedRequestBody::Requested) = cfg.load::<LoadedRequestBody>() {
debug!("loading request body into memory");
let mut body = SdkBody::taken();
mem::swap(&mut body, ctx.request_mut().expect("set above").body_mut());
let loaded_body = halt_on_err!([ctx] =>
ByteStream::new(body).collect().await.map_err(OrchestratorError::other)
)
.into_bytes();
*ctx.request_mut().as_mut().expect("set above").body_mut() =
SdkBody::from(loaded_body.clone());
cfg.interceptor_state()
.store_put(LoadedRequestBody::Loaded(loaded_body));
}
// Before transmit
ctx.enter_before_transmit_phase();
run_interceptors!(halt_on_err: {
read_after_serialization(ctx, runtime_components, cfg);
modify_before_retry_loop(ctx, runtime_components, cfg);
});
// If we got a retry strategy from the bag, ask it what to do.
// Otherwise, assume we should attempt the initial request.
let should_attempt = runtime_components
.retry_strategy()
.should_attempt_initial_request(runtime_components, cfg);
match should_attempt {
// Yes, let's make a request
Ok(ShouldAttempt::Yes) => debug!("retry strategy has OKed initial request"),
// No, this request shouldn't be sent
Ok(ShouldAttempt::No) => {
let err: BoxError = "the retry strategy indicates that an initial request shouldn't be made, but it didn't specify why".into();
halt!([ctx] => OrchestratorError::other(err));
}
// No, we shouldn't make a request because...
Err(err) => halt!([ctx] => OrchestratorError::other(err)),
Ok(ShouldAttempt::YesAfterDelay(delay)) => {
let sleep_impl = halt_on_err!([ctx] => runtime_components.sleep_impl().ok_or_else(|| OrchestratorError::other(
"the retry strategy requested a delay before sending the initial request, but no 'async sleep' implementation was set"
)));
debug!("retry strategy has OKed initial request after a {delay:?} delay");
sleep_impl.sleep(delay).await;
}
}
// Save a request checkpoint before we make the request. This will allow us to "rewind"
// the request in the case of retry attempts.
ctx.save_checkpoint();
let mut retry_delay = None;
for i in 1u32.. {
// Break from the loop if we can't rewind the request's state. This will always succeed the
// first time, but will fail on subsequent iterations if the request body wasn't retryable.
trace!("checking if context can be rewound for attempt #{i}");
if let RewindResult::Impossible = ctx.rewind(cfg) {
debug!("request cannot be retried since the request body cannot be cloned");
break;
}
// Track which attempt we're currently on.
cfg.interceptor_state()
.store_put::<RequestAttempts>(i.into());
// Backoff time should not be included in the attempt timeout
if let Some((delay, sleep)) = retry_delay.take() {
debug!("delaying for {delay:?}");
sleep.await;
}
let attempt_timeout_config =
MaybeTimeoutConfig::new(runtime_components, cfg, TimeoutKind::OperationAttempt);
trace!(attempt_timeout_config = ?attempt_timeout_config);
let maybe_timeout = async {
debug!("beginning attempt #{i}");
try_attempt(ctx, cfg, runtime_components, stop_point).await;
finally_attempt(ctx, cfg, runtime_components).await;
Result::<_, SdkError<Error, HttpResponse>>::Ok(())
}
.maybe_timeout(attempt_timeout_config)
.await
.map_err(|err| OrchestratorError::timeout(err.into_source().unwrap()));
// We continue when encountering a timeout error. The retry classifier will decide what to do with it.
continue_on_err!([ctx] => maybe_timeout);
// If we got a retry strategy from the bag, ask it what to do.
// If no strategy was set, we won't retry.
let should_attempt = halt_on_err!([ctx] => runtime_components
.retry_strategy()
.should_attempt_retry(ctx, runtime_components, cfg)
.map_err(OrchestratorError::other));
match should_attempt {
// Yes, let's retry the request
ShouldAttempt::Yes => continue,
// No, this request shouldn't be retried
ShouldAttempt::No => {
debug!("a retry is either unnecessary or not possible, exiting attempt loop");
break;
}
ShouldAttempt::YesAfterDelay(delay) => {
let sleep_impl = halt_on_err!([ctx] => runtime_components.sleep_impl().ok_or_else(|| OrchestratorError::other(
"the retry strategy requested a delay before sending the retry request, but no 'async sleep' implementation was set"
)));
retry_delay = Some((delay, sleep_impl.sleep(delay)));
continue;
}
}
}
}
#[instrument(skip_all, level = "debug")]
async fn try_attempt(
ctx: &mut InterceptorContext,
cfg: &mut ConfigBag,
runtime_components: &RuntimeComponents,
stop_point: StopPoint,
) {
run_interceptors!(halt_on_err: read_before_attempt(ctx, runtime_components, cfg));
halt_on_err!([ctx] => orchestrate_endpoint(ctx, runtime_components, cfg).await.map_err(OrchestratorError::other));
run_interceptors!(halt_on_err: {
modify_before_signing(ctx, runtime_components, cfg);
read_before_signing(ctx, runtime_components, cfg);
});
halt_on_err!([ctx] => orchestrate_auth(ctx, runtime_components, cfg).await.map_err(OrchestratorError::other));
run_interceptors!(halt_on_err: {
read_after_signing(ctx, runtime_components, cfg);
modify_before_transmit(ctx, runtime_components, cfg);
read_before_transmit(ctx, runtime_components, cfg);
});
// Return early if a stop point is set for before transmit
if let StopPoint::BeforeTransmit = stop_point {
debug!("ending orchestration early because the stop point is `BeforeTransmit`");
return;
}
// The connection consumes the request but we need to keep a copy of it
// within the interceptor context, so we clone it here.
ctx.enter_transmit_phase();
let response = halt_on_err!([ctx] => {
let request = ctx.take_request().expect("set during serialization");
trace!(request = ?request, "transmitting request");
let http_client = halt_on_err!([ctx] => runtime_components.http_client().ok_or_else(||
OrchestratorError::other("No HTTP client was available to send this request. \
Enable the `rustls` crate feature or configure a HTTP client to fix this.")
));
let timeout_config = cfg.load::<TimeoutConfig>().expect("timeout config must be set");
let settings = {
let mut builder = HttpConnectorSettings::builder();
builder.set_connect_timeout(timeout_config.connect_timeout());
builder.set_read_timeout(timeout_config.read_timeout());
builder.build()
};
let connector = http_client.http_connector(&settings, runtime_components);
connector.call(request).await.map_err(OrchestratorError::connector)
});
trace!(response = ?response, "received response from service");
ctx.set_response(response);
ctx.enter_before_deserialization_phase();
run_interceptors!(halt_on_err: {
read_after_transmit(ctx, runtime_components, cfg);
modify_before_deserialization(ctx, runtime_components, cfg);
read_before_deserialization(ctx, runtime_components, cfg);
});
ctx.enter_deserialization_phase();
let output_or_error = async {
let response = ctx.response_mut().expect("set during transmit");
let response_deserializer = cfg
.load::<SharedResponseDeserializer>()
.expect("a request deserializer must be in the config bag");
let maybe_deserialized = {
let _span = debug_span!("deserialize_streaming").entered();
response_deserializer.deserialize_streaming(response)
};
match maybe_deserialized {
Some(output_or_error) => output_or_error,
None => read_body(response)
.instrument(debug_span!("read_body"))
.await
.map_err(OrchestratorError::response)
.and_then(|_| {
let _span = debug_span!("deserialize_nonstreaming").entered();
log_response_body(response, cfg);
response_deserializer.deserialize_nonstreaming(response)
}),
}
}
.instrument(debug_span!("deserialization"))
.await;
trace!(output_or_error = ?output_or_error);
ctx.set_output_or_error(output_or_error);
ctx.enter_after_deserialization_phase();
run_interceptors!(halt_on_err: read_after_deserialization(ctx, runtime_components, cfg));
}
#[instrument(skip_all, level = "debug")]
async fn finally_attempt(
ctx: &mut InterceptorContext,
cfg: &mut ConfigBag,
runtime_components: &RuntimeComponents,
) {
run_interceptors!(continue_on_err: {
modify_before_attempt_completion(ctx, runtime_components, cfg);
read_after_attempt(ctx, runtime_components, cfg);
});
}
#[instrument(skip_all, level = "debug")]
async fn finally_op(
ctx: &mut InterceptorContext,
cfg: &mut ConfigBag,
runtime_components: &RuntimeComponents,
) {
run_interceptors!(continue_on_err: {
modify_before_completion(ctx, runtime_components, cfg);
read_after_execution(ctx, runtime_components, cfg);
});
}
#[cfg(all(test, feature = "test-util"))]
mod tests {
use super::*;
use crate::client::auth::no_auth::{NoAuthRuntimePlugin, NO_AUTH_SCHEME_ID};
use crate::client::http::test_util::NeverClient;
use crate::client::orchestrator::endpoints::StaticUriEndpointResolver;
use crate::client::retries::strategy::NeverRetryStrategy;
use crate::client::test_util::{
deserializer::CannedResponseDeserializer, serializer::CannedRequestSerializer,
};
use ::http::{Response, StatusCode};
use aws_smithy_runtime_api::client::auth::static_resolver::StaticAuthSchemeOptionResolver;
use aws_smithy_runtime_api::client::auth::{
AuthSchemeOptionResolverParams, SharedAuthSchemeOptionResolver,
};
use aws_smithy_runtime_api::client::endpoint::{
EndpointResolverParams, SharedEndpointResolver,
};
use aws_smithy_runtime_api::client::http::{
http_client_fn, HttpConnector, HttpConnectorFuture,
};
use aws_smithy_runtime_api::client::interceptors::context::{
AfterDeserializationInterceptorContextRef, BeforeDeserializationInterceptorContextMut,
BeforeDeserializationInterceptorContextRef, BeforeSerializationInterceptorContextMut,
BeforeSerializationInterceptorContextRef, BeforeTransmitInterceptorContextMut,
BeforeTransmitInterceptorContextRef, FinalizerInterceptorContextMut,
FinalizerInterceptorContextRef,
};
use aws_smithy_runtime_api::client::interceptors::{Intercept, SharedInterceptor};
use aws_smithy_runtime_api::client::orchestrator::HttpRequest;
use aws_smithy_runtime_api::client::retries::SharedRetryStrategy;
use aws_smithy_runtime_api::client::runtime_components::RuntimeComponentsBuilder;
use aws_smithy_runtime_api::client::runtime_plugin::{RuntimePlugin, RuntimePlugins};
use aws_smithy_runtime_api::shared::IntoShared;
use aws_smithy_types::config_bag::{ConfigBag, FrozenLayer, Layer};
use std::borrow::Cow;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tracing_test::traced_test;
fn new_request_serializer() -> CannedRequestSerializer {
CannedRequestSerializer::success(HttpRequest::empty())
}
fn new_response_deserializer() -> CannedResponseDeserializer {
CannedResponseDeserializer::new(
Response::builder()
.status(StatusCode::OK)
.body(SdkBody::empty())
.map_err(|err| OrchestratorError::other(Box::new(err)))
.map(Output::erase),
)
}
#[derive(Debug, Default)]
struct OkConnector {}
impl OkConnector {
fn new() -> Self {
Self::default()
}
}
impl HttpConnector for OkConnector {
fn call(&self, _request: HttpRequest) -> HttpConnectorFuture {
HttpConnectorFuture::ready(Ok(::http::Response::builder()
.status(200)
.body(SdkBody::empty())
.expect("OK response is valid")
.try_into()
.unwrap()))
}
}
#[derive(Debug)]
struct TestOperationRuntimePlugin {
builder: RuntimeComponentsBuilder,
}
impl TestOperationRuntimePlugin {
fn new() -> Self {
Self {
builder: RuntimeComponentsBuilder::for_tests()
.with_retry_strategy(Some(SharedRetryStrategy::new(NeverRetryStrategy::new())))
.with_endpoint_resolver(Some(SharedEndpointResolver::new(
StaticUriEndpointResolver::http_localhost(8080),
)))
.with_http_client(Some(http_client_fn(|_, _| {
OkConnector::new().into_shared()
})))
.with_auth_scheme_option_resolver(Some(SharedAuthSchemeOptionResolver::new(
StaticAuthSchemeOptionResolver::new(vec![NO_AUTH_SCHEME_ID]),
))),
}
}
}
impl RuntimePlugin for TestOperationRuntimePlugin {
fn config(&self) -> Option<FrozenLayer> {
let mut layer = Layer::new("TestOperationRuntimePlugin");
layer.store_put(AuthSchemeOptionResolverParams::new("idontcare"));
layer.store_put(EndpointResolverParams::new("dontcare"));
layer.store_put(SharedRequestSerializer::new(new_request_serializer()));
layer.store_put(SharedResponseDeserializer::new(new_response_deserializer()));
layer.store_put(TimeoutConfig::builder().build());
Some(layer.freeze())
}
fn runtime_components(
&self,
_: &RuntimeComponentsBuilder,
) -> Cow<'_, RuntimeComponentsBuilder> {
Cow::Borrowed(&self.builder)
}
}
macro_rules! interceptor_error_handling_test {
(read_before_execution, $ctx:ty, $expected:expr,) => {
interceptor_error_handling_test!(__private read_before_execution, $ctx, $expected,);
};
($interceptor:ident, $ctx:ty, $expected:expr) => {
interceptor_error_handling_test!(__private $interceptor, $ctx, $expected, _rc: &RuntimeComponents,);
};
(__private $interceptor:ident, $ctx:ty, $expected:expr, $($rc_arg:tt)*) => {
#[derive(Debug)]
struct FailingInterceptorA;
impl Intercept for FailingInterceptorA {
fn name(&self) -> &'static str { "FailingInterceptorA" }
fn $interceptor(
&self,
_ctx: $ctx,
$($rc_arg)*
_cfg: &mut ConfigBag,
) -> Result<(), BoxError> {
tracing::debug!("FailingInterceptorA called!");
Err("FailingInterceptorA".into())
}
}
#[derive(Debug)]
struct FailingInterceptorB;
impl Intercept for FailingInterceptorB {
fn name(&self) -> &'static str { "FailingInterceptorB" }
fn $interceptor(
&self,
_ctx: $ctx,
$($rc_arg)*
_cfg: &mut ConfigBag,
) -> Result<(), BoxError> {
tracing::debug!("FailingInterceptorB called!");
Err("FailingInterceptorB".into())
}
}
#[derive(Debug)]
struct FailingInterceptorC;
impl Intercept for FailingInterceptorC {
fn name(&self) -> &'static str { "FailingInterceptorC" }
fn $interceptor(
&self,
_ctx: $ctx,
$($rc_arg)*
_cfg: &mut ConfigBag,
) -> Result<(), BoxError> {
tracing::debug!("FailingInterceptorC called!");
Err("FailingInterceptorC".into())
}
}
#[derive(Debug)]
struct FailingInterceptorsClientRuntimePlugin(RuntimeComponentsBuilder);
impl FailingInterceptorsClientRuntimePlugin {
fn new() -> Self {
Self(RuntimeComponentsBuilder::new("test").with_interceptor(SharedInterceptor::new(FailingInterceptorA)))
}
}
impl RuntimePlugin for FailingInterceptorsClientRuntimePlugin {
fn runtime_components(&self, _: &RuntimeComponentsBuilder) -> Cow<'_, RuntimeComponentsBuilder> {
Cow::Borrowed(&self.0)
}
}
#[derive(Debug)]
struct FailingInterceptorsOperationRuntimePlugin(RuntimeComponentsBuilder);
impl FailingInterceptorsOperationRuntimePlugin {
fn new() -> Self {
Self(
RuntimeComponentsBuilder::new("test")
.with_interceptor(SharedInterceptor::new(FailingInterceptorB))
.with_interceptor(SharedInterceptor::new(FailingInterceptorC))
)
}
}
impl RuntimePlugin for FailingInterceptorsOperationRuntimePlugin {
fn runtime_components(&self, _: &RuntimeComponentsBuilder) -> Cow<'_, RuntimeComponentsBuilder> {
Cow::Borrowed(&self.0)
}
}
let input = Input::doesnt_matter();
let runtime_plugins = RuntimePlugins::new()
.with_client_plugin(FailingInterceptorsClientRuntimePlugin::new())
.with_operation_plugin(TestOperationRuntimePlugin::new())
.with_operation_plugin(NoAuthRuntimePlugin::new())
.with_operation_plugin(FailingInterceptorsOperationRuntimePlugin::new());
let actual = invoke("test", "test", input, &runtime_plugins)
.await
.expect_err("should error");
let actual = format!("{:?}", actual);
assert!(
actual.starts_with(&$expected),
"\nActual error: {actual}\nShould start with: {}\n",
$expected
);
assert!(logs_contain("FailingInterceptorA called!"));
assert!(logs_contain("FailingInterceptorB called!"));
assert!(logs_contain("FailingInterceptorC called!"));
};
}
#[tokio::test]
#[traced_test]
async fn test_read_before_execution_error_handling() {
let expected = r#"ConstructionFailure(ConstructionFailure { source: InterceptorError { kind: ReadBeforeExecution, interceptor_name: Some("FailingInterceptorC"), source: Some("FailingInterceptorC") } })"#.to_string();
interceptor_error_handling_test!(
read_before_execution,
&BeforeSerializationInterceptorContextRef<'_>,
expected,
);
}
#[tokio::test]
#[traced_test]
async fn test_modify_before_serialization_error_handling() {
let expected = r#"ConstructionFailure(ConstructionFailure { source: InterceptorError { kind: ModifyBeforeSerialization, interceptor_name: Some("FailingInterceptorC"), source: Some("FailingInterceptorC") } })"#.to_string();
interceptor_error_handling_test!(
modify_before_serialization,
&mut BeforeSerializationInterceptorContextMut<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_read_before_serialization_error_handling() {
let expected = r#"ConstructionFailure(ConstructionFailure { source: InterceptorError { kind: ReadBeforeSerialization, interceptor_name: Some("FailingInterceptorC"), source: Some("FailingInterceptorC") } })"#.to_string();
interceptor_error_handling_test!(
read_before_serialization,
&BeforeSerializationInterceptorContextRef<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_read_after_serialization_error_handling() {
let expected = r#"DispatchFailure(DispatchFailure { source: ConnectorError { kind: Other(None), source: InterceptorError { kind: ReadAfterSerialization, interceptor_name: Some("FailingInterceptorC")"#.to_string();
interceptor_error_handling_test!(
read_after_serialization,
&BeforeTransmitInterceptorContextRef<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_modify_before_retry_loop_error_handling() {
let expected = r#"DispatchFailure(DispatchFailure { source: ConnectorError { kind: Other(None), source: InterceptorError { kind: ModifyBeforeRetryLoop, interceptor_name: Some("FailingInterceptorC")"#.to_string();
interceptor_error_handling_test!(
modify_before_retry_loop,
&mut BeforeTransmitInterceptorContextMut<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_read_before_attempt_error_handling() {
let expected = r#"DispatchFailure(DispatchFailure { source: ConnectorError { kind: Other(None), source: InterceptorError { kind: ReadBeforeAttempt, interceptor_name: Some("FailingInterceptorC")"#;
interceptor_error_handling_test!(
read_before_attempt,
&BeforeTransmitInterceptorContextRef<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_modify_before_signing_error_handling() {
let expected = r#"DispatchFailure(DispatchFailure { source: ConnectorError { kind: Other(None), source: InterceptorError { kind: ModifyBeforeSigning, interceptor_name: Some("FailingInterceptorC")"#;
interceptor_error_handling_test!(
modify_before_signing,
&mut BeforeTransmitInterceptorContextMut<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_read_before_signing_error_handling() {
let expected = r#"DispatchFailure(DispatchFailure { source: ConnectorError { kind: Other(None), source: InterceptorError { kind: ReadBeforeSigning, interceptor_name: Some("FailingInterceptorC")"#;
interceptor_error_handling_test!(
read_before_signing,
&BeforeTransmitInterceptorContextRef<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_read_after_signing_error_handling() {
let expected = r#"DispatchFailure(DispatchFailure { source: ConnectorError { kind: Other(None), source: InterceptorError { kind: ReadAfterSigning, interceptor_name: Some("FailingInterceptorC")"#;
interceptor_error_handling_test!(
read_after_signing,
&BeforeTransmitInterceptorContextRef<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_modify_before_transmit_error_handling() {
let expected = r#"DispatchFailure(DispatchFailure { source: ConnectorError { kind: Other(None), source: InterceptorError { kind: ModifyBeforeTransmit, interceptor_name: Some("FailingInterceptorC")"#;
interceptor_error_handling_test!(
modify_before_transmit,
&mut BeforeTransmitInterceptorContextMut<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_read_before_transmit_error_handling() {
let expected = r#"DispatchFailure(DispatchFailure { source: ConnectorError { kind: Other(None), source: InterceptorError { kind: ReadBeforeTransmit, interceptor_name: Some("FailingInterceptorC")"#;
interceptor_error_handling_test!(
read_before_transmit,
&BeforeTransmitInterceptorContextRef<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_read_after_transmit_error_handling() {
let expected = r#"ResponseError(ResponseError { source: InterceptorError { kind: ReadAfterTransmit, interceptor_name: Some("FailingInterceptorC")"#;
interceptor_error_handling_test!(
read_after_transmit,
&BeforeDeserializationInterceptorContextRef<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_modify_before_deserialization_error_handling() {
let expected = r#"ResponseError(ResponseError { source: InterceptorError { kind: ModifyBeforeDeserialization, interceptor_name: Some("FailingInterceptorC")"#;
interceptor_error_handling_test!(
modify_before_deserialization,
&mut BeforeDeserializationInterceptorContextMut<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_read_before_deserialization_error_handling() {
let expected = r#"ResponseError(ResponseError { source: InterceptorError { kind: ReadBeforeDeserialization, interceptor_name: Some("FailingInterceptorC")"#;
interceptor_error_handling_test!(
read_before_deserialization,
&BeforeDeserializationInterceptorContextRef<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_read_after_deserialization_error_handling() {
let expected = r#"ResponseError(ResponseError { source: InterceptorError { kind: ReadAfterDeserialization, interceptor_name: Some("FailingInterceptorC")"#;
interceptor_error_handling_test!(
read_after_deserialization,
&AfterDeserializationInterceptorContextRef<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_modify_before_attempt_completion_error_handling() {
let expected = r#"ResponseError(ResponseError { source: InterceptorError { kind: ModifyBeforeAttemptCompletion, interceptor_name: Some("FailingInterceptorC")"#;
interceptor_error_handling_test!(
modify_before_attempt_completion,
&mut FinalizerInterceptorContextMut<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_read_after_attempt_error_handling() {
let expected = r#"ResponseError(ResponseError { source: InterceptorError { kind: ReadAfterAttempt, interceptor_name: Some("FailingInterceptorC")"#;
interceptor_error_handling_test!(
read_after_attempt,
&FinalizerInterceptorContextRef<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_modify_before_completion_error_handling() {
let expected = r#"ResponseError(ResponseError { source: InterceptorError { kind: ModifyBeforeCompletion, interceptor_name: Some("FailingInterceptorC")"#;
interceptor_error_handling_test!(
modify_before_completion,
&mut FinalizerInterceptorContextMut<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_read_after_execution_error_handling() {
let expected = r#"ResponseError(ResponseError { source: InterceptorError { kind: ReadAfterExecution, interceptor_name: Some("FailingInterceptorC")"#;
interceptor_error_handling_test!(
read_after_execution,
&FinalizerInterceptorContextRef<'_>,
expected
);
}
macro_rules! interceptor_error_redirection_test {
(read_before_execution, $origin_ctx:ty, $destination_interceptor:ident, $destination_ctx:ty, $expected:expr) => {
interceptor_error_redirection_test!(__private read_before_execution, $origin_ctx, $destination_interceptor, $destination_ctx, $expected,);
};
($origin_interceptor:ident, $origin_ctx:ty, $destination_interceptor:ident, $destination_ctx:ty, $expected:expr) => {
interceptor_error_redirection_test!(__private $origin_interceptor, $origin_ctx, $destination_interceptor, $destination_ctx, $expected, _rc: &RuntimeComponents,);
};
(__private $origin_interceptor:ident, $origin_ctx:ty, $destination_interceptor:ident, $destination_ctx:ty, $expected:expr, $($rc_arg:tt)*) => {
#[derive(Debug)]
struct OriginInterceptor;
impl Intercept for OriginInterceptor {
fn name(&self) -> &'static str { "OriginInterceptor" }
fn $origin_interceptor(
&self,
_ctx: $origin_ctx,
$($rc_arg)*
_cfg: &mut ConfigBag,
) -> Result<(), BoxError> {
tracing::debug!("OriginInterceptor called!");
Err("OriginInterceptor".into())
}
}
#[derive(Debug)]
struct DestinationInterceptor;
impl Intercept for DestinationInterceptor {
fn name(&self) -> &'static str { "DestinationInterceptor" }
fn $destination_interceptor(
&self,
_ctx: $destination_ctx,
_runtime_components: &RuntimeComponents,
_cfg: &mut ConfigBag,
) -> Result<(), BoxError> {
tracing::debug!("DestinationInterceptor called!");
Err("DestinationInterceptor".into())
}
}
#[derive(Debug)]
struct InterceptorsTestOperationRuntimePlugin(RuntimeComponentsBuilder);
impl InterceptorsTestOperationRuntimePlugin {
fn new() -> Self {
Self(
RuntimeComponentsBuilder::new("test")
.with_interceptor(SharedInterceptor::new(OriginInterceptor))
.with_interceptor(SharedInterceptor::new(DestinationInterceptor))
)
}
}
impl RuntimePlugin for InterceptorsTestOperationRuntimePlugin {
fn runtime_components(&self, _: &RuntimeComponentsBuilder) -> Cow<'_, RuntimeComponentsBuilder> {
Cow::Borrowed(&self.0)
}
}
let input = Input::doesnt_matter();
let runtime_plugins = RuntimePlugins::new()
.with_operation_plugin(TestOperationRuntimePlugin::new())
.with_operation_plugin(NoAuthRuntimePlugin::new())
.with_operation_plugin(InterceptorsTestOperationRuntimePlugin::new());
let actual = invoke("test", "test", input, &runtime_plugins)
.await
.expect_err("should error");
let actual = format!("{:?}", actual);
assert!(
actual.starts_with(&$expected),
"\nActual error: {actual}\nShould start with: {}\n",
$expected
);
assert!(logs_contain("OriginInterceptor called!"));
assert!(logs_contain("DestinationInterceptor called!"));
};
}
#[tokio::test]
#[traced_test]
async fn test_read_before_execution_error_causes_jump_to_modify_before_completion() {
let expected = r#"ConstructionFailure(ConstructionFailure { source: InterceptorError { kind: ModifyBeforeCompletion, interceptor_name: Some("DestinationInterceptor")"#;
interceptor_error_redirection_test!(
read_before_execution,
&BeforeSerializationInterceptorContextRef<'_>,
modify_before_completion,
&mut FinalizerInterceptorContextMut<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_modify_before_serialization_error_causes_jump_to_modify_before_completion() {
let expected = r#"ConstructionFailure(ConstructionFailure { source: InterceptorError { kind: ModifyBeforeCompletion, interceptor_name: Some("DestinationInterceptor")"#;
interceptor_error_redirection_test!(
modify_before_serialization,
&mut BeforeSerializationInterceptorContextMut<'_>,
modify_before_completion,
&mut FinalizerInterceptorContextMut<'_>,
expected
);
}
#[tokio::test]
#[traced_test]
async fn test_read_before_serialization_error_causes_jump_to_modify_before_completion() {
let expected = r#"ConstructionFailure(ConstructionFailure { source: InterceptorError { kind: ModifyBeforeCompletion, interceptor_name: Some("DestinationInterceptor")"#;
interceptor_error_redirection_test!(
read_before_serialization,
&BeforeSerializationInterceptorContextRef<'_>,
modify_before_completion,
&mut FinalizerInterceptorContextMut<'_>,