baukit-core 0.10.21

Dependency-light shared vocabulary for Baukit services.
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
//! Runtime-neutral resource-budget measurements.

use serde::Serialize;
use thiserror::Error;

/// A measured amount and the maximum amount allowed by a caller.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LimitMeasurement {
    measured: usize,
    allowed: usize,
}

impl LimitMeasurement {
    /// Returns the measured amount.
    #[must_use]
    pub const fn measured(self) -> usize {
        self.measured
    }

    /// Returns the caller-provided maximum.
    #[must_use]
    pub const fn allowed(self) -> usize {
        self.allowed
    }
}

/// A resource-budget check whose measured amount exceeds its allowed amount.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[error("measured {measured} exceeds allowed {allowed}")]
pub struct LimitExceeded {
    measured: usize,
    allowed: usize,
}

impl LimitExceeded {
    /// Returns the measured amount.
    #[must_use]
    pub const fn measured(self) -> usize {
        self.measured
    }

    /// Returns the caller-provided maximum.
    #[must_use]
    pub const fn allowed(self) -> usize {
        self.allowed
    }
}

/// A whole-number measurement within inclusive caller-provided bounds.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LimitRange {
    measured: u64,
    minimum: u64,
    maximum: u64,
}

impl LimitRange {
    /// Returns the measured amount.
    #[must_use]
    pub const fn measured(self) -> u64 {
        self.measured
    }

    /// Returns the inclusive minimum.
    #[must_use]
    pub const fn minimum(self) -> u64 {
        self.minimum
    }

    /// Returns the inclusive maximum.
    #[must_use]
    pub const fn maximum(self) -> u64 {
        self.maximum
    }
}

/// A whole-number measurement outside inclusive caller-provided bounds.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[error("measured {measured} is outside {minimum}..={maximum}")]
pub struct LimitOutOfRange {
    measured: u64,
    minimum: u64,
    maximum: u64,
}

impl LimitOutOfRange {
    /// Returns the measured amount.
    #[must_use]
    pub const fn measured(self) -> u64 {
        self.measured
    }

    /// Returns the inclusive minimum.
    #[must_use]
    pub const fn minimum(self) -> u64 {
        self.minimum
    }

    /// Returns the inclusive maximum.
    #[must_use]
    pub const fn maximum(self) -> u64 {
        self.maximum
    }
}

/// Caller-provided bounds whose minimum exceeds their maximum.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[error("minimum {minimum} exceeds maximum {maximum}")]
pub struct InvalidLimitRange {
    minimum: u64,
    maximum: u64,
}

impl InvalidLimitRange {
    /// Returns the caller-provided minimum.
    #[must_use]
    pub const fn minimum(self) -> u64 {
        self.minimum
    }

    /// Returns the caller-provided maximum.
    #[must_use]
    pub const fn maximum(self) -> u64 {
        self.maximum
    }
}

