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
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
//! What the hooks hear: every operation and request the client makes, in order, with what it meant.

mod support;

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

use hey_sdk::cache::InMemoryCache;
use hey_sdk::observability::{
    ChainHooks, Hooks, NoopHooks, OperationInfo, OperationState, RequestInfo, RequestResult,
};
use hey_sdk::{Client, Config, Error, ErrorCode, StaticTokenProvider, TokenProvider};

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

use support::builder;

#[tokio::test]
async fn a_read_is_announced_once_around_the_request_it_takes() {
    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 = Recorder::new();

    builder(&server)
        .hooks(recorder.clone())
        .build()
        .unwrap()
        .boxes()
        .list()
        .await
        .unwrap();

    let started = recorder.operations();
    assert_eq!(started.len(), 1);
    assert_eq!(started[0].service, "Boxes");
    assert_eq!(started[0].operation, "ListBoxes");
    assert_eq!(started[0].resource_type, "box");
    assert!(!started[0].is_mutation);
    assert_eq!(started[0].resource_id, None);
    assert_eq!(recorder.endings(), [None]);
    assert_eq!(recorder.attempts(), ["GET /boxes.json 1"]);
    assert_eq!(recorder.answers(), ["1 200 retryable=false"]);
    assert!(recorder.retries().is_empty());
}

#[tokio::test]
async fn a_write_says_so_and_names_the_record_it_changes() {
    let server = MockServer::start().await;
    Mock::given(method("DELETE"))
        .and(path("/calendar/habits/456.json"))
        .respond_with(ResponseTemplate::new(204))
        .mount(&server)
        .await;
    let recorder = Recorder::new();

    builder(&server)
        .hooks(recorder.clone())
        .build()
        .unwrap()
        .habits()
        .delete(456)
        .await
        .unwrap();

    let started = recorder.operations();
    assert_eq!(started.len(), 1);
    assert_eq!(started[0].service, "Habits");
    assert_eq!(started[0].operation, "DeleteHabit");
    assert_eq!(started[0].resource_type, "habit");
    assert!(started[0].is_mutation);
    assert_eq!(started[0].resource_id, Some(456));
}

#[tokio::test]
async fn a_read_of_one_record_names_it() {
    let server = MockServer::start().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 recorder = Recorder::new();

    builder(&server)
        .hooks(recorder.clone())
        .build()
        .unwrap()
        .boxes()
        .get(123, &hey_sdk::services::boxes::GetBoxParams::default())
        .await
        .unwrap();

    assert_eq!(recorder.operations()[0].resource_id, Some(123));
}

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

    builder(&server)
        .hooks(recorder.clone())
        .build()
        .unwrap()
        .boxes()
        .list()
        .await
        .unwrap();

    assert_eq!(
        recorder.attempts(),
        [
            "GET /boxes.json 1",
            "GET /boxes.json 2",
            "GET /boxes.json 3"
        ]
    );
    assert_eq!(
        recorder.answers(),
        [
            "1 503 retryable=true",
            "2 503 retryable=true",
            "3 200 retryable=false"
        ]
    );
    assert_eq!(
        recorder.retries(),
        [
            "1 -> 2 api_error API error: 503 Service Unavailable retryable",
            "2 -> 3 api_error API error: 503 Service Unavailable retryable"
        ]
    );
    assert_eq!(recorder.endings(), [None]);
}

#[tokio::test]
async fn a_resend_after_a_refreshed_credential_is_a_retry_of_its_own() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .and(header("authorization", "Bearer stale-token"))
        .respond_with(ResponseTemplate::new(401))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .and(header("authorization", "Bearer fresh-token"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!([])))
        .mount(&server)
        .await;
    let recorder = Recorder::new();

    builder(&server)
        .token_provider(RefreshingToken::new())
        .hooks(recorder.clone())
        .build()
        .unwrap()
        .boxes()
        .list()
        .await
        .unwrap();

    assert_eq!(
        recorder.attempts(),
        ["GET /boxes.json 1", "GET /boxes.json 2"]
    );
    assert_eq!(
        recorder.retries(),
        ["1 -> 2 auth_required Token refreshed retryable"]
    );
}

