riffdb-types 0.1.0

First-party RiffDB runtime crate (riffdb-types)
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
//! The closed canonical value algebra shared by semantic boundaries.

use std::fmt;

use crate::limits::{
    MAX_BYTES_VALUE_BYTES, MAX_LIST_ENTRIES, MAX_NESTING_DEPTH, MAX_RECORD_FIELDS, MAX_STRING_BYTES,
};
use crate::{CanonicalVector, Date, Decimal, EnumTypeId, EnumVariantId, FieldId, Money, Timestamp};

/// A value in RiffDB's closed, deterministic transactional value algebra.
///
/// Constructors for variable-sized variants enforce process hard limits. The
/// canonical encoder validates again so direct enum construction cannot bypass
/// a durable-boundary check.
#[derive(Clone, Eq, PartialEq)]
pub enum CanonicalValue {
    /// Explicit optional absence.
    Null,
    /// Boolean value.
    Bool(bool),
    /// Signed 64-bit integer.
    I64(i64),
    /// Unsigned 64-bit integer.
    U64(u64),
    /// Checked fixed-scale decimal.
    Decimal(Decimal),
    /// Currency-qualified checked decimal.
    Money(Money),
    /// Exact UTF-8 text without implicit normalization.
    String(CanonicalString),
    /// Exact opaque bytes.
    Bytes(CanonicalBytes),
    /// UTC timestamp supplied by an input or deterministic transaction context.
    Timestamp(Timestamp),
    /// Calendar date represented as days since the Unix epoch.
    Date(Date),
    /// UUID network-order bytes.
    Uuid([u8; 16]),
    /// Stable enum type and variant IDs. Display names are not canonical.
    Enum {
        /// Stable enum type ID.
        type_id: EnumTypeId,
        /// Stable enum variant ID.
        variant_id: EnumVariantId,
    },
    /// Bounded ordered values.
    List(CanonicalList),
    /// Fields in strictly increasing stable-ID order.
    Record(CanonicalRecord),
    /// A fixed-dimension f32 vector for nearest-neighbor search (ADR-0091).
    Vector(CanonicalVector),
}

impl crate::InspectOwnedCapacityV1 for CanonicalValue {
    fn inspect_owned_capacity(
        &self,
        inspection: &mut crate::OwnedCapacityInspectionV1,
    ) -> Result<(), crate::OwnedCapacityInspectionErrorV1> {
        match self {
            Self::String(value) => inspection.visit(value),
            Self::Bytes(value) => inspection.visit(value),
            Self::List(value) => inspection.visit(value),
            Self::Record(value) => inspection.visit(value),
            Self::Vector(value) => inspection.visit(value),
            Self::Null
            | Self::Bool(_)
            | Self::I64(_)
            | Self::U64(_)
            | Self::Decimal(_)
            | Self::Money(_)
            | Self::Timestamp(_)
            | Self::Date(_)
            | Self::Uuid(_)
            | Self::Enum {
                type_id: _,
                variant_id: _,
            } => Ok(()),
        }
    }
}

impl fmt::Debug for CanonicalValue {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Null => formatter.write_str("CanonicalValue::Null"),
            Self::Bool(_) => formatter.write_str("CanonicalValue::Bool([REDACTED])"),
            Self::I64(_) => formatter.write_str("CanonicalValue::I64([REDACTED])"),
            Self::U64(_) => formatter.write_str("CanonicalValue::U64([REDACTED])"),
            Self::Decimal(_) => formatter.write_str("CanonicalValue::Decimal([REDACTED])"),
            Self::Money(_) => formatter.write_str("CanonicalValue::Money([REDACTED])"),
            Self::String(value) => formatter
                .debug_tuple("CanonicalValue::String")
                .field(value)
                .finish(),
            Self::Bytes(value) => formatter
                .debug_tuple("CanonicalValue::Bytes")
                .field(value)
                .finish(),
            Self::Timestamp(_) => formatter.write_str("CanonicalValue::Timestamp([REDACTED])"),
            Self::Date(_) => formatter.write_str("CanonicalValue::Date([REDACTED])"),
            Self::Uuid(_) => formatter.write_str("CanonicalValue::Uuid([REDACTED])"),
            Self::Enum { .. } => formatter.write_str("CanonicalValue::Enum([REDACTED])"),
            Self::List(values) => formatter
                .debug_struct("CanonicalValue::List")
                .field("length", &values.len())
                .finish(),
            Self::Record(record) => formatter
                .debug_struct("CanonicalValue::Record")
                .field("field_count", &record.len())
                .finish(),
            Self::Vector(vector) => formatter
                .debug_struct("CanonicalValue::Vector")
                .field("dimension", &vector.dimension())
                .finish(),
        }
    }
}

impl CanonicalValue {
    /// Constructs bounded exact UTF-8 text.
    pub fn string(value: impl Into<String>) -> Result<Self, ValueError> {
        let value = value.into();
        Ok(Self::String(CanonicalString::new(value)?))
    }

    /// Constructs bounded exact bytes.
    pub fn bytes(value: impl Into<Vec<u8>>) -> Result<Self, ValueError> {
        let value = value.into();
        Ok(Self::Bytes(CanonicalBytes::new(value)?))
    }

