qubit-budget 0.5.0

Dependency-light resource limit and budget accounting primitives for Qubit Rust crates
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
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Transactional admission for one complete JSON value.

use super::JsonValueBudget;
use super::internal::JsonValueState;
use super::internal::PreparedJsonAdmission;
use crate::json::JsonContainerKind;
use crate::json::JsonMeasurement;
use crate::resource::InsufficientBudgetError;
use crate::resource::MeasuredBudgetError;
use crate::resource::ResourceQuantity;

/// A transaction that stages JSON-value accounting until explicitly committed.
///
/// Dropping this value, including during unwinding, discards its fixed-size
/// working state and leaves the target budget's committed state unchanged.
/// A failed admission changes neither the working nor committed state and
/// permanently poisons the transaction. Every later admission returns the
/// first error, and [`Self::commit`] returns that error without publishing any
/// staged state. Returning an admission error with `?` therefore drops the
/// transaction and publishes none of its staged state.
///
/// # Type Parameters
///
/// * `R` - Caller-defined resource identity retained by limits and errors.
/// * `Q` - Exact unsigned quantity used for measurements and accounting.
///
/// # Examples
///
/// ```
/// use qubit_budget::json::JsonMeasurement;
/// use qubit_budget::json::JsonValueLimits;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut budget = JsonValueLimits::builder().max_nodes(1_usize).budget();
/// let mut transaction = budget.transaction();
/// transaction.try_admit(JsonMeasurement::Null { depth: 1 }).expect("null should fit");
/// transaction.commit()?;
/// assert_eq!(budget.used_nodes(), Some(1));
/// # Ok(()) }
/// ```
pub struct JsonValueTransaction<'a, R, Q>
where
    Q: ResourceQuantity,
{
    /// Budget that receives the staged state if [`Self::commit`] is called.
    target: &'a mut JsonValueBudget<R, Q>,
    /// Fixed-size state changed by successful staged admissions.
    working: JsonValueState<Q>,
    /// First admission failure, retained to prevent partial publication.
    failure: Option<MeasuredBudgetError<R, Q>>,
}

