-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathapi.rs
More file actions
1277 lines (1154 loc) · 43.2 KB
/
api.rs
File metadata and controls
1277 lines (1154 loc) · 43.2 KB
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
use std::{ops::Deref, pin::Pin, sync::Arc, time::Duration};
use async_stream::try_stream;
use async_trait::async_trait;
use bytes::BytesMut;
use futures::{Stream, StreamExt};
use http::{
HeaderMap, HeaderValue, StatusCode,
header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE, InvalidHeaderValue},
};
use prost::{self, Message};
use s2_api::v1::{
access::{
AccessTokenInfo, IssueAccessTokenResponse, ListAccessTokensRequest,
ListAccessTokensResponse,
},
basin::{
BasinInfo, CreateBasinRequest, ListBasinsRequest, ListBasinsResponse,
},
config::{BasinConfig, BasinReconfiguration, StreamConfig, StreamReconfiguration},
metrics::{
AccountMetricSetRequest, BasinMetricSetRequest, MetricSetResponse, StreamMetricSetRequest,
},
stream::{
AppendConditionFailed, CreateStreamRequest, ListStreamsRequest, ListStreamsResponse,
ReadEnd, ReadStart, StreamInfo, TailResponse,
proto::{AppendAck, AppendInput, ReadBatch},
s2s::{self, FrameDecoder, SessionMessage, TerminalMessage},
},
};
use secrecy::ExposeSecret;
use tokio_util::codec::Decoder;
use tracing::{debug, warn};
use url::Url;
#[cfg(feature = "_hidden")]
use s2_api::v1::basin::CreateOrReconfigureBasinRequest;
use crate::frame_signal::FrameSignal;
use crate::{
client::{self, StreamingResponse, UnaryResponse},
retry::{RetryBackoff, RetryBackoffBuilder},
types::{
AccessTokenId, AppendRetryPolicy, BasinAuthority, BasinName, Compression, RetryConfig,
S2Config, S2Endpoints, StreamName,
},
};
const CONTENT_TYPE_S2S: &str = "s2s/proto";
const CONTENT_TYPE_PROTO: &str = "application/protobuf";
const ACCEPT_PROTO: &str = "application/protobuf";
const S2_REQUEST_TOKEN: &str = "s2-request-token";
const S2_BASIN: &str = "s2-basin";
const RETRY_AFTER_MS_HEADER: &str = "retry-after-ms";
#[derive(Debug, Clone)]
pub struct AccountClient {
pub client: BaseClient,
pub config: Arc<S2Config>,
pub base_url: Url,
}
impl AccountClient {
pub fn init(config: S2Config, client: BaseClient) -> Self {
let base_url = base_url(&config.endpoints, ClientKind::Account);
Self {
client,
config: Arc::new(config),
base_url,
}
}
pub fn basin_client(&self, name: BasinName) -> BasinClient {
BasinClient::init(name, self.config.clone(), self.client.clone())
}
pub async fn list_access_tokens(
&self,
request: ListAccessTokensRequest,
) -> Result<ListAccessTokensResponse, ApiError> {
let url = self.base_url.join("v1/access-tokens")?;
let request = self.get(url).query(&request).build()?;
let response = self.request(request).send().await?;
Ok(response.json::<ListAccessTokensResponse>()?)
}
pub async fn issue_access_token(
&self,
info: AccessTokenInfo,
) -> Result<IssueAccessTokenResponse, ApiError> {
let url = self.base_url.join("v1/access-tokens")?;
let request = self.post(url).json(&info).build()?;
let response = self.request(request).send().await?;
Ok(response.json::<IssueAccessTokenResponse>()?)
}
pub async fn revoke_access_token(&self, id: AccessTokenId) -> Result<(), ApiError> {
let url = self
.base_url
.join(&format!("v1/access-tokens/{}", urlencoding::encode(&id)))?;
let request = self.delete(url).build()?;
let _response = self.request(request).send().await?;
Ok(())
}
pub async fn list_basins(
&self,
request: ListBasinsRequest,
) -> Result<ListBasinsResponse, ApiError> {
let url = self.base_url.join("v1/basins")?;
let request = self.get(url).query(&request).build()?;
let response = self.request(request).send().await?;
Ok(response.json::<ListBasinsResponse>()?)
}
pub async fn create_basin(
&self,
request: CreateBasinRequest,
idempotency_token: String,
) -> Result<BasinInfo, ApiError> {
let url = self.base_url.join("v1/basins")?;
let request = self
.post(url)
.header(S2_REQUEST_TOKEN, idempotency_token)
.json(&request)
.build()?;
let response = self.request(request).send().await?;
Ok(response.json::<BasinInfo>()?)
}
pub async fn get_basin_config(&self, name: BasinName) -> Result<BasinConfig, ApiError> {
let url = self.base_url.join(&format!("v1/basins/{name}"))?;
let request = self.get(url).build()?;
let response = self.request(request).send().await?;
Ok(response.json::<BasinConfig>()?)
}
pub async fn reconfigure_basin(
&self,
name: BasinName,
config: BasinReconfiguration,
) -> Result<BasinConfig, ApiError> {
let url = self.base_url.join(&format!("v1/basins/{name}"))?;
let request = self.patch(url).json(&config).build()?;
let response = self.request(request).send().await?;
Ok(response.json::<BasinConfig>()?)
}
#[cfg(feature = "_hidden")]
pub async fn create_or_reconfigure_basin(
&self,
name: BasinName,
request: Option<CreateOrReconfigureBasinRequest>,
) -> Result<(bool, BasinInfo), ApiError> {
let url = self.base_url.join(&format!("v1/basins/{name}"))?;
let request = match request {
Some(body) => self.put(url).json(&body).build()?,
None => self.put(url).build()?,
};
let response = self.request(request).send().await?;
let was_created = response.status() == StatusCode::CREATED;
Ok((was_created, response.json::<BasinInfo>()?))
}
pub async fn delete_basin(
&self,
name: BasinName,
ignore_not_found: bool,
) -> Result<(), ApiError> {
let url = self.base_url.join(&format!("v1/basins/{name}"))?;
let request = self.delete(url).build()?;
self.request(request)
.send()
.await
.ignore_not_found(ignore_not_found)?;
Ok(())
}
pub async fn get_account_metrics(
&self,
request: AccountMetricSetRequest,
) -> Result<MetricSetResponse, ApiError> {
let url = self.base_url.join("v1/metrics")?;
let request = self.get(url).query(&request).build()?;
let response = self.request(request).send().await?;
Ok(response.json::<MetricSetResponse>()?)
}
pub async fn get_basin_metrics(
&self,
name: BasinName,
request: BasinMetricSetRequest,
) -> Result<MetricSetResponse, ApiError> {
let url = self.base_url.join(&format!("v1/metrics/{name}"))?;
let request = self.get(url).query(&request).build()?;
let response = self.request(request).send().await?;
Ok(response.json::<MetricSetResponse>()?)
}
pub async fn get_stream_metrics(
&self,
basin_name: BasinName,
stream_name: StreamName,
request: StreamMetricSetRequest,
) -> Result<MetricSetResponse, ApiError> {
let url = self.base_url.join(&format!(
"v1/metrics/{basin_name}/{}",
urlencoding::encode(&stream_name)
))?;
let request = self.get(url).query(&request).build()?;
let response = self.request(request).send().await?;
Ok(response.json::<MetricSetResponse>()?)
}
}
impl Deref for AccountClient {
type Target = BaseClient;
fn deref(&self) -> &Self::Target {
&self.client
}
}
#[derive(Debug, Clone)]
pub struct BasinClient {
pub name: BasinName,
pub client: BaseClient,
pub config: Arc<S2Config>,
pub base_url: Url,
}
impl BasinClient {
pub fn init(name: BasinName, config: Arc<S2Config>, client: BaseClient) -> Self {
let base_url = base_url(&config.endpoints, ClientKind::Basin(name.clone()));
Self {
name,
client,
config,
base_url,
}
}
fn request(&self, mut request: client::Request) -> RequestBuilder<'_> {
if matches!(
self.config.endpoints.basin_authority,
BasinAuthority::Direct(_)
) {
request.headers_mut().insert(
S2_BASIN,
HeaderValue::from_str(&self.name).expect("valid header value"),
);
}
self.client.request(request)
}
pub async fn list_streams(
&self,
request: ListStreamsRequest,
) -> Result<ListStreamsResponse, ApiError> {
let url = self.base_url.join("v1/streams")?;
let request = self.get(url).query(&request).build()?;
let response = self.request(request).send().await?;
Ok(response.json::<ListStreamsResponse>()?)
}
pub async fn create_stream(
&self,
request: CreateStreamRequest,
idempotency_token: String,
) -> Result<StreamInfo, ApiError> {
let url = self.base_url.join("v1/streams")?;
let request = self
.post(url)
.header(S2_REQUEST_TOKEN, idempotency_token)
.json(&request)
.build()?;
let response = self.request(request).send().await?;
Ok(response.json::<StreamInfo>()?)
}
pub async fn get_stream_config(&self, name: StreamName) -> Result<StreamConfig, ApiError> {
let url = self
.base_url
.join(&format!("v1/streams/{}", urlencoding::encode(&name)))?;
let request = self.get(url).build()?;
let response = self.request(request).send().await?;
Ok(response.json::<StreamConfig>()?)
}
pub async fn reconfigure_stream(
&self,
name: StreamName,
config: StreamReconfiguration,
) -> Result<StreamConfig, ApiError> {
let url = self
.base_url
.join(&format!("v1/streams/{}", urlencoding::encode(&name)))?;
let request = self.patch(url).json(&config).build()?;
let response = self.request(request).send().await?;
Ok(response.json::<StreamConfig>()?)
}
#[cfg(feature = "_hidden")]
pub async fn create_or_reconfigure_stream(
&self,
name: StreamName,
config: Option<StreamReconfiguration>,
) -> Result<(bool, StreamInfo), ApiError> {
let url = self
.base_url
.join(&format!("v1/streams/{}", urlencoding::encode(&name)))?;
let request = match config {
Some(body) => self.put(url).json(&body).build()?,
None => self.put(url).build()?,
};
let response = self.request(request).send().await?;
let was_created = response.status() == StatusCode::CREATED;
Ok((was_created, response.json::<StreamInfo>()?))
}
pub async fn delete_stream(
&self,
name: StreamName,
ignore_not_found: bool,
) -> Result<(), ApiError> {
let url = self
.base_url
.join(&format!("v1/streams/{}", urlencoding::encode(&name)))?;
let request = self.delete(url).build()?;
self.request(request)
.send()
.await
.ignore_not_found(ignore_not_found)?;
Ok(())
}
pub async fn check_tail(&self, name: &StreamName) -> Result<TailResponse, ApiError> {
let url = self.base_url.join(&format!(
"v1/streams/{}/records/tail",
urlencoding::encode(name)
))?;
let request = self.get(url).build()?;
let response = self.request(request).send().await?;
Ok(response.json::<TailResponse>()?)
}
pub async fn append(
&self,
name: &StreamName,
input: AppendInput,
append_retry_policy: AppendRetryPolicy,
) -> Result<AppendAck, ApiError> {
let url = self
.base_url
.join(&format!("v1/streams/{}/records", urlencoding::encode(name)))?;
let request = self
.post(url)
.header(CONTENT_TYPE, CONTENT_TYPE_PROTO)
.header(ACCEPT, ACCEPT_PROTO)
.body(input.encode_to_vec())
.build()?;
let response = self
.request(request)
.with_append_retry_policy(append_retry_policy)
.error_handler(|status, response| {
if status == StatusCode::PRECONDITION_FAILED {
Err(ApiError::AppendConditionFailed(
response.json::<AppendConditionFailed>()?,
))
} else {
Err(ApiError::Server(
status,
response.json::<ApiErrorResponse>()?,
))
}
})
.send()
.await?;
Ok(AppendAck::decode(response.into_bytes())?)
}
pub async fn read(
&self,
name: &StreamName,
start: ReadStart,
end: ReadEnd,
) -> Result<ReadBatch, ApiError> {
let url = self
.base_url
.join(&format!("v1/streams/{}/records", urlencoding::encode(name)))?;
let mut builder = self
.get(url)
.header(ACCEPT, ACCEPT_PROTO)
.query(&start)
.query(&end);
if let Some(wait) = end.wait {
builder = builder.timeout(self.client.request_timeout + Duration::from_secs(wait.into()));
}
let request = builder.build()?;
let response = self
.request(request)
.error_handler(read_response_error_handler)
.send()
.await?;
Ok(ReadBatch::decode(response.into_bytes())?)
}
pub async fn append_session<I>(
&self,
name: &StreamName,
inputs: I,
frame_signal: Option<FrameSignal>,
) -> Result<Streaming<AppendAck>, ApiError>
where
I: Stream<Item = AppendInput> + Send + 'static,
{
let url = self
.base_url
.join(&format!("v1/streams/{}/records", urlencoding::encode(name)))?;
let compression = self.config.compression.into();
let encoded_stream = inputs.map(move |input| {
s2s::SessionMessage::regular(compression, &input).map(|msg| msg.encode())
});
let body = client::Body::wrap_stream(encoded_stream);
let body = match frame_signal {
Some(signal) => body.monitored(signal),
None => body,
};
let mut request_builder = self
.client
.post(url)
.header(CONTENT_TYPE, CONTENT_TYPE_S2S)
.body(body)
.timeout(self.client.request_timeout);
request_builder =
add_basin_header_if_required(request_builder, &self.config.endpoints, &self.name);
let response = self
.client
.init_streaming(request_builder.build()?)
.await?
.into_result()
.await?;
let mut bytes_stream = response.stream();
let mut buffer = BytesMut::new();
let mut decoder = FrameDecoder;
Ok(Box::pin(try_stream! {
while let Some(chunk) = bytes_stream.next().await {
let chunk = chunk?;
buffer.extend_from_slice(&chunk);
loop {
match decoder.decode(&mut buffer) {
Ok(Some(SessionMessage::Regular(msg))) => {
yield msg.try_into_proto()?;
}
Ok(Some(SessionMessage::Terminal(msg))) => {
Err::<(), ApiError>(msg.into())?;
}
Ok(None) => break,
Err(err) => Err(err)?,
}
}
}
}))
}
pub async fn read_session(
&self,
name: &StreamName,
start: ReadStart,
end: ReadEnd,
) -> Result<Streaming<ReadBatch>, ApiError> {
let url = self
.base_url
.join(&format!("v1/streams/{}/records", urlencoding::encode(name)))?;
let mut request_builder = self
.client
.get(url)
.header(CONTENT_TYPE, CONTENT_TYPE_S2S)
.query(&start)
.query(&end)
.timeout(self.client.request_timeout);
request_builder =
add_basin_header_if_required(request_builder, &self.config.endpoints, &self.name);
let response = self
.client
.init_streaming(request_builder.build()?)
.await?
.into_result()
.await?;
let mut bytes_stream = response.stream();
let mut buffer = BytesMut::new();
let mut decoder = FrameDecoder;
Ok(Box::pin(try_stream! {
while let Some(chunk) = bytes_stream.next().await {
let chunk = chunk?;
buffer.extend_from_slice(&chunk);
loop {
match decoder.decode(&mut buffer) {
Ok(Some(SessionMessage::Regular(msg))) => {
yield msg.try_into_proto()?;
}
Ok(Some(SessionMessage::Terminal(msg))) => {
Err::<(), ApiError>(msg.into())?;
}
Ok(None) => break,
Err(err) => Err(err)?,
}
}
}
}))
}
}
fn read_response_error_handler(
status: StatusCode,
response: UnaryResponse,
) -> Result<UnaryResponse, ApiError> {
if status == StatusCode::RANGE_NOT_SATISFIABLE {
Err(ApiError::ReadUnwritten(response.json::<TailResponse>()?))
} else {
Err(ApiError::Server(
status,
response.json::<ApiErrorResponse>()?,
))
}
}
impl Deref for BasinClient {
type Target = BaseClient;
fn deref(&self) -> &Self::Target {
&self.client
}
}
#[derive(Debug, thiserror::Error, serde::Deserialize)]
#[error("{code}: {message}")]
pub struct ApiErrorResponse {
pub code: String,
pub message: String,
}
#[derive(Debug, thiserror::Error)]
pub enum ApiError {
#[error(transparent)]
Client(#[from] ClientError),
#[error(transparent)]
Url(#[from] url::ParseError),
#[error(transparent)]
ProtoDecode(#[from] prost::DecodeError),
#[error(transparent)]
S2STerminalDecode(#[from] S2STerminalDecodeError),
#[error(transparent)]
InvalidHeaderValue(#[from] InvalidHeaderValue),
#[error(transparent)]
Compression(#[from] std::io::Error),
#[error("append condition check failed")]
AppendConditionFailed(AppendConditionFailed),
#[error("read from an unwritten position")]
ReadUnwritten(TailResponse),
#[error("{1}")]
Server(StatusCode, ApiErrorResponse),
}
impl ApiError {
pub fn is_retryable(&self) -> bool {
match self {
Self::Server(status, err_resp) => {
matches!(
*status,
StatusCode::REQUEST_TIMEOUT
| StatusCode::TOO_MANY_REQUESTS
| StatusCode::INTERNAL_SERVER_ERROR
| StatusCode::BAD_GATEWAY
| StatusCode::SERVICE_UNAVAILABLE
| StatusCode::GATEWAY_TIMEOUT
) || (*status == StatusCode::CONFLICT && err_resp.code == "transaction_conflict")
}
Self::Client(err) => err.is_retryable(),
_ => false,
}
}
pub fn has_no_side_effects(&self) -> bool {
match self {
Self::Server(status, err_resp) => matches!(
(*status, err_resp.code.as_str()),
(StatusCode::TOO_MANY_REQUESTS, "rate_limited")
| (StatusCode::BAD_GATEWAY, "hot_server")
),
Self::Client(err) => err.has_no_side_effects(),
_ => false,
}
}
}
impl From<client::Error> for ApiError {
fn from(err: client::Error) -> Self {
ClientError::from(err).into()
}
}
#[derive(Debug, thiserror::Error)]
pub enum ClientError {
#[error("connect: {0}")]
Connect(String),
#[error("timeout")]
Timeout,
#[error("connection closed early: {0}")]
ConnectionClosedEarly(String),
#[error("request canceled: {0}")]
RequestCanceled(String),
#[error("unexpected eof: {0}")]
UnexpectedEof(String),
#[error("connection reset: {0}")]
ConnectionReset(String),
#[error("connection aborted: {0}")]
ConnectionAborted(String),
#[error("connection refused: {0}")]
ConnectionRefused(String),
#[error("{0}")]
Others(String),
}
impl ClientError {
pub fn is_retryable(&self) -> bool {
!matches!(self, ClientError::Others(_))
}
pub fn has_no_side_effects(&self) -> bool {
match self {
ClientError::Connect(_)
| ClientError::Timeout
| ClientError::ConnectionClosedEarly(_)
| ClientError::RequestCanceled(_)
| ClientError::UnexpectedEof(_)
| ClientError::ConnectionReset(_)
| ClientError::ConnectionAborted(_)
| ClientError::Others(_) => false,
ClientError::ConnectionRefused(_) => true,
}
}
}
impl From<client::Error> for ClientError {
fn from(err: client::Error) -> Self {
let err_msg = err.to_string();
match err {
client::Error::Send(ref send_err) if send_err.is_connect() => {
classify_io_source(&err, &err_msg)
.or_else(|| classify_dns_source(&err, &err_msg))
.unwrap_or(Self::Connect(err_msg))
}
client::Error::Send(_) | client::Error::Receive(_) => {
classify_hyper_source(&err, &err_msg)
.or_else(|| classify_io_source(&err, &err_msg))
.unwrap_or(Self::Others(err_msg))
}
client::Error::Timeout => Self::Timeout,
_ => Self::Others(err_msg),
}
}
}
fn classify_hyper_source(err: &client::Error, err_msg: &str) -> Option<ClientError> {
let hyper_err = source_err::<hyper::Error>(err)?;
let err_msg = format!("{hyper_err} -> {err_msg}");
if hyper_err.is_incomplete_message() {
Some(ClientError::ConnectionClosedEarly(err_msg))
} else if hyper_err.is_canceled() {
Some(ClientError::RequestCanceled(err_msg))
} else {
None
}
}
fn classify_io_source(err: &client::Error, err_msg: &str) -> Option<ClientError> {
let io_err = source_err::<std::io::Error>(err)?;
let err_msg = format!("{io_err} -> {err_msg}");
Some(match io_err.kind() {
std::io::ErrorKind::UnexpectedEof => ClientError::UnexpectedEof(err_msg),
std::io::ErrorKind::ConnectionReset => ClientError::ConnectionReset(err_msg),
std::io::ErrorKind::ConnectionAborted => ClientError::ConnectionAborted(err_msg),
std::io::ErrorKind::ConnectionRefused => ClientError::ConnectionRefused(err_msg),
_ => return None,
})
}
/// Walk the error source chain looking for a "dns error" tag.
///
/// hyper-util's `ConnectError` (not publicly exported, so we can't downcast)
/// tags DNS failures with the static string "dns error" via `ConnectError::dns()`.
/// This is not a platform-specific message — it's a structural tag from the
/// Rust library. If the HTTP client changes, this will harmlessly stop matching
/// and DNS errors will fall through to the generic `Connect` variant.
fn classify_dns_source(err: &client::Error, _err_msg: &str) -> Option<ClientError> {
let mut source = Some(err as &dyn std::error::Error);
while let Some(err) = source {
if err.to_string() == "dns error" {
// Build the message from the DNS error's source (the actual
// resolver error) rather than the top-level hyper wrapper.
let detail = match err.source() {
Some(cause) => format!("dns resolution: {cause}"),
None => "dns resolution failed".to_owned(),
};
return Some(ClientError::Connect(detail));
}
source = err.source();
}
None
}
fn source_err<T: std::error::Error + 'static>(err: &dyn std::error::Error) -> Option<&T> {
let mut source = err.source();
while let Some(err) = source {
if let Some(err) = err.downcast_ref::<T>() {
return Some(err);
}
source = err.source();
}
None
}
#[derive(Debug, thiserror::Error)]
pub enum S2STerminalDecodeError {
#[error("invalid status code: {0}")]
InvalidStatusCode(#[from] http::status::InvalidStatusCode),
#[error("failed to parse error response: {0}")]
JsonDecode(#[from] serde_json::Error),
}
impl From<TerminalMessage> for ApiError {
fn from(msg: TerminalMessage) -> Self {
let status = match StatusCode::from_u16(msg.status) {
Ok(status) => status,
Err(err) => return ApiError::S2STerminalDecode(err.into()),
};
if status == StatusCode::PRECONDITION_FAILED {
let condition_failed = match serde_json::from_str::<AppendConditionFailed>(&msg.body) {
Ok(condition_failed) => condition_failed,
Err(err) => {
return ApiError::S2STerminalDecode(err.into());
}
};
ApiError::AppendConditionFailed(condition_failed)
} else if status == StatusCode::RANGE_NOT_SATISFIABLE {
let tail = match serde_json::from_str::<TailResponse>(&msg.body) {
Ok(tail) => tail,
Err(err) => {
return ApiError::S2STerminalDecode(err.into());
}
};
ApiError::ReadUnwritten(tail)
} else {
let response = match serde_json::from_str::<ApiErrorResponse>(&msg.body) {
Ok(response) => response,
Err(err) => {
return ApiError::S2STerminalDecode(err.into());
}
};
ApiError::Server(status, response)
}
}
}
pub type Streaming<R> = Pin<Box<dyn Send + Stream<Item = Result<R, ApiError>>>>;
#[derive(Clone)]
pub struct BaseClient {
client: Arc<dyn client::RequestExecutor>,
default_headers: HeaderMap,
request_timeout: Duration,
retry_builder: RetryBackoffBuilder,
compression: Compression,
}
impl std::fmt::Debug for BaseClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BaseClient").finish_non_exhaustive()
}
}
impl BaseClient {
pub fn init(config: &S2Config) -> Result<Self, ApiError> {
let connector = client::default_connector(
Some(config.connection_timeout),
config.insecure_skip_cert_verification,
)
.map_err(|e| ClientError::Others(format!("failed to load TLS certificates: {e}")))?;
Self::init_with_connector(config, connector)
}
pub fn init_with_connector<C>(config: &S2Config, connector: C) -> Result<Self, ApiError>
where
C: client::Connect + Clone + Send + Sync + 'static,
{
let mut default_headers = HeaderMap::new();
default_headers.insert(
AUTHORIZATION,
format!("Bearer {}", config.access_token.expose_secret()).try_into()?,
);
default_headers.insert(http::header::USER_AGENT, config.user_agent.clone());
match config.compression {
Compression::Gzip => {
default_headers.insert(
http::header::ACCEPT_ENCODING,
HeaderValue::from_static("gzip"),
);
}
Compression::Zstd => {
default_headers.insert(
http::header::ACCEPT_ENCODING,
HeaderValue::from_static("zstd"),
);
}
Compression::None => {}
}
let client = client::Pool::new(connector);
Ok(Self {
client: Arc::new(client),
default_headers,
request_timeout: config.request_timeout,
retry_builder: retry_builder(&config.retry),
compression: config.compression,
})
}
pub fn get(&self, url: Url) -> client::RequestBuilder {
client::RequestBuilder::get(url)
.timeout(self.request_timeout)
.headers(&self.default_headers)
}
pub fn post(&self, url: Url) -> client::RequestBuilder {
client::RequestBuilder::post(url)
.timeout(self.request_timeout)
.headers(&self.default_headers)
.compression(self.compression)
}
pub fn patch(&self, url: Url) -> client::RequestBuilder {
client::RequestBuilder::patch(url)
.timeout(self.request_timeout)
.headers(&self.default_headers)
.compression(self.compression)
}
#[cfg(feature = "_hidden")]
pub fn put(&self, url: Url) -> client::RequestBuilder {
client::RequestBuilder::put(url)
.timeout(self.request_timeout)
.headers(&self.default_headers)
.compression(self.compression)
}
pub fn delete(&self, url: Url) -> client::RequestBuilder {
client::RequestBuilder::delete(url)
.timeout(self.request_timeout)
.headers(&self.default_headers)
}
pub async fn init_streaming(
&self,
request: client::Request,
) -> Result<StreamingResponse, client::Error> {
self.client.init_streaming(request).await
}
async fn execute_unary(
&self,
request: client::Request,
) -> Result<UnaryResponse, client::Error> {
self.client.execute_unary(request).await
}
fn request(&self, request: client::Request) -> RequestBuilder<'_> {
RequestBuilder {
client: self,
request,
retry_enabled: true,
append_retry_policy: None,
frame_signal: None,
error_handler: None,
}
}
}
pub fn retry_builder(config: &RetryConfig) -> RetryBackoffBuilder {
RetryBackoffBuilder::default()
.with_min_base_delay(config.min_base_delay)
.with_max_base_delay(config.max_base_delay)
.with_max_retries(config.max_retries())
}
type ErrorHandlerFn =
Box<dyn Fn(StatusCode, UnaryResponse) -> Result<UnaryResponse, ApiError> + Send + Sync>;
struct RequestBuilder<'a> {
client: &'a BaseClient,
request: client::Request,
retry_enabled: bool,
append_retry_policy: Option<AppendRetryPolicy>,
frame_signal: Option<FrameSignal>,
error_handler: Option<ErrorHandlerFn>,
}
impl<'a> RequestBuilder<'a> {
fn with_append_retry_policy(self, policy: AppendRetryPolicy) -> Self {
let frame_signal = match policy {
AppendRetryPolicy::NoSideEffects => Some(FrameSignal::new()),
AppendRetryPolicy::All => None,
};
Self {
append_retry_policy: Some(policy),
frame_signal,
..self
}
}
fn error_handler<F>(self, handler: F) -> Self
where
F: Fn(StatusCode, UnaryResponse) -> Result<UnaryResponse, ApiError> + Send + Sync + 'static,
{
Self {
error_handler: Some(Box::new(handler)),
..self
}
}
async fn send(self) -> Result<UnaryResponse, ApiError> {
let request = self.request;
let mut retry_backoff: Option<RetryBackoff> = self
.retry_enabled
.then(|| self.client.retry_builder.build());
loop {
if let Some(ref signal) = self.frame_signal {
signal.reset();
}
let attempt_request = {
let mut r = request.try_clone().expect("body should not be a stream");
if let Some(ref signal) = self.frame_signal {
r = r.compress().await.map_err(ApiError::from)?;
r = r.with_monitored_body(signal.clone());
}
r
};
let response = self
.client
.execute_unary(attempt_request)
.await;
let (err, retry_after) = match response {
Ok(resp) => {
let retry_after: Option<Duration> = resp
.headers()
.get(RETRY_AFTER_MS_HEADER)
.and_then(|v| match v.to_str() {
Ok(s) => Some(s),
Err(e) => {
warn!(
?e,
"failed to parse {RETRY_AFTER_MS_HEADER} header as string"
);
None
}
})
.and_then(|v| match v.parse::<u64>() {
Ok(ms) => Some(ms),
Err(e) => {
warn!(?e, "failed to parse {RETRY_AFTER_MS_HEADER} header as u64");
None
}
})
.map(Duration::from_millis);
let result = if let Some(ref handler) = self.error_handler {
resp.into_result_with_handler(handler)
} else {
resp.into_result()
};