qubit_budget/json/encode/json_encode_attempt.rs
1// =============================================================================
2// Copyright (c) 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Provides transactional value accounting for one JSON encode attempt.
9
10use crate::json::JsonMeasurement;
11use crate::json::JsonValueTransaction;
12use crate::resource::MeasuredBudgetError;
13use crate::resource::ResourceBudget;
14use crate::resource::ResourceQuantity;
15
16/// I/O accounting and transactional value admission for one JSON encode.
17///
18/// Dropping an attempt rolls back JSON value accounting. Accepted output
19/// charges remain committed, including while unwinding from a panic.
20///
21/// # Type Parameters
22///
23/// * `R` - Caller-defined resource identity retained by limits and errors.
24/// * `Q` - Exact unsigned quantity used for measurements and accounting.
25///
26/// # Examples
27///
28/// ```
29/// use qubit_budget::json::JsonEncodeLimits;
30/// use qubit_budget::json::JsonEncodeSession;
31/// use qubit_budget::json::JsonMeasurement;
32///
33/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
34/// let limits = JsonEncodeLimits::builder().max_nodes(1_usize).build();
35/// let mut session = JsonEncodeSession::from_limits(limits);
36/// let mut attempt = session.begin_value();
37/// attempt.try_admit(JsonMeasurement::Null { depth: 1 }).expect("null should fit");
38/// attempt.commit()?;
39/// # Ok(()) }
40/// ```
41pub struct JsonEncodeAttempt<'a, R, Q>
42where
43 Q: ResourceQuantity,
44{
45 /// Budget charged for accepted output bytes.
46 output: Option<&'a mut ResourceBudget<R, Q>>,
47 /// Working JSON value accounting published only by [`Self::commit`].
48 value: JsonValueTransaction<'a, R, Q>,
49}
50
51impl<'a, R, Q> JsonEncodeAttempt<'a, R, Q>
52where
53 R: Clone,
54 Q: ResourceQuantity,
55{
56 /// Creates an attempt from the budgets split out of an encode session.
57 ///
58 /// # Parameters
59 ///
60 /// * `output` - Optional output budget charged for accepted bytes.
61 /// * `value` - Transaction holding the JSON value accounting staged by this
62 /// attempt.
63 ///
64 /// # Returns
65 ///
66 /// Returns the attempt that stages value accounting and charges output
67 /// bytes immediately.
68 #[inline]
69 #[must_use]
70 pub(crate) const fn new(
71 output: Option<&'a mut ResourceBudget<R, Q>>,
72 value: JsonValueTransaction<'a, R, Q>,
73 ) -> Self {
74 Self { output, value }
75 }
76
77 /// Checks whether output bytes fit without charging them.
78 ///
79 /// Returns a quantity-conversion or budget error without changing the
80 /// configured output budget. An absent output budget is ignored.
81 ///
82 /// # Parameters
83 ///
84 /// * `amount` - Number of output bytes to check without charging.
85 ///
86 /// # Returns
87 ///
88 /// `Ok(())` when the operation completes successfully.
89 ///
90 /// # Errors
91 ///
92 /// Returns [`MeasuredBudgetError`] when a native measurement cannot fit `Q`
93 /// or a configured limit rejects it.
94 #[inline]
95 pub fn check_output_bytes(&self, amount: usize) -> Result<(), MeasuredBudgetError<R, Q>> {
96 match self.output.as_deref() {
97 Some(budget) => budget.check_available_usize(amount),
98 None => Ok(()),
99 }
100 }
101
102 /// Charges accepted output bytes immediately when the budget is set.
103 ///
104 /// Returns a quantity-conversion or budget error without changing the
105 /// configured output budget on failure. An absent budget is ignored.
106 ///
107 /// # Parameters
108 ///
109 /// * `amount` - Number of accepted output bytes to charge immediately.
110 ///
111 /// # Returns
112 ///
113 /// `Ok(())` when the operation completes successfully.
114 ///
115 /// # Errors
116 ///
117 /// Returns [`MeasuredBudgetError`] when a native measurement cannot fit `Q`
118 /// or a configured limit rejects it.
119 #[inline]
120 pub fn try_consume_output_bytes(&mut self, amount: usize) -> Result<(), MeasuredBudgetError<R, Q>> {
121 match self.output.as_deref_mut() {
122 Some(budget) => budget.try_consume_usize(amount),
123 None => Ok(()),
124 }
125 }
126
127 /// Stages one JSON measurement for publication by [`Self::commit`].
128 ///
129 /// Returns the transaction's conversion or value-limit error. A failure
130 /// leaves this attempt's working value state and output charges unchanged,
131 /// and poisons later value admissions and commit. Output failures alone do
132 /// not poison the value transaction.
133 ///
134 /// # Parameters
135 ///
136 /// * `measurement` - Native JSON measurement to convert or admit.
137 ///
138 /// # Returns
139 ///
140 /// `Ok(())` when the operation completes successfully.
141 ///
142 /// # Errors
143 ///
144 /// Returns [`MeasuredBudgetError`] when a native measurement cannot fit `Q`
145 /// or a configured limit rejects it.
146 #[inline]
147 pub fn try_admit(&mut self, measurement: JsonMeasurement) -> Result<(), MeasuredBudgetError<R, Q>> {
148 self.value.try_admit(measurement)
149 }
150
151 /// Returns the output budget while the attempt exclusively owns it.
152 ///
153 /// # Returns
154 ///
155 /// The caller-owned output budget, still mutably borrowed by this attempt.
156 ///
157 /// `None` indicates that the corresponding limit or budget dimension is
158 /// unconfigured.
159 #[inline]
160 pub fn output_budget(&self) -> Option<&ResourceBudget<R, Q>> {
161 self.output.as_deref()
162 }
163
164 /// Splits this attempt into immediate output and staged value accounting.
165 ///
166 /// The output budget, when configured, records accepted bytes immediately.
167 /// The returned transaction keeps its value changes staged until this
168 /// attempt is committed. Dropping the attempt rolls back only that value
169 /// state.
170 ///
171 /// # Returns
172 ///
173 /// A mutable output budget when configured, followed by the staged value
174 /// transaction. Mutations through the first reference charge output
175 /// immediately; value changes remain staged until commit.
176 ///
177 /// A `None` output budget indicates that output-byte accounting is
178 /// unconfigured.
179 #[must_use = "the output budget and staged value transaction must be used"]
180 #[inline]
181 pub fn split_mut(&mut self) -> (Option<&mut ResourceBudget<R, Q>>, &mut JsonValueTransaction<'a, R, Q>) {
182 (self.output.as_deref_mut(), &mut self.value)
183 }
184
185 /// Returns staged node usage when the node limit is configured.
186 ///
187 /// # Returns
188 ///
189 /// The node count including successful admissions staged by this attempt.
190 ///
191 /// `None` indicates that the corresponding limit or budget dimension is
192 /// unconfigured.
193 #[inline]
194 pub fn used_nodes(&self) -> Option<Q> {
195 self.value.used_nodes()
196 }
197
198 /// Returns staged remaining node capacity when the node limit is set.
199 ///
200 /// # Returns
201 ///
202 /// The remaining node capacity after successful staged admissions.
203 ///
204 /// `None` indicates that the corresponding limit or budget dimension is
205 /// unconfigured.
206 #[inline]
207 pub const fn remaining_nodes(&self) -> Option<Q> {
208 self.value.remaining_nodes()
209 }
210
211 /// Returns staged payload usage when the payload limit is configured.
212 ///
213 /// # Returns
214 ///
215 /// The payload-byte count including successful admissions staged by this
216 /// attempt.
217 ///
218 /// `None` indicates that the corresponding limit or budget dimension is
219 /// unconfigured.
220 #[inline]
221 pub fn used_payload_bytes(&self) -> Option<Q> {
222 self.value.used_payload_bytes()
223 }
224
225 /// Returns staged remaining payload capacity when the payload limit is set.
226 ///
227 /// # Returns
228 ///
229 /// The remaining payload-byte capacity after successful staged admissions.
230 ///
231 /// `None` indicates that the corresponding limit or budget dimension is
232 /// unconfigured.
233 #[inline]
234 pub const fn remaining_payload_bytes(&self) -> Option<Q> {
235 self.value.remaining_payload_bytes()
236 }
237
238 /// Returns the mutable transaction that holds this attempt's value state.
239 ///
240 /// # Returns
241 ///
242 /// A mutable reference to the transaction whose staged state this attempt
243 /// will publish on commit.
244 #[must_use]
245 #[inline]
246 pub fn value_transaction_mut(&mut self) -> &mut JsonValueTransaction<'a, R, Q> {
247 &mut self.value
248 }
249
250 /// Publishes this attempt's staged value state without rolling back output.
251 ///
252 /// # Returns
253 ///
254 /// `Ok(())` after publishing the staged value state.
255 ///
256 /// # Errors
257 ///
258 /// Returns the first value-admission error when the attempt is poisoned.
259 pub fn commit(self) -> Result<(), MeasuredBudgetError<R, Q>> {
260 self.value.commit()
261 }
262}