#[tokio::test]
async fn a_request_that_never_arrives_is_a_retry_with_a_network_error() {
    let recorder = Recorder::new();
    let client = Client::builder(Config::default().with_base_url("http://127.0.0.1:1"))
        .token_provider(StaticTokenProvider::new("t"))
        .http_client(support::http_client())
        .base_delay(Duration::from_millis(1))
        .max_jitter(Duration::ZERO)
        .max_retries(1)
        .hooks(recorder.clone())
        .build()
        .unwrap();

    let error = client.boxes().list().await.unwrap_err();

    assert_eq!(error.code(), ErrorCode::Network);
    assert_eq!(
        recorder.answers(),
        ["1 - retryable=true", "2 - retryable=true"]
    );
    assert_eq!(recorder.retries().len(), 1);
    assert!(
        recorder.retries()[0].starts_with("1 -> 2 network Network error"),
        "reported {:?}",
        recorder.retries()[0]
    );
    assert_eq!(recorder.endings(), [Some("Network error".to_string())]);
}

#[tokio::test]
async fn a_gate_that_refuses_stops_the_operation_before_anything_is_sent() {
    let server = MockServer::start().await;
    let recorder = Recorder::new();
    let hooks = ChainHooks::of(vec![Arc::new(Refusing), recorder.clone()]);

    let error = builder(&server)
        .hooks(hooks)
        .build()
        .unwrap()
        .boxes()
        .list()
        .await
        .unwrap_err();

    assert_eq!(error.code(), ErrorCode::Usage);
    assert_eq!(error.message(), "blocked");
    assert!(server.received_requests().await.unwrap().is_empty());
    assert!(recorder.operations().is_empty());
    assert!(recorder.endings().is_empty());
}

#[tokio::test]
async fn the_end_hook_is_handed_what_the_start_hook_made() {
    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 stateful = Arc::new(Stateful::default());

    let client = builder(&server).hooks(stateful.clone()).build().unwrap();
    client.boxes().list().await.unwrap();
    client.boxes().list().await.unwrap();

    assert_eq!(stateful.carried(), ["ListBoxes 1", "ListBoxes 2"]);
}

#[tokio::test]
async fn a_body_read_from_the_cache_says_so() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .and(header("if-none-match", "\"v1\""))
        .respond_with(ResponseTemplate::new(304).insert_header("ETag", "\"v1\""))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("ETag", "\"v1\"")
                .set_body_json(json!([{ "id": 7, "kind": "imbox", "name": "Imbox" }])),
        )
        .mount(&server)
        .await;
    let recorder = Recorder::new();

    let client = builder(&server)
        .cache(InMemoryCache::new())
        .hooks(recorder.clone())
        .build()
        .unwrap();
    client.boxes().list().await.unwrap();
    client.boxes().list().await.unwrap();

    assert_eq!(recorder.cached(), [false, true]);
}

#[tokio::test]
async fn a_rate_limited_request_carries_the_wait_the_server_asked_for() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/boxes.json"))
        .respond_with(ResponseTemplate::new(429).insert_header("Retry-After", "17"))
        .mount(&server)
        .await;
    let recorder = Recorder::new();

    let error = builder(&server)
        .max_retries(0)
        .hooks(recorder.clone())
        .build()
        .unwrap()
        .boxes()
        .list()
        .await
        .unwrap_err();

    assert_eq!(error.code(), ErrorCode::RateLimit);
    assert_eq!(recorder.waits(), [Some(17)]);
    assert_eq!(recorder.answers(), ["1 429 retryable=true"]);
    assert_eq!(recorder.endings(), [Some(error.message().to_string())]);
}

#[tokio::test]
async fn a_client_told_to_use_noop_hooks_reports_nothing() {
    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;

    builder(&server)
        .hooks(NoopHooks)
        .build()
        .unwrap()
        .boxes()
        .list()
        .await
        .unwrap();

    assert_eq!(server.received_requests().await.unwrap().len(), 1);
}

#[tokio::test]
async fn a_wrapper_can_announce_itself_as_something_other_than_the_route_it_sends() {
    let server = MockServer::start().await;
    Mock::given(method("PUT"))
        .and(path("/calendar/time_tracks/701.json"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "id": 701 })))
        .mount(&server)
        .await;
    let recorder = Recorder::new();
    let client = builder(&server).hooks(recorder.clone()).build().unwrap();

    let mut operation = client.operation(&hey_sdk::routes::UPDATE_TIME_TRACK, &[&701]);
    operation
        .operation_name("StopTimeTrack")
        .resource_type("time_track")
        .resource_id(701);
    client.send_unit(operation).await.unwrap();

    let started = recorder.operations();
    assert_eq!(started[0].service, "TimeTracks");
    assert_eq!(started[0].operation, "StopTimeTrack");
    assert_eq!(started[0].resource_type, "time_track");
    assert_eq!(started[0].resource_id, Some(701));
    assert!(started[0].is_mutation);
}

