hey-sdk 0.31.0

Rust client for the HEY API, generated from a Smithy model of the API
Documentation
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
//! The resilience layers on the client: circuit breaker, bulkhead and rate limit, and the errors they refuse with.

mod support;

use std::sync::{Arc, Mutex};
use std::time::Duration;

use hey_sdk::observability::{Hooks, OperationInfo, OperationState, RequestInfo, RequestResult};
use hey_sdk::resilience::{
    BulkheadConfig, CircuitBreakerConfig, RateLimitConfig, ResilienceConfig,
};
use hey_sdk::{Error, ErrorCode};

use async_trait::async_trait;
use serde_json::json;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

use support::builder;

#[tokio::test]
async fn a_scope_that_keeps_failing_is_given_up_on_before_the_next_call_is_sent() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;
    let client = builder(&server)
        .max_retries(0)
        .circuit_breaker(CircuitBreakerConfig {
            failure_threshold: 2,
            ..CircuitBreakerConfig::default()
        })
        .build()
        .unwrap();

    assert_eq!(
        ErrorCode::Api,
        client.boxes().list().await.unwrap_err().code()
    );
    assert_eq!(
        ErrorCode::Api,
        client.boxes().list().await.unwrap_err().code()
    );

    let refused = client.boxes().list().await.unwrap_err();
    assert_eq!(ErrorCode::CircuitOpen, refused.code());
    assert_eq!("circuit breaker is open", refused.message());
    assert_eq!(2, server.received_requests().await.unwrap().len());
}

#[tokio::test]
async fn a_breaker_that_is_open_for_one_operation_leaves_the_others_alone() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/boxes/123.json"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({ "id": 123, "kind": "imbox", "name": "Imbox" })),
        )
        .mount(&server)
        .await;
    let client = builder(&server)
        .max_retries(0)
        .circuit_breaker(CircuitBreakerConfig {
            failure_threshold: 1,
            ..CircuitBreakerConfig::default()
        })
        .build()
        .unwrap();

    client.boxes().list().await.unwrap_err();

    assert_eq!(
        ErrorCode::CircuitOpen,
        client.boxes().list().await.unwrap_err().code()
    );
    assert!(
        client
            .boxes()
            .get(123, &hey_sdk::services::boxes::GetBoxParams::default())
            .await
            .is_ok()
    );
}

#[tokio::test]
async fn a_scope_already_running_all_it_may_refuses_the_call_beside_it() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!([]))
                .set_delay(Duration::from_millis(200)),
        )
        .mount(&server)
        .await;
    let client = builder(&server)
        .bulkhead(BulkheadConfig {
            max_concurrent: 1,
            max_wait: Duration::ZERO,
        })
        .build()
        .unwrap();

    let boxes = client.boxes();
    let (first, second) = tokio::join!(boxes.list(), boxes.list());

    assert!(first.is_ok());
    let refused = second.unwrap_err();
    assert_eq!(ErrorCode::BulkheadFull, refused.code());
    assert_eq!("bulkhead is full", refused.message());
    assert_eq!(1, server.received_requests().await.unwrap().len());

    assert!(client.boxes().list().await.is_ok());
}

/// A bulkhead with a wait to spend holds the call beside it at the gate rather than turning
/// it away, and sends it as soon as the call in flight gives its place back.
#[tokio::test]
async fn a_scope_with_a_wait_to_spend_holds_the_call_beside_it_until_there_is_room() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!([]))
                .set_delay(Duration::from_millis(50)),
        )
        .mount(&server)
        .await;
    let client = builder(&server)
        .bulkhead(BulkheadConfig {
            max_concurrent: 1,
            max_wait: Duration::from_millis(500),
        })
        .build()
        .unwrap();

    let boxes = client.boxes();
    let (first, second) = tokio::join!(boxes.list(), boxes.list());

    assert!(first.is_ok());
    assert!(second.is_ok());
    assert_eq!(2, server.received_requests().await.unwrap().len());
}