impl<'a, R, Q> JsonValueTransaction<'a, R, Q>
where
    R: Clone,
    Q: ResourceQuantity,
{
    /// Creates a transaction using a snapshot of `target`'s committed state.
    ///
    /// # Parameters
    ///
    /// * `target` - Mutable accounting state updated by the operation.
    ///
    /// # Returns
    ///
    /// Creates a transaction using a snapshot of `target`'s committed state.
    #[inline(always)]
    pub(super) const fn new(target: &'a mut JsonValueBudget<R, Q>) -> Self {
        Self {
            working: target.state,
            failure: None,
            target,
        }
    }

    /// Indicates whether this transaction enforces any JSON-value limit.
    ///
    /// # Returns
    ///
    /// Returns `true` when at least one point or cumulative value limit is
    /// configured on the target budget.
    #[must_use]
    #[inline(always)]
    pub const fn has_limits(&self) -> bool {
        self.target.limits().has_limits()
    }

    /// Stages one native JSON measurement when all applicable limits allow it.
    ///
    /// Point limits are checked before cumulative node and payload capacity.
    /// Within cumulative accounting, node capacity is checked before payload.
    ///
    /// Returns conversion, point-limit, or cumulative-budget errors with their
    /// configured resource identity. Any error leaves this transaction's
    /// working state unchanged, poisons the transaction, and does not affect
    /// the committed budget.
    ///
    /// # Parameters
    ///
    /// * `measurement` - Native JSON measurement to convert or admit.
    ///
    /// # Returns
    ///
    /// `Ok(())` when the operation completes successfully.
    ///
    /// # Errors
    ///
    /// Returns [`MeasuredBudgetError`] when a native measurement cannot fit `Q`
    /// or a configured limit rejects it.
    pub fn try_admit(&mut self, measurement: JsonMeasurement) -> Result<(), MeasuredBudgetError<R, Q>> {
        if let Some(error) = &self.failure {
            return Err(error.clone());
        }
        let result: Result<PreparedJsonAdmission<Q>, MeasuredBudgetError<R, Q>> = (|| {
            let prepared = PreparedJsonAdmission::prepare(self.target.limits(), measurement)?;
            prepared.check_point(self.target.limits())?;
            self.check_cumulative(prepared)?;
            Ok(prepared)
        })();
        match result {
            Ok(prepared) => {
                self.apply(prepared);
                Ok(())
            }
            Err(error) => {
                self.failure = Some(error.clone());
                Err(error)
            }
        }
    }

    /// Stages admission of a container before traversing its children.
    ///
    /// This checks the container depth and consumes its node immediately;
    /// child-count limits remain enforceable through
    /// [`Self::check_container_count`].
    ///
    /// # Parameters
    ///
    /// * `kind` - JSON container kind whose depth and node admission is staged.
    /// * `depth` - Root-inclusive nesting depth to validate.
    ///
    /// # Returns
    ///
    /// `Ok(())` when the operation completes successfully.
    ///
    /// # Errors
    ///
    /// Returns [`MeasuredBudgetError`] when a native measurement cannot fit `Q`
    /// or a configured limit rejects it.
    pub fn try_enter_container(
        &mut self,
        kind: JsonContainerKind,
        depth: usize,
    ) -> Result<(), MeasuredBudgetError<R, Q>> {
        let measurement = match kind {
            JsonContainerKind::Sequence => JsonMeasurement::Array { depth, items: 0 },
            JsonContainerKind::Map => JsonMeasurement::Object { depth, entries: 0 },
        };
        self.try_admit(measurement)
    }

    /// Checks one prospective JSON container count without changing staged
    /// accounting.
    ///
    /// # Parameters
    ///
    /// * `kind` - Container dimension whose point limit is checked.
    /// * `prospective` - Number of direct children that would be present after
    ///   the next child is entered.
    ///
    /// # Returns
    ///
    /// `Ok(())` when the operation completes successfully.
    ///
    /// # Errors
    ///
    /// Returns a quantity conversion error when `prospective` cannot be
    /// represented by `Q`, or a point-limit error when the configured limit
    /// for `kind` rejects it. The first failure poisons the transaction.
    pub fn check_container_count(
        &mut self,
        kind: JsonContainerKind,
        prospective: usize,
    ) -> Result<(), MeasuredBudgetError<R, Q>> {
        let limit = match kind {
            JsonContainerKind::Sequence => self.target.limits().structure_limits().sequence_items_limit(),
            JsonContainerKind::Map => self.target.limits().structure_limits().map_entries_limit(),
        };
        if let Some(error) = &self.failure {
            return Err(error.clone());
        }
        let result = self.check_container_items(prospective, limit);
        if let Err(error) = &result {
            self.failure = Some(error.clone());
        }
        result
    }

    /// Publishes every successful staged admission to the target budget.
    ///
    /// Consumes this transaction. Dropping an uncommitted transaction has no
    /// effect on the target budget.
    ///
    /// # Returns
    ///
    /// `Ok(())` after publishing an active transaction.
    ///
    /// # Errors
    ///
    /// Returns the first retained admission error when the transaction is
    /// poisoned. No staged state is published.
    pub fn commit(self) -> Result<(), MeasuredBudgetError<R, Q>> {
        if let Some(error) = self.failure {
            return Err(error);
        }
        self.target.state = self.working;
        Ok(())
    }

    /// Returns staged node usage when the cumulative node limit is configured.
    ///
    /// # Returns
    ///
    /// Returns staged node usage when the cumulative node limit is configured.
    ///
    /// `None` indicates that the corresponding limit or budget dimension is
    /// unconfigured.
    #[must_use]
    #[inline]
    pub fn used_nodes(&self) -> Option<Q> {
        self.working
            .remaining_nodes()
            .zip(self.target.limits().max_nodes())
            .map(|(remaining, maximum)| maximum - remaining)
    }

    /// Returns staged remaining node capacity when the node limit is
    /// configured.
    ///
    /// # Returns
    ///
    /// Returns staged remaining node capacity when the node limit is
    /// configured.
    ///
    /// `None` indicates that the corresponding limit or budget dimension is
    /// unconfigured.
    #[must_use]
    #[inline(always)]
    pub const fn remaining_nodes(&self) -> Option<Q> {
        self.working.remaining_nodes()
    }

    /// Returns staged payload usage when the payload limit is configured.
    ///
    /// # Returns
    ///
    /// Returns staged payload usage when the payload limit is configured.
    ///
    /// `None` indicates that the corresponding limit or budget dimension is
    /// unconfigured.
    #[must_use]
    #[inline]
    pub fn used_payload_bytes(&self) -> Option<Q> {
        self.working
            .remaining_payload_bytes()
            .zip(self.target.limits().max_payload_bytes())
            .map(|(remaining, maximum)| maximum - remaining)
    }

    /// Returns staged remaining payload capacity when that limit is configured.
    ///
    /// # Returns
    ///
    /// Returns staged remaining payload capacity when that limit is configured.
    ///
    /// `None` indicates that the corresponding limit or budget dimension is
    /// unconfigured.
    #[must_use]
    #[inline(always)]
    pub const fn remaining_payload_bytes(&self) -> Option<Q> {
        self.working.remaining_payload_bytes()
    }

    /// Checks cumulative capacity for an event without changing working state.
    ///
    /// # Parameters
    ///
    /// * `prepared` - Converted event whose cumulative cost is checked.
    ///
    /// # Returns
    ///
    /// `Ok(())` when the operation completes successfully.
    ///
    /// # Errors
    ///
    /// Returns [`MeasuredBudgetError::Budget`] when the staged node or payload
    /// capacity cannot accommodate the event.
    fn check_cumulative(&self, prepared: PreparedJsonAdmission<Q>) -> Result<(), MeasuredBudgetError<R, Q>> {
        let (node, payload_bytes) = cumulative_cost(prepared);
        if node {
            self.check_nodes()?;
        }
        self.check_payload(payload_bytes)
    }

    /// Converts and checks one prospective container count without mutation.
    ///
    /// # Parameters
    ///
    /// * `amount` - Prospective number of direct container children.
    /// * `limit` - Optional point limit for that container dimension.
    ///
    /// # Returns
    ///
    /// `Ok(())` when the operation completes successfully.
    ///
    /// # Errors
    ///
    /// Returns [`MeasuredBudgetError::Quantity`] when `amount` cannot be
    /// represented by `Q`, or [`MeasuredBudgetError::Budget`] when it exceeds
    /// the configured point limit.
    fn check_container_items(
        &self,
        amount: usize,
        limit: Option<&crate::ResourceLimit<R, Q>>,
    ) -> Result<(), MeasuredBudgetError<R, Q>> {
        let Some(limit) = limit else {
            return Ok(());
        };
        let amount = Q::try_from_usize(amount)
            .map_err(|source| MeasuredBudgetError::quantity(limit.resource().clone(), source))?;
        limit.check(amount).map_err(MeasuredBudgetError::from)
    }

    /// Checks the configured node budget for one additional value node.
    ///
    /// # Returns
    ///
    /// `Ok(())` when the operation completes successfully.
    ///
    /// # Errors
    ///
    /// Returns [`MeasuredBudgetError::Budget`] when the configured node budget
    /// has no remaining unit.
    fn check_nodes(&self) -> Result<(), MeasuredBudgetError<R, Q>> {
        let Some(remaining) = self.working.remaining_nodes() else {
            return Ok(());
        };
        if Q::ONE <= remaining {
            return Ok(());
        }
        let Some(limit) = self.target.limits().structure_limits().nodes_limit() else {
            return Ok(());
        };
        Err(InsufficientBudgetError {
            resource: limit.resource().clone(),
            limit: limit.maximum(),
            remaining,
            requested: Q::ONE,
        }
        .into())
    }

    /// Checks the configured payload budget for one event without mutation.
    ///
    /// # Parameters
    ///
    /// * `payload_bytes` - Converted payload cost of the event.
    ///
    /// # Returns
    ///
    /// `Ok(())` when the operation completes successfully.
    ///
    /// # Errors
    ///
    /// Returns [`MeasuredBudgetError::Budget`] when the configured payload
    /// budget has insufficient remaining capacity.
    fn check_payload(&self, payload_bytes: Q) -> Result<(), MeasuredBudgetError<R, Q>> {
        let Some(remaining) = self.working.remaining_payload_bytes() else {
            return Ok(());
        };
        if payload_bytes <= remaining {
            return Ok(());
        }
        let Some(limit) = self.target.limits().payload_bytes_limit() else {
            return Ok(());
        };
        Err(InsufficientBudgetError {
            resource: limit.resource().clone(),
            limit: limit.maximum(),
            remaining,
            requested: payload_bytes,
        }
        .into())
    }

    /// Applies a previously checked event to the fixed-size working state.
    ///
    /// # Parameters
    ///
    /// * `prepared` - Previously validated event to apply to working state.
    fn apply(&mut self, prepared: PreparedJsonAdmission<Q>) {
        let (node, payload_bytes) = cumulative_cost(prepared);
        self.working.apply(node, payload_bytes);
    }
}

/// Returns the cumulative node and payload cost of a prepared JSON event.
///
/// # Type Parameters
///
/// * `Q` - Exact unsigned quantity used for measurements and accounting.
///
/// # Parameters
///
/// * `prepared` - Converted event whose node and payload costs are extracted.
///
/// # Returns
///
/// Returns the cumulative node and payload cost of a prepared JSON event.
fn cumulative_cost<Q>(prepared: PreparedJsonAdmission<Q>) -> (bool, Q)
where
    Q: ResourceQuantity,
{
    match prepared {
        PreparedJsonAdmission::Null { .. }
        | PreparedJsonAdmission::Boolean { .. }
        | PreparedJsonAdmission::Array { .. }
        | PreparedJsonAdmission::Object { .. } => (true, Q::ZERO),
        PreparedJsonAdmission::String { bytes, .. } | PreparedJsonAdmission::Number { bytes, .. } => (true, bytes),
        PreparedJsonAdmission::Key { bytes } => (false, bytes),
    }
}