/// Everything the hooks were told, kept so a test can assert on it afterwards.
#[derive(Default)]
struct Recorder {
    operations: Mutex<Vec<OperationInfo>>,
    endings: Mutex<Vec<Option<String>>>,
    attempts: Mutex<Vec<String>>,
    answers: Mutex<Vec<String>>,
    cached: Mutex<Vec<bool>>,
    waits: Mutex<Vec<Option<u64>>>,
    retries: Mutex<Vec<String>>,
}

impl Recorder {
    fn new() -> Arc<Recorder> {
        Arc::new(Recorder::default())
    }

    fn operations(&self) -> Vec<OperationInfo> {
        self.operations.lock().unwrap().clone()
    }

    fn endings(&self) -> Vec<Option<String>> {
        self.endings.lock().unwrap().clone()
    }

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

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

    fn cached(&self) -> Vec<bool> {
        self.cached.lock().unwrap().clone()
    }

    fn waits(&self) -> Vec<Option<u64>> {
        self.waits.lock().unwrap().clone()
    }

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

impl Hooks for Recorder {
    fn on_operation_start(&self, op: &OperationInfo) -> OperationState {
        self.operations.lock().unwrap().push(op.clone());
        None
    }

    fn on_operation_end(
        &self,
        _op: &OperationInfo,
        _state: OperationState,
        outcome: Result<(), &Error>,
        _duration: Duration,
    ) {
        let ending = outcome.err().map(|error| error.message().to_string());
        self.endings.lock().unwrap().push(ending);
    }

    fn on_request_start(&self, info: &RequestInfo) {
        self.attempts.lock().unwrap().push(format!(
            "{} {} {}",
            info.method,
            info.url.path(),
            info.attempt
        ));
    }

    fn on_request_end(&self, info: &RequestInfo, result: &RequestResult<'_>) {
        let status = match result.status {
            Some(status) => status.as_u16().to_string(),
            None => "-".to_string(),
        };
        self.answers.lock().unwrap().push(format!(
            "{} {status} retryable={}",
            info.attempt, result.retryable
        ));
        self.cached.lock().unwrap().push(result.from_cache);
        self.waits.lock().unwrap().push(result.retry_after);
    }

    fn on_retry(&self, info: &RequestInfo, next_attempt: u32, cause: &Error) {
        let retryable = if cause.is_retryable() {
            "retryable"
        } else {
            "final"
        };
        self.retries.lock().unwrap().push(format!(
            "{} -> {next_attempt} {} {} {retryable}",
            info.attempt,
            cause.code(),
            cause.message()
        ));
    }
}

/// Hooks that hand their end a token their start made, to prove the two are paired.
#[derive(Default)]
struct Stateful {
    issued: Mutex<u32>,
    carried: Mutex<Vec<String>>,
}

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

impl Hooks for Stateful {
    fn on_operation_start(&self, _op: &OperationInfo) -> OperationState {
        let mut issued = self.issued.lock().unwrap();
        *issued += 1;
        Some(Box::new(*issued))
    }

    fn on_operation_end(
        &self,
        op: &OperationInfo,
        state: OperationState,
        _outcome: Result<(), &Error>,
        _duration: Duration,
    ) {
        let token = state
            .and_then(|state| state.downcast::<u32>().ok())
            .expect("the start hook's token");
        self.carried
            .lock()
            .unwrap()
            .push(format!("{} {token}", op.operation));
    }
}

struct Refusing;

#[async_trait]
impl Hooks for Refusing {
    async fn on_operation_gate(&self, _op: &OperationInfo) -> Result<(), Error> {
        Err(Error::usage("blocked"))
    }
}

/// A provider whose credentials can be renewed, so the first 401 is answered by a resend.
struct RefreshingToken {
    token: Mutex<String>,
}

impl RefreshingToken {
    fn new() -> RefreshingToken {
        RefreshingToken {
            token: Mutex::new("stale-token".to_string()),
        }
    }
}

#[async_trait]
impl TokenProvider for RefreshingToken {
    async fn access_token(&self) -> Result<String, Error> {
        Ok(self.token.lock().unwrap().clone())
    }

    async fn refresh(&self) -> bool {
        *self.token.lock().unwrap() = "fresh-token".to_string();
        true
    }
}