    /// Constructs a bounded list without changing its order.
    pub fn list(values: Vec<Self>) -> Result<Self, ValueError> {
        Ok(Self::List(CanonicalList::new(values)?))
    }

    /// Constructs a record, sorting fields by stable ID and rejecting duplicates.
    pub fn record(fields: Vec<(FieldId, Self)>) -> Result<Self, ValueError> {
        Ok(Self::Record(CanonicalRecord::new(fields)?))
    }

    fn nesting_depth(&self) -> usize {
        match self {
            Self::List(list) => list
                .values()
                .iter()
                .map(Self::nesting_depth)
                .max()
                .map_or(0, |depth| depth + 1),
            Self::Record(record) => record
                .fields()
                .iter()
                .map(|(_, value)| value.nesting_depth())
                .max()
                .map_or(0, |depth| depth + 1),
            _ => 0,
        }
    }
}

/// Exact bounded UTF-8 text for a canonical value.
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct CanonicalString(String);
crate::inspect_owned_capacity_tuple_v1!(CanonicalString, String);

impl fmt::Debug for CanonicalString {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CanonicalString")
            .field("value", &"[REDACTED]")
            .field("length", &self.len())
            .finish()
    }
}

impl CanonicalString {
    /// Validates and constructs exact UTF-8 text without normalization.
    pub fn new(value: impl Into<String>) -> Result<Self, ValueError> {
        let value = value.into();
        if value.len() > MAX_STRING_BYTES {
            return Err(ValueError::StringTooLong {
                actual: value.len(),
                maximum: MAX_STRING_BYTES,
            });
        }
        Ok(Self(value))
    }

    /// Borrows the exact UTF-8 text.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns the UTF-8 byte length.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns whether the text is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Consumes the wrapper and returns the owned UTF-8 string.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

/// Exact bounded opaque bytes for a canonical value.
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct CanonicalBytes(Vec<u8>);
crate::inspect_owned_capacity_tuple_v1!(CanonicalBytes, Vec<u8>);

impl fmt::Debug for CanonicalBytes {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CanonicalBytes")
            .field("value", &"[REDACTED]")
            .field("length", &self.len())
            .finish()
    }
}

impl CanonicalBytes {
    /// Validates and constructs an exact byte value.
    pub fn new(value: impl Into<Vec<u8>>) -> Result<Self, ValueError> {
        let value = value.into();
        if value.len() > MAX_BYTES_VALUE_BYTES {
            return Err(ValueError::BytesTooLong {
                actual: value.len(),
                maximum: MAX_BYTES_VALUE_BYTES,
            });
        }
        Ok(Self(value))
    }

    /// Borrows the exact bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Returns the byte length.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns whether the value is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Consumes the wrapper and returns the owned byte vector.
    #[must_use]
    pub fn into_vec(self) -> Vec<u8> {
        self.0
    }
}

/// A bounded ordered list of canonical values.
#[derive(Clone, Eq, PartialEq)]
pub struct CanonicalList(Vec<CanonicalValue>);
crate::inspect_owned_capacity_tuple_v1!(CanonicalList, Vec<CanonicalValue>);

impl fmt::Debug for CanonicalList {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CanonicalList")
            .field("length", &self.len())
            .finish()
    }
}

impl CanonicalList {
    /// Validates and constructs a bounded list without changing its order.
    pub fn new(values: Vec<CanonicalValue>) -> Result<Self, ValueError> {
        if values.len() > MAX_LIST_ENTRIES {
            return Err(ValueError::TooManyListEntries {
                actual: values.len(),
                maximum: MAX_LIST_ENTRIES,
            });
        }
        validate_child_depth(values.iter())?;
        Ok(Self(values))
    }

    /// Borrows the ordered values.
    pub fn values(&self) -> &[CanonicalValue] {
        &self.0
    }

    /// Returns the number of values.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns whether the list contains no values.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Consumes the list and returns the ordered values.
    #[must_use]
    pub fn into_values(self) -> Vec<CanonicalValue> {
        self.0
    }
}

/// A record whose fields are canonicalized by stable field ID.
#[derive(Clone, Eq, PartialEq)]
pub struct CanonicalRecord {
    fields: Vec<(FieldId, CanonicalValue)>,
}
crate::inspect_owned_capacity_struct_v1!(CanonicalRecord {
    owned: [fields],
    inline: []
});

impl fmt::Debug for CanonicalRecord {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CanonicalRecord")
            .field("field_count", &self.len())
            .finish()
    }
}

impl CanonicalRecord {
    /// Sorts fields by stable ID and rejects duplicate IDs.
    pub fn new(mut fields: Vec<(FieldId, CanonicalValue)>) -> Result<Self, ValueError> {
        if fields.len() > MAX_RECORD_FIELDS {
            return Err(ValueError::TooManyRecordFields {
                actual: fields.len(),
                maximum: MAX_RECORD_FIELDS,
            });
        }

        fields.sort_by_key(|(field_id, _)| field_id.get());
        if let Some(field_id) = fields
            .windows(2)
            .find_map(|pair| (pair[0].0 == pair[1].0).then_some(pair[0].0))
        {
            return Err(ValueError::DuplicateRecordField { field_id });
        }
        validate_child_depth(fields.iter().map(|(_, value)| value))?;

        Ok(Self { fields })
    }