#[tokio::test]
async fn a_scope_that_is_still_busy_when_the_wait_runs_out_refuses_the_call_waiting_on_it() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!([]))
                .set_delay(Duration::from_millis(700)),
        )
        .mount(&server)
        .await;
    let client = builder(&server)
        .bulkhead(BulkheadConfig {
            max_concurrent: 1,
            max_wait: Duration::from_millis(500),
        })
        .build()
        .unwrap();

    let boxes = client.boxes();
    let (first, second) = tokio::join!(boxes.list(), boxes.list());

    assert!(first.is_ok());
    let refused = second.unwrap_err();
    assert_eq!(ErrorCode::BulkheadFull, refused.code());
    assert_eq!("bulkhead is full", refused.message());
    assert_eq!(1, server.received_requests().await.unwrap().len());
}

#[tokio::test]
async fn a_client_that_has_spent_its_budget_refuses_before_it_sends() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!([])))
        .mount(&server)
        .await;
    let client = builder(&server)
        .rate_limit(RateLimitConfig {
            requests_per_second: 0.0001,
            burst_size: 1,
            ..RateLimitConfig::default()
        })
        .build()
        .unwrap();

    client.boxes().list().await.unwrap();

    let refused = client.boxes().list().await.unwrap_err();
    assert_eq!(ErrorCode::RateLimit, refused.code());
    assert_eq!("rate limit exceeded", refused.message());
    assert_eq!(None, refused.http_status());
    assert_eq!(1, server.received_requests().await.unwrap().len());
}

#[tokio::test]
async fn the_wait_hey_asked_for_holds_the_next_call_back() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .respond_with(ResponseTemplate::new(429).insert_header("Retry-After", "30"))
        .mount(&server)
        .await;
    let client = builder(&server)
        .max_retries(0)
        .rate_limit(RateLimitConfig::default())
        .build()
        .unwrap();

    let answered = client.boxes().list().await.unwrap_err();
    assert_eq!(ErrorCode::RateLimit, answered.code());
    assert_eq!(Some(429), answered.http_status());

    let refused = client.boxes().list().await.unwrap_err();
    assert_eq!(ErrorCode::RateLimit, refused.code());
    assert_eq!("rate limit exceeded", refused.message());
    assert_eq!(None, refused.http_status());
    assert_eq!(1, server.received_requests().await.unwrap().len());
}

/// Go's chain gates through the first member that can gate and stops, so installing two
/// layers there quietly runs only the outer one. Every layer installed here is asked.
#[tokio::test]
async fn every_layer_installed_gates_the_call() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;
    let client = builder(&server)
        .max_retries(0)
        .circuit_breaker(CircuitBreakerConfig {
            failure_threshold: 1,
            ..CircuitBreakerConfig::default()
        })
        .rate_limit(RateLimitConfig::default())
        .build()
        .unwrap();

    client.boxes().list().await.unwrap_err();

    let refused = client.boxes().list().await.unwrap_err();
    assert_eq!(ErrorCode::CircuitOpen, refused.code());
    assert_eq!(1, server.received_requests().await.unwrap().len());
}

#[tokio::test]
async fn the_hooks_that_were_already_on_hear_everything_they_would_have() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!([])))
        .mount(&server)
        .await;
    let recorder = Arc::new(Recorder::default());

    builder(&server)
        .hooks(recorder.clone())
        .resilience(ResilienceConfig::default())
        .build()
        .unwrap()
        .boxes()
        .list()
        .await
        .unwrap();

    assert_eq!(
        [
            "gate Boxes.ListBoxes",
            "start Boxes.ListBoxes",
            "request start GET",
            "request end 200",
            "end Boxes.ListBoxes carrying its own",
        ],
        recorder.entries().as_slice()
    );
}

