Skip to main content

calandria_sim/script/
owner.rs

1//! Bounded exact request matching with non-consuming mismatch.
2
3use alloc::{collections::VecDeque, vec::Vec};
4
5use calandria::{Retained, RetainedBytes};
6
7use super::{Plan, ScriptBuildError, ScriptBuildFailure, ScriptFailure, ScriptLimits, ScriptStep};
8
9/// Count- and byte-bounded exact finite capability script.
10#[derive(Debug)]
11pub struct ExactScript<Q, R> {
12    limits: ScriptLimits,
13    retained: RetainedBytes,
14    steps: VecDeque<MeasuredStep<Q, R>>,
15}
16
17impl<Q: Retained, R: Retained> ExactScript<Q, R> {
18    /// Retains all supplied steps or returns them unchanged on rejection.
19    pub fn try_new(
20        limits: ScriptLimits,
21        steps: Vec<ScriptStep<Q, R>>,
22    ) -> Result<Self, ScriptBuildError<Q, R>> {
23        if steps.len() > limits.steps().get() {
24            let actual = steps.len();
25            return Err(ScriptBuildError::new(
26                steps,
27                ScriptBuildFailure::StepCapacity {
28                    limit: limits.steps(),
29                    actual,
30                },
31            ));
32        }
33        let outcomes = match count_outcomes(&steps) {
34            Ok(outcomes) => outcomes,
35            Err(failure) => return Err(ScriptBuildError::new(steps, failure)),
36        };
37        if outcomes > limits.outcomes().get() {
38            return Err(ScriptBuildError::new(
39                steps,
40                ScriptBuildFailure::OutcomeCapacity {
41                    limit: limits.outcomes(),
42                    actual: outcomes,
43                },
44            ));
45        }
46        let (retained, measurements) = match measure_steps(&steps) {
47            Ok(measured) => measured,
48            Err(failure) => return Err(ScriptBuildError::new(steps, failure)),
49        };
50        if retained > limits.retained_bytes() {
51            return Err(ScriptBuildError::new(
52                steps,
53                ScriptBuildFailure::RetainedByteCapacity {
54                    limit: limits.retained_bytes(),
55                    actual: retained,
56                },
57            ));
58        }
59        let measured = steps
60            .into_iter()
61            .zip(measurements)
62            .map(|(step, retained)| MeasuredStep { step, retained })
63            .collect();
64        Ok(Self {
65            limits,
66            retained,
67            steps: measured,
68        })
69    }
70
71    /// Returns configured hard ownership limits.
72    pub const fn limits(&self) -> ScriptLimits {
73        self.limits
74    }
75
76    /// Returns the remaining exact request count.
77    pub fn len(&self) -> usize {
78        self.steps.len()
79    }
80
81    /// Returns whether no scripted request remains.
82    pub fn is_empty(&self) -> bool {
83        self.steps.is_empty()
84    }
85
86    /// Returns variable bytes retained by remaining requests and responses.
87    pub const fn retained_bytes(&self) -> RetainedBytes {
88        self.retained
89    }
90
91    /// Borrows the next exact expected request without consuming it.
92    pub fn expected(&self) -> Option<&Q> {
93        self.steps.front().map(|measured| measured.step.expected())
94    }
95}
96
97impl<Q: Retained + PartialEq, R: Retained> ExactScript<Q, R> {
98    /// Consumes the next response only when the request matches exactly.
99    pub fn respond(&mut self, request: &Q) -> Result<Plan<R>, ScriptFailure> {
100        let Some(next) = self.steps.front() else {
101            return Err(ScriptFailure::Exhausted);
102        };
103        if next.step.expected() != request {
104            return Err(ScriptFailure::Mismatch);
105        }
106        let measured = self
107            .steps
108            .pop_front()
109            .unwrap_or_else(|| panic!("matched script step must remain present"));
110        self.retained = self
111            .retained
112            .checked_sub(measured.retained)
113            .unwrap_or_else(|| panic!("script retained-byte accounting must be exact"));
114        let (_, response) = measured.step.into_parts();
115        Ok(response)
116    }
117}
118
119#[derive(Debug)]
120struct MeasuredStep<Q, R> {
121    step: ScriptStep<Q, R>,
122    retained: RetainedBytes,
123}
124
125fn count_outcomes<Q, R>(steps: &[ScriptStep<Q, R>]) -> Result<usize, ScriptBuildFailure> {
126    let mut total = 0usize;
127    for step in steps {
128        let Some(next) = total.checked_add(step.response().len()) else {
129            return Err(ScriptBuildFailure::OutcomeCountOverflow);
130        };
131        total = next;
132    }
133    Ok(total)
134}
135
136fn measure_steps<Q: Retained, R: Retained>(
137    steps: &[ScriptStep<Q, R>],
138) -> Result<(RetainedBytes, Vec<RetainedBytes>), ScriptBuildFailure> {
139    let mut total = RetainedBytes::ZERO;
140    let mut measurements = Vec::with_capacity(steps.len());
141    for step in steps {
142        let Some(measured) = measure_step(step) else {
143            return Err(ScriptBuildFailure::RetainedByteOverflow);
144        };
145        let Some(next) = total.checked_add(measured) else {
146            return Err(ScriptBuildFailure::RetainedByteOverflow);
147        };
148        measurements.push(measured);
149        total = next;
150    }
151    Ok((total, measurements))
152}
153
154fn measure_step<Q: Retained, R: Retained>(step: &ScriptStep<Q, R>) -> Option<RetainedBytes> {
155    let mut total = step.expected().retained_bytes();
156    for outcome in step.response().outcomes() {
157        total = total.checked_add(outcome.outcome().retained_bytes())?;
158    }
159    Some(total)
160}