    pub(crate) fn from_canonical_fields(fields: Vec<(FieldId, CanonicalValue)>) -> Self {
        debug_assert!(fields.windows(2).all(|pair| pair[0].0 < pair[1].0));
        Self { fields }
    }

    /// Returns fields in strictly increasing stable-ID order.
    pub fn fields(&self) -> &[(FieldId, CanonicalValue)] {
        &self.fields
    }

    /// Returns the number of fields.
    pub fn len(&self) -> usize {
        self.fields.len()
    }

    /// Returns whether the record contains no fields.
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }

    /// Consumes the record and returns fields in stable-ID order.
    #[must_use]
    pub fn into_fields(self) -> Vec<(FieldId, CanonicalValue)> {
        self.fields
    }
}

/// A bounded-value construction failure.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ValueError {
    /// A string exceeds the process hard limit.
    StringTooLong {
        /// Observed UTF-8 byte length.
        actual: usize,
        /// Maximum permitted UTF-8 byte length.
        maximum: usize,
    },
    /// A byte value exceeds the process hard limit.
    BytesTooLong {
        /// Observed byte length.
        actual: usize,
        /// Maximum permitted byte length.
        maximum: usize,
    },
    /// A list exceeds the process hard entry limit.
    TooManyListEntries {
        /// Observed entry count.
        actual: usize,
        /// Maximum permitted entry count.
        maximum: usize,
    },
    /// A record exceeds the process hard field limit.
    TooManyRecordFields {
        /// Observed field count.
        actual: usize,
        /// Maximum permitted field count.
        maximum: usize,
    },
    /// Two record fields use the same stable field ID.
    DuplicateRecordField {
        /// Duplicated stable field ID.
        field_id: FieldId,
    },
    /// A list or record would exceed the canonical nesting limit.
    NestingTooDeep {
        /// Attempted depth below the root value.
        depth: usize,
        /// Maximum depth below the root value.
        maximum: usize,
    },
}

impl fmt::Display for ValueError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::StringTooLong { actual, maximum } => {
                write!(formatter, "string has {actual} bytes; maximum is {maximum}")
            }
            Self::BytesTooLong { actual, maximum } => {
                write!(
                    formatter,
                    "byte value has {actual} bytes; maximum is {maximum}"
                )
            }
            Self::TooManyListEntries { actual, maximum } => {
                write!(formatter, "list has {actual} entries; maximum is {maximum}")
            }
            Self::TooManyRecordFields { actual, maximum } => {
                write!(
                    formatter,
                    "record has {actual} fields; maximum is {maximum}"
                )
            }
            Self::DuplicateRecordField { field_id } => {
                write!(
                    formatter,
                    "record contains duplicate field ID {}",
                    field_id.get()
                )
            }
            Self::NestingTooDeep { depth, maximum } => {
                write!(formatter, "nesting depth is {depth}; maximum is {maximum}")
            }
        }
    }
}

impl std::error::Error for ValueError {}

fn validate_child_depth<'a>(
    children: impl IntoIterator<Item = &'a CanonicalValue>,
) -> Result<(), ValueError> {
    let depth = children
        .into_iter()
        .map(CanonicalValue::nesting_depth)
        .max()
        .map_or(0, |depth| depth + 1);
    if depth > MAX_NESTING_DEPTH {
        return Err(ValueError::NestingTooDeep {
            depth,
            maximum: MAX_NESTING_DEPTH,
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn record_constructor_sorts_and_rejects_duplicates() {
        let record = CanonicalRecord::new(vec![
            (FieldId::new(9).expect("nonzero"), CanonicalValue::Null),
            (
                FieldId::new(2).expect("nonzero"),
                CanonicalValue::Bool(true),
            ),
        ])
        .expect("valid record");
        assert_eq!(
            record
                .fields()
                .iter()
                .map(|(id, _)| id.get())
                .collect::<Vec<_>>(),
            [2, 9]
        );

        assert_eq!(
            CanonicalRecord::new(vec![
                (FieldId::new(2).expect("nonzero"), CanonicalValue::Null),
                (FieldId::new(2).expect("nonzero"), CanonicalValue::Null),
            ]),
            Err(ValueError::DuplicateRecordField {
                field_id: FieldId::new(2).expect("nonzero")
            })
        );
    }

    #[test]
    fn canonical_debug_output_redacts_exact_values() {
        let secret = "raw-idempotency-key-canary";
        let values = [
            CanonicalValue::string(secret).expect("bounded string"),
            CanonicalValue::bytes(secret.as_bytes().to_vec()).expect("bounded bytes"),
            CanonicalValue::I64(4_242_424_242),
        ];

        for value in values {
            let output = format!("{value:?}");
            assert!(!output.contains(secret));
            assert!(!output.contains("4242424242"));
        }
    }
}