s2-common 0.39.1

Common stuff for client and servers for S2, the durable streams 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
use std::{marker::PhantomData, ops::Deref, str::FromStr, time::Duration};

use compact_str::{CompactString, ToCompactString};
use time::OffsetDateTime;

use super::{
    ValidationError,
    strings::{NameProps, PrefixProps, StartAfterProps, StrProps},
};
use crate::{
    caps,
    encryption::EncryptionAlgorithm,
    read_extent::{ReadLimit, ReadUntil},
    record::{
        FencingToken, Metered, MeteredSize, Record, SeqNum, Sequenced, StreamPosition, Timestamp,
    },
    resources::ListItemsRequest,
};

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct StreamNameStr<T: StrProps>(CompactString, PhantomData<T>);

impl<T: StrProps> StreamNameStr<T> {
    fn validate_str(name: &str) -> Result<(), ValidationError> {
        if !T::IS_PREFIX && name.is_empty() {
            return Err(format!("stream {} must not be empty", T::FIELD_NAME).into());
        }

        if !T::IS_PREFIX && (name == "." || name == "..") {
            return Err(format!("stream {} must not be \".\" or \"..\"", T::FIELD_NAME).into());
        }

        if name.len() > caps::MAX_STREAM_NAME_LEN {
            return Err(format!(
                "stream {} must not exceed {} bytes in length",
                T::FIELD_NAME,
                caps::MAX_STREAM_NAME_LEN
            )
            .into());
        }

        Ok(())
    }
}

#[cfg(feature = "utoipa")]
impl<T> utoipa::PartialSchema for StreamNameStr<T>
where
    T: StrProps,
{
    fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
        utoipa::openapi::Object::builder()
            .schema_type(utoipa::openapi::Type::String)
            .min_length((!T::IS_PREFIX).then_some(caps::MIN_STREAM_NAME_LEN))
            .max_length(Some(caps::MAX_STREAM_NAME_LEN))
            .into()
    }
}

#[cfg(feature = "utoipa")]
impl<T> utoipa::ToSchema for StreamNameStr<T> where T: StrProps {}

impl<T: StrProps> serde::Serialize for StreamNameStr<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.0)
    }
}

impl<'de, T: StrProps> serde::Deserialize<'de> for StreamNameStr<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = CompactString::deserialize(deserializer)?;
        s.try_into().map_err(serde::de::Error::custom)
    }
}

impl<T: StrProps> AsRef<str> for StreamNameStr<T> {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl<T: StrProps> Deref for StreamNameStr<T> {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T: StrProps> TryFrom<CompactString> for StreamNameStr<T> {
    type Error = ValidationError;

    fn try_from(name: CompactString) -> Result<Self, Self::Error> {
        Self::validate_str(&name)?;
        Ok(Self(name, PhantomData))
    }
}

impl<T: StrProps> FromStr for StreamNameStr<T> {
    type Err = ValidationError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::validate_str(s)?;
        Ok(Self(s.to_compact_string(), PhantomData))
    }
}

impl<T: StrProps> std::fmt::Debug for StreamNameStr<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl<T: StrProps> std::fmt::Display for StreamNameStr<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl<T: StrProps> From<StreamNameStr<T>> for CompactString {
    fn from(value: StreamNameStr<T>) -> Self {
        value.0
    }
}

pub type StreamName = StreamNameStr<NameProps>;

pub type StreamNamePrefix = StreamNameStr<PrefixProps>;

impl Default for StreamNamePrefix {
    fn default() -> Self {
        StreamNameStr(CompactString::default(), PhantomData)
    }
}

impl From<StreamName> for StreamNamePrefix {
    fn from(value: StreamName) -> Self {
        Self(value.0, PhantomData)
    }
}

pub type StreamNameStartAfter = StreamNameStr<StartAfterProps>;

impl Default for StreamNameStartAfter {
    fn default() -> Self {
        StreamNameStr(CompactString::default(), PhantomData)
    }
}

impl From<StreamName> for StreamNameStartAfter {
    fn from(value: StreamName) -> Self {
        Self(value.0, PhantomData)
    }
}

#[derive(Debug, Clone)]
pub struct StreamInfo {
    pub name: StreamName,
    pub created_at: OffsetDateTime,
    pub deleted_at: Option<OffsetDateTime>,
    pub cipher: Option<EncryptionAlgorithm>,
}

#[derive(Debug, Clone)]
pub struct AppendRecord<T = Record>(AppendRecordParts<T>);

impl<T> AppendRecord<T> {
    pub fn parts(&self) -> &AppendRecordParts<T> {
        let Self(parts) = self;
        parts
    }

