This repository was archived by the owner on Feb 16, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtypes.rs
More file actions
3462 lines (3137 loc) · 105 KB
/
Copy pathtypes.rs
File metadata and controls
3462 lines (3137 loc) · 105 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
//! Types relevant to [`S2`](crate::S2), [`S2Basin`](crate::S2Basin), and
//! [`S2Stream`](crate::S2Stream).
use std::{
collections::HashSet,
env::VarError,
fmt,
num::NonZeroU32,
ops::{Deref, RangeTo},
pin::Pin,
str::FromStr,
time::Duration,
};
use bytes::Bytes;
use http::{
header::HeaderValue,
uri::{Authority, Scheme},
};
use rand::RngExt;
use s2_api::{v1 as api, v1::stream::s2s::CompressionAlgorithm};
pub use s2_common::caps::RECORD_BATCH_MAX;
/// Validation error.
pub use s2_common::types::ValidationError;
/// Access token ID.
///
/// **Note:** It must be unique to the account and between 1 and 96 bytes in length.
pub use s2_common::types::access::AccessTokenId;
/// See [`ListAccessTokensInput::prefix`].
pub use s2_common::types::access::AccessTokenIdPrefix;
/// See [`ListAccessTokensInput::start_after`].
pub use s2_common::types::access::AccessTokenIdStartAfter;
/// Basin name.
///
/// **Note:** It must be globally unique and between 8 and 48 bytes in length. It can only
/// comprise lowercase letters, numbers, and hyphens. It cannot begin or end with a hyphen.
pub use s2_common::types::basin::BasinName;
/// See [`ListBasinsInput::prefix`].
pub use s2_common::types::basin::BasinNamePrefix;
/// See [`ListBasinsInput::start_after`].
pub use s2_common::types::basin::BasinNameStartAfter;
/// Stream name.
///
/// **Note:** It must be unique to the basin and between 1 and 512 bytes in length.
pub use s2_common::types::stream::StreamName;
/// See [`ListStreamsInput::prefix`].
pub use s2_common::types::stream::StreamNamePrefix;
/// See [`ListStreamsInput::start_after`].
pub use s2_common::types::stream::StreamNameStartAfter;
pub(crate) const ONE_MIB: u32 = 1024 * 1024;
use s2_common::{maybe::Maybe, record::MAX_FENCING_TOKEN_LENGTH};
use secrecy::SecretString;
use crate::api::{ApiError, ApiErrorResponse};
/// An RFC 3339 datetime.
///
/// It can be created in either of the following ways:
/// - Parse an RFC 3339 datetime string using [`FromStr`] or [`str::parse`].
/// - Convert from [`time::OffsetDateTime`] using [`From`]/[`Into`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct S2DateTime(time::OffsetDateTime);
impl From<time::OffsetDateTime> for S2DateTime {
fn from(dt: time::OffsetDateTime) -> Self {
Self(dt)
}
}
impl From<S2DateTime> for time::OffsetDateTime {
fn from(dt: S2DateTime) -> Self {
dt.0
}
}
impl FromStr for S2DateTime {
type Err = ValidationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
time::OffsetDateTime::parse(s, &time::format_description::well_known::Rfc3339)
.map(Self)
.map_err(|e| ValidationError(format!("invalid datetime: {e}")))
}
}
impl fmt::Display for S2DateTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
self.0
.format(&time::format_description::well_known::Rfc3339)
.expect("RFC3339 formatting should not fail for S2DateTime")
)
}
}
/// Authority for connecting to an S2 basin.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum BasinAuthority {
/// Parent zone for basins. DNS is used to route to the correct cell for the basin.
ParentZone(Authority),
/// Direct cell authority. Basin is expected to be hosted by this cell.
Direct(Authority),
}
/// Account endpoint.
#[derive(Debug, Clone)]
pub struct AccountEndpoint {
scheme: Scheme,
authority: Authority,
}
impl AccountEndpoint {
/// Create a new [`AccountEndpoint`] with the given endpoint.
pub fn new(endpoint: &str) -> Result<Self, ValidationError> {
endpoint.parse()
}
}
impl FromStr for AccountEndpoint {
type Err = ValidationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (scheme, authority) = match s.find("://") {
Some(idx) => {
let scheme: Scheme = s[..idx]
.parse()
.map_err(|_| "invalid account endpoint scheme".to_string())?;
(scheme, &s[idx + 3..])
}
None => (Scheme::HTTPS, s),
};
Ok(Self {
scheme,
authority: authority
.parse()
.map_err(|e| format!("invalid account endpoint authority: {e}"))?,
})
}
}
/// Basin endpoint.
#[derive(Debug, Clone)]
pub struct BasinEndpoint {
scheme: Scheme,
authority: BasinAuthority,
}
impl BasinEndpoint {
/// Create a new [`BasinEndpoint`] with the given endpoint.
pub fn new(endpoint: &str) -> Result<Self, ValidationError> {
endpoint.parse()
}
}
impl FromStr for BasinEndpoint {
type Err = ValidationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (scheme, authority) = match s.find("://") {
Some(idx) => {
let scheme: Scheme = s[..idx]
.parse()
.map_err(|_| "invalid basin endpoint scheme".to_string())?;
(scheme, &s[idx + 3..])
}
None => (Scheme::HTTPS, s),
};
let authority = if let Some(authority) = authority.strip_prefix("{basin}.") {
BasinAuthority::ParentZone(
authority
.parse()
.map_err(|e| format!("invalid basin endpoint authority: {e}"))?,
)
} else {
BasinAuthority::Direct(
authority
.parse()
.map_err(|e| format!("invalid basin endpoint authority: {e}"))?,
)
};
Ok(Self { scheme, authority })
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
/// Endpoints for the S2 environment.
pub struct S2Endpoints {
pub(crate) scheme: Scheme,
pub(crate) account_authority: Authority,
pub(crate) basin_authority: BasinAuthority,
}
impl S2Endpoints {
/// Create a new [`S2Endpoints`] with the given account and basin endpoints.
pub fn new(
account_endpoint: AccountEndpoint,
basin_endpoint: BasinEndpoint,
) -> Result<Self, ValidationError> {
if account_endpoint.scheme != basin_endpoint.scheme {
return Err("account and basin endpoints must have the same scheme".into());
}
Ok(Self {
scheme: account_endpoint.scheme,
account_authority: account_endpoint.authority,
basin_authority: basin_endpoint.authority,
})
}
/// Create a new [`S2Endpoints`] from environment variables.
///
/// The following environment variables are expected to be set:
/// - `S2_ACCOUNT_ENDPOINT` - Account-level endpoint.
/// - `S2_BASIN_ENDPOINT` - Basin-level endpoint.
pub fn from_env() -> Result<Self, ValidationError> {
let account_endpoint: AccountEndpoint = match std::env::var("S2_ACCOUNT_ENDPOINT") {
Ok(endpoint) => endpoint.parse()?,
Err(VarError::NotPresent) => return Err("S2_ACCOUNT_ENDPOINT env var not set".into()),
Err(VarError::NotUnicode(_)) => {
return Err("S2_ACCOUNT_ENDPOINT is not valid unicode".into());
}
};
let basin_endpoint: BasinEndpoint = match std::env::var("S2_BASIN_ENDPOINT") {
Ok(endpoint) => endpoint.parse()?,
Err(VarError::NotPresent) => return Err("S2_BASIN_ENDPOINT env var not set".into()),
Err(VarError::NotUnicode(_)) => {
return Err("S2_BASIN_ENDPOINT is not valid unicode".into());
}
};
if account_endpoint.scheme != basin_endpoint.scheme {
return Err(
"S2_ACCOUNT_ENDPOINT and S2_BASIN_ENDPOINT must have the same scheme".into(),
);
}
Ok(Self {
scheme: account_endpoint.scheme,
account_authority: account_endpoint.authority,
basin_authority: basin_endpoint.authority,
})
}
pub(crate) fn for_aws() -> Self {
Self {
scheme: Scheme::HTTPS,
account_authority: "aws.s2.dev".try_into().expect("valid authority"),
basin_authority: BasinAuthority::ParentZone(
"b.aws.s2.dev".try_into().expect("valid authority"),
),
}
}
}
#[derive(Debug, Clone, Copy)]
/// Compression algorithm for request and response bodies.
pub enum Compression {
/// No compression.
None,
/// Gzip compression.
Gzip,
/// Zstd compression.
Zstd,
}
impl From<Compression> for CompressionAlgorithm {
fn from(value: Compression) -> Self {
match value {
Compression::None => CompressionAlgorithm::None,
Compression::Gzip => CompressionAlgorithm::Gzip,
Compression::Zstd => CompressionAlgorithm::Zstd,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
/// Retry policy for [`append`](crate::S2Stream::append) and
/// [`append_session`](crate::S2Stream::append_session) operations.
pub enum AppendRetryPolicy {
/// Retry all appends. Use when duplicate records on the stream are acceptable.
All,
/// Only retry appends that include [`match_seq_num`](AppendInput::match_seq_num).
NoSideEffects,
}
impl AppendRetryPolicy {
pub(crate) fn is_compliant(&self, input: &AppendInput) -> bool {
match self {
Self::All => true,
Self::NoSideEffects => input.match_seq_num.is_some(),
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
/// Configuration for retrying requests in case of transient failures.
///
/// Exponential backoff with jitter is the retry strategy. Below is the pseudocode for the strategy:
/// ```text
/// base_delay = min(min_base_delay · 2ⁿ, max_base_delay) (n = retry attempt, starting from 0)
/// jitter = rand[0, base_delay]
/// delay = base_delay + jitter
/// ````
pub struct RetryConfig {
/// Total number of attempts including the initial try. A value of `1` means no retries.
///
/// Defaults to `3`.
pub max_attempts: NonZeroU32,
/// Minimum base delay for retries.
///
/// Defaults to `100ms`.
pub min_base_delay: Duration,
/// Maximum base delay for retries.
///
/// Defaults to `1s`.
pub max_base_delay: Duration,
/// Retry policy for [`append`](crate::S2Stream::append) and
/// [`append_session`](crate::S2Stream::append_session) operations.
///
/// Defaults to `All`.
pub append_retry_policy: AppendRetryPolicy,
}
impl Default for RetryConfig {
fn default() -> Self {
Self {
max_attempts: NonZeroU32::new(3).expect("valid non-zero u32"),
min_base_delay: Duration::from_millis(100),
max_base_delay: Duration::from_secs(1),
append_retry_policy: AppendRetryPolicy::All,
}
}
}
impl RetryConfig {
/// Create a new [`RetryConfig`] with default settings.
pub fn new() -> Self {
Self::default()
}
pub(crate) fn max_retries(&self) -> u32 {
self.max_attempts.get() - 1
}
/// Set the total number of attempts including the initial try.
pub fn with_max_attempts(self, max_attempts: NonZeroU32) -> Self {
Self {
max_attempts,
..self
}
}
/// Set the minimum base delay for retries.
pub fn with_min_base_delay(self, min_base_delay: Duration) -> Self {
Self {
min_base_delay,
..self
}
}
/// Set the maximum base delay for retries.
pub fn with_max_base_delay(self, max_base_delay: Duration) -> Self {
Self {
max_base_delay,
..self
}
}
/// Set the retry policy for [`append`](crate::S2Stream::append) and
/// [`append_session`](crate::S2Stream::append_session) operations.
pub fn with_append_retry_policy(self, append_retry_policy: AppendRetryPolicy) -> Self {
Self {
append_retry_policy,
..self
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
/// Configuration for [`S2`](crate::S2).
pub struct S2Config {
pub(crate) access_token: SecretString,
pub(crate) endpoints: S2Endpoints,
pub(crate) connection_timeout: Duration,
pub(crate) request_timeout: Duration,
pub(crate) retry: RetryConfig,
pub(crate) compression: Compression,
pub(crate) user_agent: HeaderValue,
pub(crate) insecure_skip_cert_verification: bool,
}
impl S2Config {
/// Create a new [`S2Config`] with the given access token and default settings.
pub fn new(access_token: impl Into<String>) -> Self {
Self {
access_token: access_token.into().into(),
endpoints: S2Endpoints::for_aws(),
connection_timeout: Duration::from_secs(3),
request_timeout: Duration::from_secs(5),
retry: RetryConfig::new(),
compression: Compression::None,
user_agent: concat!("s2-sdk-rust/", env!("CARGO_PKG_VERSION"))
.parse()
.expect("valid user agent"),
insecure_skip_cert_verification: false,
}
}
/// Set the S2 endpoints to connect to.
pub fn with_endpoints(self, endpoints: S2Endpoints) -> Self {
Self { endpoints, ..self }
}
/// Set the timeout for establishing a connection to the server.
///
/// Defaults to `3s`.
pub fn with_connection_timeout(self, connection_timeout: Duration) -> Self {
Self {
connection_timeout,
..self
}
}
/// Set the timeout for requests.
///
/// Defaults to `5s`.
pub fn with_request_timeout(self, request_timeout: Duration) -> Self {
Self {
request_timeout,
..self
}
}
/// Set the retry configuration for requests.
///
/// See [`RetryConfig`] for defaults.
pub fn with_retry(self, retry: RetryConfig) -> Self {
Self { retry, ..self }
}
/// Set the compression algorithm for requests and responses.
///
/// Defaults to no compression.
pub fn with_compression(self, compression: Compression) -> Self {
Self {
compression,
..self
}
}
/// Skip TLS certificate verification (insecure).
///
/// This is useful for connecting to endpoints with self-signed certificates
/// or certificates that don't match the hostname (similar to `curl -k`).
///
/// # Warning
///
/// This disables certificate verification and should only be used for
/// testing or development purposes. **Never use this in production.**
///
/// Defaults to `false`.
pub fn with_insecure_skip_cert_verification(self, skip: bool) -> Self {
Self {
insecure_skip_cert_verification: skip,
..self
}
}
#[doc(hidden)]
#[cfg(feature = "_hidden")]
pub fn with_user_agent(self, user_agent: impl Into<String>) -> Result<Self, ValidationError> {
let user_agent = user_agent
.into()
.parse()
.map_err(|e| ValidationError(format!("invalid user agent: {e}")))?;
Ok(Self { user_agent, ..self })
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// A page of values.
pub struct Page<T> {
/// Values in this page.
pub values: Vec<T>,
/// Whether there are more pages.
pub has_more: bool,
}
impl<T> Page<T> {
pub(crate) fn new(values: impl Into<Vec<T>>, has_more: bool) -> Self {
Self {
values: values.into(),
has_more,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Storage class for recent appends.
pub enum StorageClass {
/// Standard storage class that offers append latencies under `500ms`.
Standard,
/// Express storage class that offers append latencies under `50ms`.
Express,
}
impl From<api::config::StorageClass> for StorageClass {
fn from(value: api::config::StorageClass) -> Self {
match value {
api::config::StorageClass::Standard => StorageClass::Standard,
api::config::StorageClass::Express => StorageClass::Express,
}
}
}
impl From<StorageClass> for api::config::StorageClass {
fn from(value: StorageClass) -> Self {
match value {
StorageClass::Standard => api::config::StorageClass::Standard,
StorageClass::Express => api::config::StorageClass::Express,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Retention policy for records in a stream.
pub enum RetentionPolicy {
/// Age in seconds. Records older than this age are automatically trimmed.
Age(u64),
/// Records are retained indefinitely unless explicitly trimmed.
Infinite,
}
impl From<api::config::RetentionPolicy> for RetentionPolicy {
fn from(value: api::config::RetentionPolicy) -> Self {
match value {
api::config::RetentionPolicy::Age(secs) => RetentionPolicy::Age(secs),
api::config::RetentionPolicy::Infinite(_) => RetentionPolicy::Infinite,
}
}
}
impl From<RetentionPolicy> for api::config::RetentionPolicy {
fn from(value: RetentionPolicy) -> Self {
match value {
RetentionPolicy::Age(secs) => api::config::RetentionPolicy::Age(secs),
RetentionPolicy::Infinite => {
api::config::RetentionPolicy::Infinite(api::config::InfiniteRetention {})
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Timestamping mode for appends that influences how timestamps are handled.
pub enum TimestampingMode {
/// Prefer client-specified timestamp if present otherwise use arrival time.
ClientPrefer,
/// Require a client-specified timestamp and reject the append if it is missing.
ClientRequire,
/// Use the arrival time and ignore any client-specified timestamp.
Arrival,
}
impl From<api::config::TimestampingMode> for TimestampingMode {
fn from(value: api::config::TimestampingMode) -> Self {
match value {
api::config::TimestampingMode::ClientPrefer => TimestampingMode::ClientPrefer,
api::config::TimestampingMode::ClientRequire => TimestampingMode::ClientRequire,
api::config::TimestampingMode::Arrival => TimestampingMode::Arrival,
}
}
}
impl From<TimestampingMode> for api::config::TimestampingMode {
fn from(value: TimestampingMode) -> Self {
match value {
TimestampingMode::ClientPrefer => api::config::TimestampingMode::ClientPrefer,
TimestampingMode::ClientRequire => api::config::TimestampingMode::ClientRequire,
TimestampingMode::Arrival => api::config::TimestampingMode::Arrival,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
/// Configuration for timestamping behavior.
pub struct TimestampingConfig {
/// Timestamping mode for appends that influences how timestamps are handled.
///
/// Defaults to [`ClientPrefer`](TimestampingMode::ClientPrefer).
pub mode: Option<TimestampingMode>,
/// Whether client-specified timestamps are allowed to exceed the arrival time.
///
/// Defaults to `false` (client timestamps are capped at the arrival time).
pub uncapped: bool,
}
impl TimestampingConfig {
/// Create a new [`TimestampingConfig`] with default settings.
pub fn new() -> Self {
Self::default()
}
/// Set the timestamping mode for appends that influences how timestamps are handled.
pub fn with_mode(self, mode: TimestampingMode) -> Self {
Self {
mode: Some(mode),
..self
}
}
/// Set whether client-specified timestamps are allowed to exceed the arrival time.
pub fn with_uncapped(self, uncapped: bool) -> Self {
Self { uncapped, ..self }
}
}
impl From<api::config::TimestampingConfig> for TimestampingConfig {
fn from(value: api::config::TimestampingConfig) -> Self {
Self {
mode: value.mode.map(Into::into),
uncapped: value.uncapped.unwrap_or_default(),
}
}
}
impl From<TimestampingConfig> for api::config::TimestampingConfig {
fn from(value: TimestampingConfig) -> Self {
Self {
mode: value.mode.map(Into::into),
uncapped: Some(value.uncapped),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
/// Configuration for automatically deleting a stream when it becomes empty.
pub struct DeleteOnEmptyConfig {
/// Minimum age in seconds before an empty stream can be deleted.
///
/// Defaults to `0` (disables automatic deletion).
pub min_age_secs: u64,
}
impl DeleteOnEmptyConfig {
/// Create a new [`DeleteOnEmptyConfig`] with default settings.
pub fn new() -> Self {
Self::default()
}
/// Set the minimum age in seconds before an empty stream can be deleted.
pub fn with_min_age(self, min_age: Duration) -> Self {
Self {
min_age_secs: min_age.as_secs(),
}
}
}
impl From<api::config::DeleteOnEmptyConfig> for DeleteOnEmptyConfig {
fn from(value: api::config::DeleteOnEmptyConfig) -> Self {
Self {
min_age_secs: value.min_age_secs,
}
}
}
impl From<DeleteOnEmptyConfig> for api::config::DeleteOnEmptyConfig {
fn from(value: DeleteOnEmptyConfig) -> Self {
Self {
min_age_secs: value.min_age_secs,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
/// Configuration for a stream.
pub struct StreamConfig {
/// Storage class for the stream.
///
/// Defaults to [`Express`](StorageClass::Express).
pub storage_class: Option<StorageClass>,
/// Retention policy for records in the stream.
///
/// Defaults to `7 days` of retention.
pub retention_policy: Option<RetentionPolicy>,
/// Configuration for timestamping behavior.
///
/// See [`TimestampingConfig`] for defaults.
pub timestamping: Option<TimestampingConfig>,
/// Configuration for automatically deleting the stream when it becomes empty.
///
/// See [`DeleteOnEmptyConfig`] for defaults.
pub delete_on_empty: Option<DeleteOnEmptyConfig>,
}
impl StreamConfig {
/// Create a new [`StreamConfig`] with default settings.
pub fn new() -> Self {
Self::default()
}
/// Set the storage class for the stream.
pub fn with_storage_class(self, storage_class: StorageClass) -> Self {
Self {
storage_class: Some(storage_class),
..self
}
}
/// Set the retention policy for records in the stream.
pub fn with_retention_policy(self, retention_policy: RetentionPolicy) -> Self {
Self {
retention_policy: Some(retention_policy),
..self
}
}
/// Set the configuration for timestamping behavior.
pub fn with_timestamping(self, timestamping: TimestampingConfig) -> Self {
Self {
timestamping: Some(timestamping),
..self
}
}
/// Set the configuration for automatically deleting the stream when it becomes empty.
pub fn with_delete_on_empty(self, delete_on_empty: DeleteOnEmptyConfig) -> Self {
Self {
delete_on_empty: Some(delete_on_empty),
..self
}
}
}
impl From<api::config::StreamConfig> for StreamConfig {
fn from(value: api::config::StreamConfig) -> Self {
Self {
storage_class: value.storage_class.map(Into::into),
retention_policy: value.retention_policy.map(Into::into),
timestamping: value.timestamping.map(Into::into),
delete_on_empty: value.delete_on_empty.map(Into::into),
}
}
}
impl From<StreamConfig> for api::config::StreamConfig {
fn from(value: StreamConfig) -> Self {
Self {
storage_class: value.storage_class.map(Into::into),
retention_policy: value.retention_policy.map(Into::into),
timestamping: value.timestamping.map(Into::into),
delete_on_empty: value.delete_on_empty.map(Into::into),
}
}
}
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
/// Configuration for a basin.
pub struct BasinConfig {
/// Default configuration for all streams in the basin.
///
/// See [`StreamConfig`] for defaults.
pub default_stream_config: Option<StreamConfig>,
/// Whether to create stream on append if it doesn't exist using default stream configuration.
///
/// Defaults to `false`.
pub create_stream_on_append: bool,
/// Whether to create stream on read if it doesn't exist using default stream configuration.
///
/// Defaults to `false`.
pub create_stream_on_read: bool,
}
impl BasinConfig {
/// Create a new [`BasinConfig`] with default settings.
pub fn new() -> Self {
Self::default()
}
/// Set the default configuration for all streams in the basin.
pub fn with_default_stream_config(self, config: StreamConfig) -> Self {
Self {
default_stream_config: Some(config),
..self
}
}
/// Set whether to create stream on append if it doesn't exist using default stream
/// configuration.
pub fn with_create_stream_on_append(self, create_stream_on_append: bool) -> Self {
Self {
create_stream_on_append,
..self
}
}
/// Set whether to create stream on read if it doesn't exist using default stream configuration.
pub fn with_create_stream_on_read(self, create_stream_on_read: bool) -> Self {
Self {
create_stream_on_read,
..self
}
}
}
impl From<api::config::BasinConfig> for BasinConfig {
fn from(value: api::config::BasinConfig) -> Self {
Self {
default_stream_config: value.default_stream_config.map(Into::into),
create_stream_on_append: value.create_stream_on_append,
create_stream_on_read: value.create_stream_on_read,
}
}
}
impl From<BasinConfig> for api::config::BasinConfig {
fn from(value: BasinConfig) -> Self {
Self {
default_stream_config: value.default_stream_config.map(Into::into),
create_stream_on_append: value.create_stream_on_append,
create_stream_on_read: value.create_stream_on_read,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// Scope of a basin.
pub enum BasinScope {
/// AWS `us-east-1` region.
AwsUsEast1,
}
impl From<api::basin::BasinScope> for BasinScope {
fn from(value: api::basin::BasinScope) -> Self {
match value {
api::basin::BasinScope::AwsUsEast1 => BasinScope::AwsUsEast1,
}
}
}
impl From<BasinScope> for api::basin::BasinScope {
fn from(value: BasinScope) -> Self {
match value {
BasinScope::AwsUsEast1 => api::basin::BasinScope::AwsUsEast1,
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
/// Input for [`create_basin`](crate::S2::create_basin) operation.
pub struct CreateBasinInput {
/// Basin name.
pub name: BasinName,
/// Configuration for the basin.
///
/// See [`BasinConfig`] for defaults.
pub config: Option<BasinConfig>,
/// Scope of the basin.
///
/// Defaults to [`AwsUsEast1`](BasinScope::AwsUsEast1).
pub scope: Option<BasinScope>,
idempotency_token: String,
}
impl CreateBasinInput {
/// Create a new [`CreateBasinInput`] with the given basin name.
pub fn new(name: BasinName) -> Self {
Self {
name,
config: None,
scope: None,
idempotency_token: idempotency_token(),
}
}
/// Set the configuration for the basin.
pub fn with_config(self, config: BasinConfig) -> Self {
Self {
config: Some(config),
..self
}
}
/// Set the scope of the basin.
pub fn with_scope(self, scope: BasinScope) -> Self {
Self {
scope: Some(scope),
..self
}
}
}
impl From<CreateBasinInput> for (api::basin::CreateBasinRequest, String) {
fn from(value: CreateBasinInput) -> Self {
(
api::basin::CreateBasinRequest {
basin: value.name,
config: value.config.map(Into::into),
scope: value.scope.map(Into::into),
},
value.idempotency_token,
)
}
}
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
/// Input for [`list_basins`](crate::S2::list_basins) operation.
pub struct ListBasinsInput {
/// Filter basins whose names begin with this value.
///
/// Defaults to `""`.
pub prefix: BasinNamePrefix,
/// Filter basins whose names are lexicographically greater than this value.
///
/// **Note:** It must be greater than or equal to [`prefix`](ListBasinsInput::prefix).
///
/// Defaults to `""`.
pub start_after: BasinNameStartAfter,
/// Number of basins to return in a page. Will be clamped to a maximum of `1000`.
///
/// Defaults to `1000`.
pub limit: Option<usize>,
}
impl ListBasinsInput {
/// Create a new [`ListBasinsInput`] with default values.
pub fn new() -> Self {
Self::default()
}
/// Set the prefix used to filter basins whose names begin with this value.
pub fn with_prefix(self, prefix: BasinNamePrefix) -> Self {
Self { prefix, ..self }
}
/// Set the value used to filter basins whose names are lexicographically greater than this
/// value.
pub fn with_start_after(self, start_after: BasinNameStartAfter) -> Self {
Self {
start_after,
..self
}
}
/// Set the limit on number of basins to return in a page.
pub fn with_limit(self, limit: usize) -> Self {
Self {
limit: Some(limit),
..self
}
}
}
impl From<ListBasinsInput> for api::basin::ListBasinsRequest {
fn from(value: ListBasinsInput) -> Self {
Self {
prefix: Some(value.prefix),
start_after: Some(value.start_after),
limit: value.limit,
}
}
}
#[derive(Debug, Clone, Default)]
/// Input for [`S2::list_all_basins`](crate::S2::list_all_basins).
pub struct ListAllBasinsInput {
/// Filter basins whose names begin with this value.
///
/// Defaults to `""`.
pub prefix: BasinNamePrefix,
/// Filter basins whose names are lexicographically greater than this value.
///
/// **Note:** It must be greater than or equal to [`prefix`](ListAllBasinsInput::prefix).
///
/// Defaults to `""`.
pub start_after: BasinNameStartAfter,
/// Whether to include basins that are being deleted.
///
/// Defaults to `false`.
pub include_deleted: bool,
}
impl ListAllBasinsInput {
/// Create a new [`ListAllBasinsInput`] with default values.
pub fn new() -> Self {
Self::default()