exoware-sdk 2026.4.1

Interact with the Exoware API in Rust.
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
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
use anyhow::{ensure, Context};
use bytes::{Buf, BufMut};
use commonware_codec::{
    Encode, EncodeSize, Error as CodecError, FixedSize, RangeCfg, Read, ReadExt, Write,
};
use std::collections::HashSet;

use crate::keys::KeyCodec;
use crate::kv_codec::Utf8;
use crate::match_key::{compile_payload_regex, MatchKey};

pub use crate::match_key::MatchKey as MatchKeyReexport;

pub const PRUNE_POLICY_CONTROL_KEY: &str = "manifest/control/compaction-prune-policies";
pub const PRUNE_POLICY_DOCUMENT_VERSION: u32 = 1;

/// One prune rule. `scope` picks the keyspace; `retain` decides what survives.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PrunePolicy {
    pub scope: PolicyScope,
    pub retain: RetainPolicy,
}

/// Which keyspace a `PrunePolicy` applies to. `Keys` mirrors the original
/// user-keys prune (filter by family+regex, group, order, then retain).
/// `Sequence` operates over the sequence-number-indexed batch log served by
/// `store.stream.v1` — no grouping/ordering needed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PolicyScope {
    Keys(KeysScope),
    Sequence,
}

/// User-key-space scope: same meaning as the previous top-level prune policy
/// fields, just nested under the scope discriminator.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KeysScope {
    pub match_key: MatchKey,
    pub group_by: GroupBy,
    pub order_by: Option<OrderBy>,
}