    pub fn into_parts(self) -> AppendRecordParts<T> {
        let Self(parts) = self;
        parts
    }
}

impl<T> MeteredSize for AppendRecord<T> {
    fn metered_size(&self) -> usize {
        self.0.record.metered_size()
    }
}

#[derive(Debug, Clone)]
pub struct AppendRecordParts<T = Record> {
    pub timestamp: Option<Timestamp>,
    pub record: Metered<T>,
}

impl<T> MeteredSize for AppendRecordParts<T> {
    fn metered_size(&self) -> usize {
        self.record.metered_size()
    }
}

impl<T> From<AppendRecord<T>> for AppendRecordParts<T> {
    fn from(record: AppendRecord<T>) -> Self {
        record.into_parts()
    }
}

impl<T> TryFrom<AppendRecordParts<T>> for AppendRecord<T> {
    type Error = &'static str;

    fn try_from(parts: AppendRecordParts<T>) -> Result<Self, Self::Error> {
        if parts.metered_size() > caps::RECORD_BATCH_MAX.bytes {
            Err("record must have metered size less than 1 MiB")
        } else {
            Ok(Self(parts))
        }
    }
}

#[derive(Clone)]
pub struct AppendRecordBatch<T = Record>(Metered<Vec<AppendRecord<T>>>);

impl<T> std::fmt::Debug for AppendRecordBatch<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AppendRecordBatch")
            .field("num_records", &self.0.len())
            .field("metered_size", &self.0.metered_size())
            .finish()
    }
}

impl<T> MeteredSize for AppendRecordBatch<T> {
    fn metered_size(&self) -> usize {
        self.0.metered_size()
    }
}

impl<T> std::ops::Deref for AppendRecordBatch<T> {
    type Target = [AppendRecord<T>];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> TryFrom<Metered<Vec<AppendRecord<T>>>> for AppendRecordBatch<T> {
    type Error = &'static str;

    fn try_from(records: Metered<Vec<AppendRecord<T>>>) -> Result<Self, Self::Error> {
        if records.is_empty() {
            return Err("record batch must not be empty");
        }

        if records.len() > caps::RECORD_BATCH_MAX.count {
            return Err("record batch must not exceed 1000 records");
        }

        if records.metered_size() > caps::RECORD_BATCH_MAX.bytes {
            return Err("record batch must not exceed a metered size of 1 MiB");
        }

        Ok(Self(records))
    }
}

impl<T> TryFrom<Vec<AppendRecord<T>>> for AppendRecordBatch<T> {
    type Error = &'static str;