/// An invalid range or a measurement outside a valid range.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
pub enum LimitRangeError {
    /// The caller supplied inverted bounds.
    #[error(transparent)]
    InvalidBounds(#[from] InvalidLimitRange),
    /// The measurement is below the minimum or above the maximum.
    #[error(transparent)]
    OutOfRange(#[from] LimitOutOfRange),
}

/// An error from encoding and checking compact JSON.
#[derive(Debug, Error)]
pub enum CompactJsonLimitError {
    /// Compact JSON encoding failed.
    #[error("compact JSON encoding failed")]
    Encoding(#[from] serde_json::Error),
    /// The encoded JSON exceeds the caller-provided maximum.
    #[error(transparent)]
    Limit(#[from] LimitExceeded),
}

/// Counts Unicode scalar values after trimming Unicode whitespace from both ends.
#[must_use]
pub fn trimmed_unicode_scalar_count(value: &str) -> usize {
    value.trim().chars().count()
}

/// Returns the UTF-8 byte length of the compact JSON encoding.
pub fn compact_json_utf8_bytes(value: &impl Serialize) -> Result<usize, serde_json::Error> {
    serde_json::to_vec(value).map(|encoded| encoded.len())
}

/// Returns the length of a byte slice.
#[must_use]
pub const fn byte_length(value: &[u8]) -> usize {
    value.len()
}

/// Returns the number of elements in a slice.
#[must_use]
pub const fn collection_length<Element>(value: &[Element]) -> usize {
    value.len()
}

/// Checks a measured amount against a caller-provided maximum.
pub const fn check_measurement(
    measured: usize,
    allowed: usize,
) -> Result<LimitMeasurement, LimitExceeded> {
    if measured > allowed {
        return Err(LimitExceeded { measured, allowed });
    }
    Ok(LimitMeasurement { measured, allowed })
}

/// Checks a whole-number measurement against inclusive bounds.
///
/// Uses `u64` so seconds from [`std::time::Duration::as_secs`] fit on every target.
/// Inverted bounds return [`LimitRangeError::InvalidBounds`] before checking the measurement.
pub const fn check_range(
    measured: u64,
    minimum: u64,
    maximum: u64,
) -> Result<LimitRange, LimitRangeError> {
    if minimum > maximum {
        return Err(LimitRangeError::InvalidBounds(InvalidLimitRange {
            minimum,
            maximum,
        }));
    }
    if measured < minimum || measured > maximum {
        return Err(LimitRangeError::OutOfRange(LimitOutOfRange {
            measured,
            minimum,
            maximum,
        }));
    }
    Ok(LimitRange {
        measured,
        minimum,
        maximum,
    })
}

/// Measures trimmed Unicode scalar values and checks the result.
pub fn check_trimmed_unicode_scalars(
    value: &str,
    allowed: usize,
) -> Result<LimitMeasurement, LimitExceeded> {
    check_measurement(trimmed_unicode_scalar_count(value), allowed)
}

/// Measures compact JSON UTF-8 bytes and checks the result.
pub fn check_compact_json_utf8_bytes(
    value: &impl Serialize,
    allowed: usize,
) -> Result<LimitMeasurement, CompactJsonLimitError> {
    let measured = compact_json_utf8_bytes(value)?;
    check_measurement(measured, allowed).map_err(Into::into)
}

/// Measures a byte slice and checks the result.
pub const fn check_bytes(value: &[u8], allowed: usize) -> Result<LimitMeasurement, LimitExceeded> {
    check_measurement(byte_length(value), allowed)
}

/// Measures a collection slice and checks the result.
pub const fn check_collection<Element>(
    value: &[Element],
    allowed: usize,
) -> Result<LimitMeasurement, LimitExceeded> {
    check_measurement(collection_length(value), allowed)
}

#[cfg(test)]
mod tests {
    use serde::Deserialize;
    use serde_json::{Value, json};

    use super::*;

    #[derive(Debug, Deserialize)]
    struct FixtureCorpus {
        version: u8,
        text: Vec<TextFixture>,
        json: Vec<JsonFixture>,
        bytes: Vec<BytesFixture>,
        collections: Vec<CollectionFixture>,
        ranges: Vec<RangeFixture>,
    }

    #[derive(Debug, Deserialize)]
    struct TextFixture {
        name: String,
        value: String,
        trimmed_unicode_scalars: usize,
    }

    #[derive(Debug, Deserialize)]
    struct JsonFixture {
        name: String,
        value: Value,
        compact: String,
        utf8_bytes: usize,
    }

    #[derive(Debug, Deserialize)]
    struct BytesFixture {
        name: String,
        value: Vec<u8>,
        bytes: usize,
    }

    #[derive(Debug, Deserialize)]
    struct CollectionFixture {
        name: String,
        value: Vec<Value>,
        elements: usize,
    }

    #[derive(Debug, Deserialize)]
    struct RangeFixture {
        name: String,
        measured: u64,
        minimum: u64,
        maximum: u64,
        outcome: String,
    }

    fn fixtures() -> FixtureCorpus {
        serde_json::from_str(include_str!(
            "../../../../fixtures/limits/resource-budget-measurements-v1.json"
        ))
        .expect("resource-budget fixture should parse")
    }

    #[test]
    fn shared_ranges_check_inclusive_bounds_and_distinguish_invalid_bounds() {
        let ranges = fixtures().ranges;
        assert_eq!(ranges.len(), 11);
        for fixture in ranges {
            let result = check_range(fixture.measured, fixture.minimum, fixture.maximum);
            match fixture.outcome.as_str() {
                "ok" => {
                    let measurement = result.expect(&fixture.name);
                    assert_eq!(measurement.measured(), fixture.measured, "{}", fixture.name);
                    assert_eq!(measurement.minimum(), fixture.minimum, "{}", fixture.name);
                    assert_eq!(measurement.maximum(), fixture.maximum, "{}", fixture.name);
                }
                "out_of_range" => {
                    let Err(LimitRangeError::OutOfRange(error)) = result else {
                        panic!(
                            "{}: expected out-of-range error, got {result:?}",
                            fixture.name
                        );
                    };
                    assert_eq!(error.measured(), fixture.measured, "{}", fixture.name);
                    assert_eq!(error.minimum(), fixture.minimum, "{}", fixture.name);
                    assert_eq!(error.maximum(), fixture.maximum, "{}", fixture.name);
                }
                "invalid_bounds" => {
                    let Err(LimitRangeError::InvalidBounds(error)) = result else {
                        panic!("{}: expected invalid bounds, got {result:?}", fixture.name);
                    };
                    assert_eq!(error.minimum(), fixture.minimum, "{}", fixture.name);
                    assert_eq!(error.maximum(), fixture.maximum, "{}", fixture.name);
                }
                outcome => panic!("unknown range fixture outcome {outcome}"),
            }
        }
    }

    #[test]
    fn range_checks_accept_the_full_duration_seconds_width() {
        assert_eq!(
            check_range(u64::MAX, 0, u64::MAX)
                .expect("full-width duration should fit")
                .measured(),
            u64::MAX
        );
        assert!(matches!(
            check_range(0, u64::MAX, 0),
            Err(LimitRangeError::InvalidBounds(_))
        ));
    }

    #[test]
    fn counts_ascii_composed_decomposed_and_emoji_scalars() {
        assert_eq!(trimmed_unicode_scalar_count(" plain "), 5);
        assert_eq!(trimmed_unicode_scalar_count("\u{e9}"), 1);
        assert_eq!(trimmed_unicode_scalar_count("e\u{301}"), 2);
        assert_eq!(
            trimmed_unicode_scalar_count(
                "\u{1f469}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466}"
            ),
            7
        );
    }

    #[test]
    fn measures_compact_objects_arrays_escapes_and_multibyte_strings() {
        for fixture in fixtures().json {
            let encoded = serde_json::to_string(&fixture.value).expect("fixture should encode");
            assert_eq!(encoded, fixture.compact, "{}", fixture.name);
            assert_eq!(
                compact_json_utf8_bytes(&fixture.value).expect("fixture should encode"),
                fixture.utf8_bytes,
                "{}",
                fixture.name
            );
        }
    }

    #[test]
    fn byte_and_collection_checks_report_both_sides_of_the_boundary() {
        let bytes = [1_u8, 2, 3];
        let values = ["a", "b", "c"];

        assert_eq!(
            check_bytes(&bytes, 3)
                .expect("boundary should pass")
                .measured(),
            3
        );
        assert_eq!(
            check_collection(&values, 3)
                .expect("boundary should pass")
                .allowed(),
            3
        );
        assert_eq!(
            check_bytes(&bytes, 2),
            Err(LimitExceeded {
                measured: 3,
                allowed: 2,
            })
        );
        assert_eq!(
            check_collection(&values, 2),
            Err(LimitExceeded {
                measured: 3,
                allowed: 2,
            })
        );
    }

    #[test]
    fn specialized_checks_return_measurement_and_allowed_values() {
        assert_eq!(
            check_trimmed_unicode_scalars("  e\u{301}  ", 2),
            Ok(LimitMeasurement {
                measured: 2,
                allowed: 2,
            })
        );
        let error = check_compact_json_utf8_bytes(&json!({"value": "\u{e9}"}), 13)
            .expect_err("fourteen-byte document should fail");
        assert!(matches!(
            error,
            CompactJsonLimitError::Limit(LimitExceeded {
                measured: 14,
                allowed: 13,
            })
        ));
    }

    #[test]
    fn shared_fixture_matches_all_rust_measurements() {
        let fixtures = fixtures();
        assert_eq!(fixtures.version, 1);
        assert!(!fixtures.text.is_empty());
        assert!(!fixtures.json.is_empty());
        assert!(!fixtures.bytes.is_empty());
        assert!(!fixtures.collections.is_empty());

        for fixture in fixtures.text {
            assert_eq!(
                trimmed_unicode_scalar_count(&fixture.value),
                fixture.trimmed_unicode_scalars,
                "{}",
                fixture.name
            );
        }
        for fixture in fixtures.bytes {
            assert_eq!(
                byte_length(&fixture.value),
                fixture.bytes,
                "{}",
                fixture.name
            );
        }
        for fixture in fixtures.collections {
            assert_eq!(
                collection_length(&fixture.value),
                fixture.elements,
                "{}",
                fixture.name
            );
        }
    }
}