#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct GroupBy {
    pub capture_groups: Vec<Utf8>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OrderBy {
    pub capture_group: Utf8,
    pub encoding: OrderEncoding,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OrderEncoding {
    BytesAsc,
    U64Be,
    I64Be,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RetainPolicy {
    KeepLatest { count: usize },
    GreaterThan { threshold: u64 },
    GreaterThanOrEqual { threshold: u64 },
    DropAll,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PrunePolicyDocument {
    pub version: u32,
    pub policies: Vec<PrunePolicy>,
}

impl Write for OrderEncoding {
    fn write(&self, buf: &mut impl BufMut) {
        match self {
            OrderEncoding::BytesAsc => 0u8.write(buf),
            OrderEncoding::U64Be => 1u8.write(buf),
            OrderEncoding::I64Be => 2u8.write(buf),
        }
    }
}

impl FixedSize for OrderEncoding {
    const SIZE: usize = 1;
}

impl Read for OrderEncoding {
    type Cfg = ();
    fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, CodecError> {
        match u8::read(buf)? {
            0 => Ok(OrderEncoding::BytesAsc),
            1 => Ok(OrderEncoding::U64Be),
            2 => Ok(OrderEncoding::I64Be),
            v => Err(CodecError::InvalidEnum(v)),
        }
    }
}

impl Write for RetainPolicy {
    fn write(&self, buf: &mut impl BufMut) {
        match self {
            RetainPolicy::KeepLatest { count } => {
                0u8.write(buf);
                (*count as u64).write(buf);
            }
            RetainPolicy::GreaterThan { threshold } => {
                1u8.write(buf);
                threshold.write(buf);
            }
            RetainPolicy::GreaterThanOrEqual { threshold } => {
                2u8.write(buf);
                threshold.write(buf);
            }
            RetainPolicy::DropAll => {
                3u8.write(buf);
            }
        }
    }
}

impl EncodeSize for RetainPolicy {
    fn encode_size(&self) -> usize {
        1 + match self {
            RetainPolicy::KeepLatest { .. }
            | RetainPolicy::GreaterThan { .. }
            | RetainPolicy::GreaterThanOrEqual { .. } => u64::SIZE,
            RetainPolicy::DropAll => 0,
        }
    }
}

impl Read for RetainPolicy {
    type Cfg = ();
    fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, CodecError> {
        match u8::read(buf)? {
            0 => Ok(RetainPolicy::KeepLatest {
                count: u64::read(buf)? as usize,
            }),
            1 => Ok(RetainPolicy::GreaterThan {
                threshold: u64::read(buf)?,
            }),
            2 => Ok(RetainPolicy::GreaterThanOrEqual {
                threshold: u64::read(buf)?,
            }),
            3 => Ok(RetainPolicy::DropAll),
            v => Err(CodecError::InvalidEnum(v)),
        }
    }
}

impl Write for GroupBy {
    fn write(&self, buf: &mut impl BufMut) {
        self.capture_groups.as_slice().write(buf);
    }
}

impl EncodeSize for GroupBy {
    fn encode_size(&self) -> usize {
        self.capture_groups.as_slice().encode_size()
    }
}

impl Read for GroupBy {
    type Cfg = ();
    fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, CodecError> {
        let range: RangeCfg<usize> = (..).into();
        let capture_groups = Vec::<Utf8>::read_cfg(buf, &(range, ()))?;
        Ok(GroupBy { capture_groups })
    }
}

impl Write for OrderBy {
    fn write(&self, buf: &mut impl BufMut) {
        self.capture_group.write(buf);
        self.encoding.write(buf);
    }
}

impl EncodeSize for OrderBy {
    fn encode_size(&self) -> usize {
        self.capture_group.encode_size() + OrderEncoding::SIZE
    }
}

impl Read for OrderBy {
    type Cfg = ();
    fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, CodecError> {
        Ok(OrderBy {
            capture_group: Utf8::read(buf)?,
            encoding: OrderEncoding::read(buf)?,
        })
    }
}

impl Write for KeysScope {
    fn write(&self, buf: &mut impl BufMut) {
        self.match_key.write(buf);
        self.group_by.write(buf);
        self.order_by.write(buf);
    }
}

impl EncodeSize for KeysScope {
    fn encode_size(&self) -> usize {
        self.match_key.encode_size() + self.group_by.encode_size() + self.order_by.encode_size()
    }
}

impl Read for KeysScope {
    type Cfg = ();
    fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, CodecError> {
        Ok(KeysScope {
            match_key: MatchKey::read(buf)?,
            group_by: GroupBy::read(buf)?,
            order_by: Option::<OrderBy>::read(buf)?,
        })
    }
}

impl Write for PolicyScope {
    fn write(&self, buf: &mut impl BufMut) {
        match self {
            PolicyScope::Keys(s) => {
                0u8.write(buf);
                s.write(buf);
            }
            PolicyScope::Sequence => {
                1u8.write(buf);
            }
        }
    }
}

impl EncodeSize for PolicyScope {
    fn encode_size(&self) -> usize {
        1 + match self {
            PolicyScope::Keys(s) => s.encode_size(),
            PolicyScope::Sequence => 0,
        }
    }
}

impl Read for PolicyScope {
    type Cfg = ();
    fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, CodecError> {
        match u8::read(buf)? {
            0 => Ok(PolicyScope::Keys(KeysScope::read(buf)?)),
            1 => Ok(PolicyScope::Sequence),
            v => Err(CodecError::InvalidEnum(v)),
        }
    }
}

impl Write for PrunePolicy {
    fn write(&self, buf: &mut impl BufMut) {
        self.scope.write(buf);
        self.retain.write(buf);
    }
}

impl EncodeSize for PrunePolicy {
    fn encode_size(&self) -> usize {
        self.scope.encode_size() + self.retain.encode_size()
    }
}

impl Read for PrunePolicy {
    type Cfg = ();
    fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, CodecError> {
        Ok(PrunePolicy {
            scope: PolicyScope::read(buf)?,
            retain: RetainPolicy::read(buf)?,
        })
    }
}

impl Write for PrunePolicyDocument {
    fn write(&self, buf: &mut impl BufMut) {
        self.version.write(buf);
        self.policies.as_slice().write(buf);
    }
}

impl EncodeSize for PrunePolicyDocument {
    fn encode_size(&self) -> usize {
        u32::SIZE + self.policies.as_slice().encode_size()
    }
}

impl Read for PrunePolicyDocument {
    type Cfg = ();
    fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, CodecError> {
        let version = u32::read(buf)?;
        let range: RangeCfg<usize> = (..).into();
        let policies = Vec::<PrunePolicy>::read_cfg(buf, &(range, ()))?;
        Ok(PrunePolicyDocument { version, policies })
    }
}

pub fn validate_policy(policy: &PrunePolicy) -> anyhow::Result<()> {
    match &policy.scope {
        PolicyScope::Keys(scope) => validate_user_keys_scope(scope)?,
        PolicyScope::Sequence => {
            // No scope-level configuration to validate; retention rules below
            // are constrained by `validate_retain_for_scope`.
        }
    }
    validate_retain_for_scope(policy)?;
    Ok(())
}

fn validate_user_keys_scope(scope: &KeysScope) -> anyhow::Result<()> {
    KeyCodec::new(scope.match_key.reserved_bits, scope.match_key.prefix);
    let regex = compile_payload_regex(&scope.match_key.payload_regex)?;
    validate_capture_groups(
        &regex,
        &scope.group_by.capture_groups,
        "group_by capture_groups",
    )?;
    ensure!(
        capture_groups_are_unique(&scope.group_by.capture_groups),
        "group_by capture_groups must not contain duplicates"
    );
    if let Some(order_by) = &scope.order_by {
        validate_capture_groups(
            &regex,
            std::slice::from_ref(&order_by.capture_group),
            "order_by capture_group",
        )?;
    }
    Ok(())
}

fn validate_retain_for_scope(policy: &PrunePolicy) -> anyhow::Result<()> {
    match &policy.scope {
        PolicyScope::Keys(scope) => match policy.retain {
            RetainPolicy::KeepLatest { count } => {
                ensure!(count > 0, "keep_latest count must be > 0");
                ensure!(
                    scope.order_by.is_some(),
                    "keep_latest requires order_by to be configured"
                );
            }
            RetainPolicy::GreaterThan { .. } | RetainPolicy::GreaterThanOrEqual { .. } => {
                let order_by = scope
                    .order_by
                    .as_ref()
                    .context("threshold retention requires order_by to be configured")?;
                ensure!(
                    matches!(order_by.encoding, OrderEncoding::U64Be),
                    "threshold retention currently requires order_by.encoding = u64_be"
                );
            }
            RetainPolicy::DropAll => {}
        },
        PolicyScope::Sequence => match policy.retain {
            RetainPolicy::KeepLatest { count } => {
                ensure!(count > 0, "keep_latest count must be > 0");
            }
            RetainPolicy::GreaterThan { .. }
            | RetainPolicy::GreaterThanOrEqual { .. }
            | RetainPolicy::DropAll => {}
        },
    }
    Ok(())
}

pub fn ensure_unique_policy_families(policies: &[PrunePolicy]) -> anyhow::Result<()> {
    let mut user_families = HashSet::new();
    let mut sequence_seen = false;
    for policy in policies {
        match &policy.scope {
            PolicyScope::Keys(scope) => {
                ensure!(
                    user_families.insert((scope.match_key.reserved_bits, scope.match_key.prefix)),
                    "duplicate compaction prune policy for reserved_bits={} family={}",
                    scope.match_key.reserved_bits,
                    scope.match_key.prefix
                );
            }
            PolicyScope::Sequence => {
                ensure!(
                    !sequence_seen,
                    "duplicate compaction prune policy for sequence scope"
                );
                sequence_seen = true;
            }
        }
    }
    Ok(())
}

pub fn validate_policy_document(document: &PrunePolicyDocument) -> anyhow::Result<()> {
    ensure!(
        document.version == PRUNE_POLICY_DOCUMENT_VERSION,
        "unsupported prune policy document version {} (expected {})",
        document.version,
        PRUNE_POLICY_DOCUMENT_VERSION
    );
    for policy in &document.policies {
        validate_policy(policy)?;
    }
    ensure_unique_policy_families(&document.policies)?;
    Ok(())
}

pub fn decode_policy_document(raw: &[u8]) -> anyhow::Result<PrunePolicyDocument> {
    if raw.is_empty() {
        return Ok(PrunePolicyDocument {
            version: PRUNE_POLICY_DOCUMENT_VERSION,
            policies: Vec::new(),
        });
    }
    let document = PrunePolicyDocument::read_cfg(&mut &*raw, &())
        .context("failed to decode prune policy document")?;
    validate_policy_document(&document)?;
    Ok(document)
}

pub fn encode_policy_document(document: &PrunePolicyDocument) -> anyhow::Result<Vec<u8>> {
    validate_policy_document(document)?;
    Ok(document.encode().to_vec())
}

fn validate_capture_groups(
    regex: &regex::bytes::Regex,
    groups: &[Utf8],
    label: &str,
) -> anyhow::Result<()> {
    let known: HashSet<&str> = regex.capture_names().flatten().collect();
    for group in groups {
        ensure!(
            known.contains(&**group),
            "{label} references unknown capture group {group:?}"
        );
    }
    Ok(())
}

fn capture_groups_are_unique(groups: &[Utf8]) -> bool {
    let mut seen = HashSet::new();
    groups.iter().all(|group| seen.insert(group))
}

#[cfg(test)]
mod tests {
    use super::{
        decode_policy_document, encode_policy_document, GroupBy, KeysScope, MatchKey, OrderBy,
        OrderEncoding, PolicyScope, PrunePolicy, PrunePolicyDocument, RetainPolicy,
        PRUNE_POLICY_CONTROL_KEY,
    };
    use crate::kv_codec::Utf8;

    fn sample_policy() -> PrunePolicy {
        PrunePolicy {
            scope: PolicyScope::Keys(KeysScope {
                match_key: MatchKey {
                    reserved_bits: 4,
                    prefix: 1,
                    payload_regex: Utf8::from(
                        "(?s-u)^(?P<logical>(?:\\x00\\xFF|[^\\x00])*)\\x00\\x00(?P<version>.{8})$",
                    ),
                },
                group_by: GroupBy {
                    capture_groups: vec![Utf8::from("logical")],
                },
                order_by: Some(OrderBy {
                    capture_group: Utf8::from("version"),
                    encoding: OrderEncoding::U64Be,
                }),
            }),
            retain: RetainPolicy::KeepLatest { count: 10 },
        }
    }

    fn sample_document() -> PrunePolicyDocument {
        PrunePolicyDocument {
            version: 1,
            policies: vec![sample_policy()],
        }
    }

    #[test]
    fn codec_round_trip() {
        let encoded = encode_policy_document(&sample_document()).expect("encode");
        let decoded = decode_policy_document(&encoded).expect("decode");
        assert_eq!(decoded, sample_document());
    }

    #[test]
    fn empty_bytes_means_no_policies() {
        let decoded = decode_policy_document(b"").expect("empty ok");
        assert_eq!(decoded.version, 1);
        assert!(decoded.policies.is_empty());
        assert_eq!(
            PRUNE_POLICY_CONTROL_KEY,
            "manifest/control/compaction-prune-policies"
        );
    }

    #[test]
    fn keep_latest_requires_order_by() {
        let doc = PrunePolicyDocument {
            version: 1,
            policies: vec![PrunePolicy {
                scope: PolicyScope::Keys(KeysScope {
                    match_key: MatchKey {
                        reserved_bits: 4,
                        prefix: 1,
                        payload_regex: Utf8::from(
                            "(?s-u)^(?P<logical>(?:\\x00\\xFF|[^\\x00])*)\\x00\\x00(?P<version>.{8})$",
                        ),
                    },
                    group_by: GroupBy {
                        capture_groups: vec![Utf8::from("logical")],
                    },
                    order_by: None,
                }),
                retain: RetainPolicy::KeepLatest { count: 1 },
            }],
        };
        let encoded = encode_policy_document(&doc);
        assert!(encoded.is_err());
        assert!(encoded
            .unwrap_err()
            .to_string()
            .contains("keep_latest requires order_by"));
    }

    #[test]
    fn capture_groups_must_exist() {
        let doc = PrunePolicyDocument {
            version: 1,
            policies: vec![PrunePolicy {
                scope: PolicyScope::Keys(KeysScope {
                    match_key: MatchKey {
                        reserved_bits: 4,
                        prefix: 1,
                        payload_regex: Utf8::from("(?s)^(?P<logical>.+)$"),
                    },
                    group_by: GroupBy {
                        capture_groups: vec![Utf8::from("missing")],
                    },
                    order_by: Some(OrderBy {
                        capture_group: Utf8::from("logical"),
                        encoding: OrderEncoding::BytesAsc,
                    }),
                }),
                retain: RetainPolicy::KeepLatest { count: 1 },
            }],
        };
        let encoded = encode_policy_document(&doc);
        assert!(encoded.is_err());
        assert!(encoded
            .unwrap_err()
            .to_string()
            .contains("unknown capture group"));
    }

    #[test]
    fn sequence_scope_codec_round_trip() {
        let doc = PrunePolicyDocument {
            version: 1,
            policies: vec![PrunePolicy {
                scope: PolicyScope::Sequence,
                retain: RetainPolicy::KeepLatest { count: 100 },
            }],
        };
        let encoded = encode_policy_document(&doc).expect("encode");
        let decoded = decode_policy_document(&encoded).expect("decode");
        assert_eq!(decoded, doc);
    }

    #[test]
    fn sequence_scope_rejects_duplicate() {
        let doc = PrunePolicyDocument {
            version: 1,
            policies: vec![
                PrunePolicy {
                    scope: PolicyScope::Sequence,
                    retain: RetainPolicy::DropAll,
                },
                PrunePolicy {
                    scope: PolicyScope::Sequence,
                    retain: RetainPolicy::GreaterThan { threshold: 10 },
                },
            ],
        };
        let err = encode_policy_document(&doc).unwrap_err();
        assert!(err.to_string().contains("sequence"));
    }
}