    fn try_from(records: Vec<AppendRecord<T>>) -> Result<Self, Self::Error> {
        let records = Metered::from(records);
        Self::try_from(records)
    }
}

impl<T> IntoIterator for AppendRecordBatch<T> {
    type Item = AppendRecord<T>;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

#[derive(Debug, Clone)]
pub struct AppendInput<T = Record> {
    pub records: AppendRecordBatch<T>,
    pub match_seq_num: Option<SeqNum>,
    pub fencing_token: Option<FencingToken>,
}

#[derive(Debug, Clone)]
pub struct AppendAck {
    pub start: StreamPosition,
    pub end: StreamPosition,
    pub tail: StreamPosition,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadPosition {
    SeqNum(SeqNum),
    Timestamp(Timestamp),
}

#[derive(Debug, Clone, Copy)]
pub enum ReadFrom {
    SeqNum(SeqNum),
    Timestamp(Timestamp),
    TailOffset(u64),
}

impl Default for ReadFrom {
    fn default() -> Self {
        Self::SeqNum(0)
    }
}

#[derive(Debug, Default, Clone, Copy)]
pub struct ReadStart {
    pub from: ReadFrom,
    pub clamp: bool,
}

#[derive(Debug, Default, Clone, Copy)]
pub struct ReadEnd {
    pub limit: ReadLimit,
    pub until: ReadUntil,
    pub wait: Option<Duration>,
}

impl ReadEnd {
    pub fn may_follow(&self) -> bool {
        (self.limit.is_unbounded() && self.until.is_unbounded())
            || self.wait.is_some_and(|d| d > Duration::ZERO)
    }
}

#[derive(Clone)]
pub struct ReadBatch<T = Record> {
    pub records: Metered<Vec<Sequenced<T>>>,
    pub tail: Option<StreamPosition>,
}

impl<T> Default for ReadBatch<T>
where
    T: MeteredSize,
{
    fn default() -> Self {
        Self {
            records: Metered::default(),
            tail: None,
        }
    }
}

impl<T> std::fmt::Debug for ReadBatch<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReadBatch")
            .field("num_records", &self.records.len())
            .field("metered_size", &self.records.metered_size())
            .field("tail", &self.tail)
            .finish()
    }
}

#[derive(Debug, Clone)]
pub enum ReadSessionOutput<T = Record> {
    Heartbeat(StreamPosition),
    Batch(ReadBatch<T>),
}

pub type ListStreamsRequest = ListItemsRequest<StreamNamePrefix, StreamNameStartAfter>;

#[cfg(test)]
mod test {
    use rstest::rstest;

    use super::{
        super::strings::{NameProps, PrefixProps, StartAfterProps},
        *,
    };

    #[rstest]
    #[case::normal("my-stream".to_owned())]
    #[case::max_len("a".repeat(crate::caps::MAX_STREAM_NAME_LEN))]
    fn validate_name_ok(#[case] name: String) {
        assert_eq!(StreamNameStr::<NameProps>::validate_str(&name), Ok(()));
    }

    #[rstest]
    #[case::empty("".to_owned())]
    #[case::dot(".".to_owned())]
    #[case::dot_dot("..".to_owned())]
    #[case::too_long("a".repeat(crate::caps::MAX_STREAM_NAME_LEN + 1))]
    fn validate_name_err(#[case] name: String) {
        StreamNameStr::<NameProps>::validate_str(&name).expect_err("expected validation error");
    }

    #[rstest]
    #[case::empty("".to_owned())]
    #[case::dot(".".to_owned())]
    #[case::dot_dot("..".to_owned())]
    #[case::max_len("a".repeat(crate::caps::MAX_STREAM_NAME_LEN))]
    fn validate_prefix_ok(#[case] prefix: String) {
        assert_eq!(StreamNameStr::<PrefixProps>::validate_str(&prefix), Ok(()));
    }

    #[rstest]
    #[case::too_long("a".repeat(crate::caps::MAX_STREAM_NAME_LEN + 1))]
    fn validate_prefix_err(#[case] prefix: String) {
        StreamNameStr::<PrefixProps>::validate_str(&prefix).expect_err("expected validation error");
    }

    #[rstest]
    #[case::empty("".to_owned())]
    #[case::dot(".".to_owned())]
    #[case::dot_dot("..".to_owned())]
    #[case::max_len("a".repeat(crate::caps::MAX_STREAM_NAME_LEN))]
    fn validate_start_after_ok(#[case] start_after: String) {
        assert_eq!(
            StreamNameStr::<StartAfterProps>::validate_str(&start_after),
            Ok(())
        );
    }

    #[rstest]
    #[case::too_long("a".repeat(crate::caps::MAX_STREAM_NAME_LEN + 1))]
    fn validate_start_after_err(#[case] start_after: String) {
        StreamNameStr::<StartAfterProps>::validate_str(&start_after)
            .expect_err("expected validation error");
    }

    #[test]
    fn append_record_batch_rejects_empty_batches() {
        let empty_batch: Result<AppendRecordBatch, _> = Vec::<AppendRecord>::new().try_into();

        assert_eq!(empty_batch.unwrap_err(), "record batch must not be empty");
    }
}