/// A caller can walk away from a call — a `timeout` that expired, a `select!` that took
/// another branch — and the future is dropped where it stands. The operation still has to
/// end: a start with no end leaves the scope's bulkhead a permit short for the life of the
/// client, and the next call to that scope would be refused for room that is not taken.
#[tokio::test]
async fn a_call_the_caller_gave_up_on_still_ends_and_gives_back_its_permit() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!([]))
                .set_delay(Duration::from_millis(300)),
        )
        .mount(&server)
        .await;
    let lifecycle = Arc::new(Lifecycle::default());
    let client = builder(&server)
        .hooks(lifecycle.clone())
        .bulkhead(BulkheadConfig {
            max_concurrent: 1,
            max_wait: Duration::ZERO,
        })
        .build()
        .unwrap();

    let abandoned = tokio::time::timeout(Duration::from_millis(30), client.boxes().list()).await;

    assert!(abandoned.is_err(), "the call was meant to outlast the wait");
    assert_eq!(
        [
            "start Boxes.ListBoxes",
            "end Boxes.ListBoxes: operation cancelled"
        ],
        lifecycle.entries().as_slice()
    );

    client.boxes().list().await.unwrap();

    assert_eq!(
        [
            "start Boxes.ListBoxes",
            "end Boxes.ListBoxes: operation cancelled",
            "start Boxes.ListBoxes",
            "end Boxes.ListBoxes: ok",
        ],
        lifecycle.entries().as_slice()
    );
}

/// Every operation's start and how it ended, for the calls where the ending is the point.
#[derive(Default)]
struct Lifecycle {
    entries: Mutex<Vec<String>>,
}

impl Lifecycle {
    fn entries(&self) -> Vec<String> {
        self.entries.lock().unwrap().clone()
    }
}

impl Hooks for Lifecycle {
    fn on_operation_start(&self, op: &OperationInfo) -> OperationState {
        self.entries
            .lock()
            .unwrap()
            .push(format!("start {}.{}", op.service, op.operation));
        None
    }

    fn on_operation_end(
        &self,
        op: &OperationInfo,
        _state: OperationState,
        outcome: Result<(), &Error>,
        _duration: Duration,
    ) {
        let ended = match outcome {
            Ok(()) => "ok".to_string(),
            Err(error) => error.message().to_string(),
        };
        self.entries
            .lock()
            .unwrap()
            .push(format!("end {}.{}: {ended}", op.service, op.operation));
    }
}

/// Hooks installed before the resilience layers, kept as their inner hooks.
#[derive(Default)]
struct Recorder {
    entries: Mutex<Vec<String>>,
}

impl Recorder {
    fn entries(&self) -> Vec<String> {
        self.entries.lock().unwrap().clone()
    }

    fn record(&self, entry: String) {
        self.entries.lock().unwrap().push(entry);
    }
}

#[async_trait]
impl Hooks for Recorder {
    async fn on_operation_gate(&self, op: &OperationInfo) -> Result<(), Error> {
        self.record(format!("gate {}.{}", op.service, op.operation));
        Ok(())
    }

    fn on_operation_start(&self, op: &OperationInfo) -> OperationState {
        self.record(format!("start {}.{}", op.service, op.operation));
        Some(Box::new("its own"))
    }

    fn on_operation_end(
        &self,
        op: &OperationInfo,
        state: OperationState,
        _outcome: Result<(), &Error>,
        _duration: Duration,
    ) {
        let carried = match state.and_then(|state| state.downcast::<&str>().ok()) {
            Some(carried) => *carried,
            None => "nothing",
        };
        self.record(format!(
            "end {}.{} carrying {carried}",
            op.service, op.operation
        ));
    }

    fn on_request_start(&self, info: &RequestInfo) {
        self.record(format!("request start {}", info.method));
    }

    fn on_request_end(&self, _info: &RequestInfo, result: &RequestResult<'_>) {
        self.record(format!("request end {}", result.status.unwrap().as_u16()));
    }
}