-
Notifications
You must be signed in to change notification settings - Fork 246
/
reconnect_on_transient_error.rs
313 lines (290 loc) · 9.23 KB
/
reconnect_on_transient_error.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
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#![cfg(all(
feature = "client",
feature = "wire-mock",
feature = "connector-hyper-0-14-x",
))]
use ::aws_smithy_runtime::client::retries::classifiers::{
HttpStatusCodeClassifier, TransientErrorClassifier,
};
use aws_smithy_async::rt::sleep::TokioSleep;
use aws_smithy_runtime::client::http::hyper_014::HyperClientBuilder;
use aws_smithy_runtime::client::http::test_util::wire::{
RecordedEvent, ReplayedEvent, WireMockServer,
};
use aws_smithy_runtime::client::orchestrator::operation::Operation;
use aws_smithy_runtime::test_util::capture_test_logs::capture_test_logs;
use aws_smithy_runtime::{ev, match_events};
use aws_smithy_runtime_api::client::interceptors::context::InterceptorContext;
use aws_smithy_runtime_api::client::orchestrator::OrchestratorError;
use aws_smithy_runtime_api::client::retries::classifiers::{ClassifyRetry, RetryAction};
use aws_smithy_types::body::SdkBody;
use aws_smithy_types::retry::{ErrorKind, ProvideErrorKind, ReconnectMode, RetryConfig};
use aws_smithy_types::timeout::TimeoutConfig;
use hyper_0_14::client::Builder as HyperBuilder;
use std::fmt;
use std::time::Duration;
const END_OF_TEST: &str = "end_of_test";
#[derive(Debug)]
struct OperationError(ErrorKind);
impl fmt::Display for OperationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl ProvideErrorKind for OperationError {
fn retryable_error_kind(&self) -> Option<ErrorKind> {
Some(self.0)
}
fn code(&self) -> Option<&str> {
None
}
}
impl std::error::Error for OperationError {}
#[derive(Debug)]
struct TestRetryClassifier;
impl ClassifyRetry for TestRetryClassifier {
fn classify_retry(&self, ctx: &InterceptorContext) -> RetryAction {
tracing::info!("classifying retry for {ctx:?}");
// Check for a result
let output_or_error = ctx.output_or_error();
// Check for an error
let error = match output_or_error {
Some(Ok(_)) | None => return RetryAction::NoActionIndicated,
Some(Err(err)) => err,
};
let action = if let Some(err) = error.as_operation_error() {
tracing::info!("its an operation error: {err:?}");
let err = err.downcast_ref::<OperationError>().unwrap();
RetryAction::retryable_error(err.0)
} else {
tracing::info!("its something else... using other classifiers");
let action = TransientErrorClassifier::<OperationError>::new().classify_retry(ctx);
if action == RetryAction::NoActionIndicated {
HttpStatusCodeClassifier::default().classify_retry(ctx)
} else {
action
}
};
tracing::info!("classified as {action:?}");
action
}
fn name(&self) -> &'static str {
"test"
}
}
async fn h1_and_h2(events: Vec<ReplayedEvent>, match_clause: impl Fn(&[RecordedEvent])) {
wire_level_test(
events.clone(),
|_b| {},
ReconnectMode::ReconnectOnTransientError,
&match_clause,
)
.await;
wire_level_test(
events,
|b| {
b.http2_only(true);
},
ReconnectMode::ReconnectOnTransientError,
match_clause,
)
.await;
tracing::info!("h2 ok!");
}
/// Repeatedly send test operation until `end_of_test` is received
///
/// When the test is over, match_clause is evaluated
async fn wire_level_test(
events: Vec<ReplayedEvent>,
hyper_builder_settings: impl Fn(&mut HyperBuilder),
reconnect_mode: ReconnectMode,
match_clause: impl Fn(&[RecordedEvent]),
) {
let mut hyper_builder = hyper_0_14::Client::builder();
hyper_builder_settings(&mut hyper_builder);
let mock = WireMockServer::start(events).await;
let http_client = HyperClientBuilder::new()
.hyper_builder(hyper_builder)
.build(hyper_0_14::client::HttpConnector::new_with_resolver(
mock.dns_resolver(),
));
let operation = Operation::builder()
.service_name("test")
.operation_name("test")
.no_auth()
.endpoint_url(&mock.endpoint_url())
.http_client(http_client)
.timeout_config(
TimeoutConfig::builder()
.operation_attempt_timeout(Duration::from_millis(100))
.build(),
)
.standard_retry(&RetryConfig::standard().with_reconnect_mode(reconnect_mode))
.retry_classifier(TestRetryClassifier)
.sleep_impl(TokioSleep::new())
.with_connection_poisoning()
.serializer({
let endpoint_url = mock.endpoint_url();
move |_| {
let request = http::Request::builder()
.uri(endpoint_url.clone())
// Make the body non-replayable since we don't actually want to retry
.body(SdkBody::from_body_0_4(SdkBody::from("body")))
.unwrap()
.try_into()
.unwrap();
tracing::info!("serializing request: {request:?}");
Ok(request)
}
})
.deserializer(|response| {
tracing::info!("deserializing response: {:?}", response);
match response.status() {
s if s.is_success() => {
Ok(String::from_utf8(response.body().bytes().unwrap().into()).unwrap())
}
s if s.is_client_error() => Err(OrchestratorError::operation(OperationError(
ErrorKind::ServerError,
))),
s if s.is_server_error() => Err(OrchestratorError::operation(OperationError(
ErrorKind::TransientError,
))),
_ => panic!("unexpected status: {}", response.status()),
}
})
.build();
let mut iteration = 0;
loop {
tracing::info!("iteration {iteration}...");
match operation.invoke(()).await {
Ok(resp) => {
tracing::info!("response: {:?}", resp);
if resp == END_OF_TEST {
break;
}
}
Err(e) => tracing::info!("error: {:?}", e),
}
iteration += 1;
if iteration > 50 {
panic!("probably an infinite loop; no satisfying 'end_of_test' response received");
}
}
let events = mock.events();
match_clause(&events);
mock.shutdown();
}
#[tokio::test]
async fn non_transient_errors_no_reconnect() {
let _logs = capture_test_logs();
h1_and_h2(
vec![
ReplayedEvent::status(400),
ReplayedEvent::with_body(END_OF_TEST),
],
match_events!(ev!(dns), ev!(connect), ev!(http(400)), ev!(http(200))),
)
.await
}
#[tokio::test]
async fn reestablish_dns_on_503() {
let _logs = capture_test_logs();
h1_and_h2(
vec![
ReplayedEvent::status(503),
ReplayedEvent::status(503),
ReplayedEvent::status(503),
ReplayedEvent::with_body(END_OF_TEST),
],
match_events!(
// first request
ev!(dns),
ev!(connect),
ev!(http(503)),
// second request
ev!(dns),
ev!(connect),
ev!(http(503)),
// third request
ev!(dns),
ev!(connect),
ev!(http(503)),
// all good
ev!(dns),
ev!(connect),
ev!(http(200))
),
)
.await;
}
#[tokio::test]
async fn connection_shared_on_success() {
let _logs = capture_test_logs();
h1_and_h2(
vec![
ReplayedEvent::ok(),
ReplayedEvent::ok(),
ReplayedEvent::status(503),
ReplayedEvent::with_body(END_OF_TEST),
],
match_events!(
ev!(dns),
ev!(connect),
ev!(http(200)),
ev!(http(200)),
ev!(http(503)),
ev!(dns),
ev!(connect),
ev!(http(200))
),
)
.await;
}
#[tokio::test]
async fn no_reconnect_when_disabled() {
let _logs = capture_test_logs();
wire_level_test(
vec![
ReplayedEvent::status(503),
ReplayedEvent::with_body(END_OF_TEST),
],
|_b| {},
ReconnectMode::ReuseAllConnections,
match_events!(ev!(dns), ev!(connect), ev!(http(503)), ev!(http(200))),
)
.await;
}
#[tokio::test]
async fn connection_reestablished_after_timeout() {
let _logs = capture_test_logs();
h1_and_h2(
vec![
ReplayedEvent::ok(),
ReplayedEvent::Timeout,
ReplayedEvent::ok(),
ReplayedEvent::Timeout,
ReplayedEvent::with_body(END_OF_TEST),
],
match_events!(
// first connection
ev!(dns),
ev!(connect),
ev!(http(200)),
// reuse but got a timeout
ev!(timeout),
// so we reconnect
ev!(dns),
ev!(connect),
ev!(http(200)),
ev!(timeout),
ev!(dns),
ev!(connect),
ev!(http(200))
),
)
.await;
}