1use std::collections::BTreeSet;
2use std::error::Error;
3use std::fmt;
4
5use oxide_batch_core::{
6 ComponentRevision, DefinitionError, DefinitionTokenKind, MAX_REPEAT_INTERCEPTORS,
7 MAX_REPEAT_NESTING_DEPTH, RepeatId, StateSchemaId, StateSchemaVersion, definition_token,
8 validate_token,
9};
10use serde_json::{Value, json};
11
12definition_token!(
13 RepeatPolicyKind,
14 DefinitionTokenKind::RepeatPolicy,
15 "A stable application-owned kind identifier for one repeat policy."
16);
17definition_token!(
18 RepeatPolicyConfiguration,
19 DefinitionTokenKind::RepeatPolicy,
20 "A bounded restart-relevant configuration fingerprint for one repeat policy."
21);
22definition_token!(
23 RepeatInterceptorId,
24 DefinitionTokenKind::RepeatInterceptor,
25 "A stable logical identifier for one repeat interceptor registration."
26);
27definition_token!(
28 RepeatInterceptorKind,
29 DefinitionTokenKind::RepeatInterceptor,
30 "A stable application-owned kind identifier for one repeat interceptor."
31);
32
33#[derive(Clone, Debug, Eq, PartialEq)]
35pub struct RepeatPolicyDefinition {
36 kind: RepeatPolicyKind,
37 revision: ComponentRevision,
38 configuration: RepeatPolicyConfiguration,
39}
40
41impl RepeatPolicyDefinition {
42 #[must_use]
44 pub const fn new(
45 kind: RepeatPolicyKind,
46 revision: ComponentRevision,
47 configuration: RepeatPolicyConfiguration,
48 ) -> Self {
49 Self {
50 kind,
51 revision,
52 configuration,
53 }
54 }
55
56 #[must_use]
58 pub const fn kind(&self) -> &RepeatPolicyKind {
59 &self.kind
60 }
61
62 #[must_use]
64 pub const fn revision(&self) -> &ComponentRevision {
65 &self.revision
66 }
67
68 #[must_use]
70 pub const fn configuration(&self) -> &RepeatPolicyConfiguration {
71 &self.configuration
72 }
73
74 fn manifest_value(&self) -> Value {
75 json!({
76 "configuration": self.configuration.as_str(),
77 "kind": self.kind.as_str(),
78 "revision": self.revision.as_str()
79 })
80 }
81}
82
83#[derive(Clone, Debug, Eq, PartialEq)]
85pub struct RepeatInterceptorDefinition {
86 id: RepeatInterceptorId,
87 kind: RepeatInterceptorKind,
88 revision: ComponentRevision,
89}
90
91impl RepeatInterceptorDefinition {
92 #[must_use]
94 pub const fn new(
95 id: RepeatInterceptorId,
96 kind: RepeatInterceptorKind,
97 revision: ComponentRevision,
98 ) -> Self {
99 Self { id, kind, revision }
100 }
101
102 #[must_use]
104 pub const fn id(&self) -> &RepeatInterceptorId {
105 &self.id
106 }
107
108 #[must_use]
110 pub const fn kind(&self) -> &RepeatInterceptorKind {
111 &self.kind
112 }
113
114 #[must_use]
116 pub const fn revision(&self) -> &ComponentRevision {
117 &self.revision
118 }
119
120 fn manifest_value(&self) -> Value {
121 json!({
122 "id": self.id.as_str(),
123 "kind": self.kind.as_str(),
124 "revision": self.revision.as_str()
125 })
126 }
127}
128
129#[derive(Clone, Debug, Eq, PartialEq)]
131pub struct RepeatStateSchema {
132 schema: StateSchemaId,
133 version: StateSchemaVersion,
134}
135
136impl RepeatStateSchema {
137 #[must_use]
139 pub const fn new(schema: StateSchemaId, version: StateSchemaVersion) -> Self {
140 Self { schema, version }
141 }
142
143 #[must_use]
145 pub const fn schema(&self) -> &StateSchemaId {
146 &self.schema
147 }
148
149 #[must_use]
151 pub const fn version(&self) -> StateSchemaVersion {
152 self.version
153 }
154
155 fn manifest_value(&self) -> Value {
156 json!({
157 "schema": self.schema.as_str(),
158 "version": self.version.get()
159 })
160 }
161}
162
163#[derive(Clone, Debug, Eq, PartialEq)]
169pub struct RepeatDefinition {
170 id: RepeatId,
171 policy: RepeatPolicyDefinition,
172 interceptors: Vec<RepeatInterceptorDefinition>,
173 state: RepeatStateSchema,
174 nested: Option<Box<RepeatDefinition>>,
175 depth: usize,
176}
177
178impl RepeatDefinition {
179 pub fn new(
185 id: RepeatId,
186 policy: RepeatPolicyDefinition,
187 interceptors: Vec<RepeatInterceptorDefinition>,
188 state: RepeatStateSchema,
189 ) -> Result<Self, RepeatDefinitionError> {
190 if interceptors.len() > MAX_REPEAT_INTERCEPTORS {
191 return Err(RepeatDefinitionError::TooManyInterceptors {
192 max: MAX_REPEAT_INTERCEPTORS,
193 });
194 }
195 let mut ids = BTreeSet::new();
196 for interceptor in &interceptors {
197 if !ids.insert(interceptor.id.clone()) {
198 return Err(RepeatDefinitionError::DuplicateInterceptorId {
199 interceptor: interceptor.id.clone(),
200 });
201 }
202 }
203 Ok(Self {
204 id,
205 policy,
206 interceptors,
207 state,
208 nested: None,
209 depth: 1,
210 })
211 }
212
213 pub fn with_nested(mut self, nested: RepeatDefinition) -> Result<Self, RepeatDefinitionError> {
220 if nested.contains_id(&self.id) {
221 return Err(RepeatDefinitionError::DuplicateRepeatId {
222 repeat: self.id.clone(),
223 });
224 }
225 let depth = nested.depth.saturating_add(1);
226 if depth > MAX_REPEAT_NESTING_DEPTH {
227 return Err(RepeatDefinitionError::NestingTooDeep {
228 max: MAX_REPEAT_NESTING_DEPTH,
229 });
230 }
231 self.nested = Some(Box::new(nested));
232 self.depth = depth;
233 Ok(self)
234 }
235
236 #[must_use]
238 pub const fn id(&self) -> &RepeatId {
239 &self.id
240 }
241
242 #[must_use]
244 pub const fn policy(&self) -> &RepeatPolicyDefinition {
245 &self.policy
246 }
247
248 #[must_use]
250 pub fn interceptors(&self) -> &[RepeatInterceptorDefinition] {
251 &self.interceptors
252 }
253
254 #[must_use]
256 pub const fn state_schema(&self) -> &RepeatStateSchema {
257 &self.state
258 }
259
260 #[must_use]
262 pub fn nested(&self) -> Option<&RepeatDefinition> {
263 self.nested.as_deref()
264 }
265
266 #[must_use]
268 pub const fn nesting_depth(&self) -> usize {
269 self.depth
270 }
271
272 pub(crate) fn register_ids(&self, ids: &mut BTreeSet<RepeatId>) -> Result<(), RepeatId> {
273 if !ids.insert(self.id.clone()) {
274 return Err(self.id.clone());
275 }
276 if let Some(nested) = &self.nested {
277 nested.register_ids(ids)?;
278 }
279 Ok(())
280 }
281
282 pub(crate) fn manifest_value(&self) -> Value {
283 let mut value = json!({
284 "id": self.id.as_str(),
285 "interceptors": self
286 .interceptors
287 .iter()
288 .map(RepeatInterceptorDefinition::manifest_value)
289 .collect::<Vec<_>>(),
290 "policy": self.policy.manifest_value(),
291 "state": self.state.manifest_value()
292 });
293 if let Some(nested) = &self.nested
294 && let Some(object) = value.as_object_mut()
295 {
296 object.insert("nested".to_owned(), nested.manifest_value());
297 }
298 value
299 }
300
301 fn contains_id(&self, id: &RepeatId) -> bool {
302 &self.id == id
303 || self
304 .nested
305 .as_deref()
306 .is_some_and(|nested| nested.contains_id(id))
307 }
308}
309
310#[derive(Clone, Debug, Eq, PartialEq)]
312#[non_exhaustive]
313pub enum RepeatDefinitionError {
314 TooManyInterceptors {
316 max: usize,
318 },
319 DuplicateInterceptorId {
321 interceptor: RepeatInterceptorId,
323 },
324 NestingTooDeep {
326 max: usize,
328 },
329 DuplicateRepeatId {
331 repeat: RepeatId,
333 },
334}
335
336impl fmt::Display for RepeatDefinitionError {
337 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
338 match self {
339 Self::TooManyInterceptors { max } => {
340 write!(formatter, "repeat definition exceeds {max} interceptors")
341 }
342 Self::DuplicateInterceptorId { interceptor } => write!(
343 formatter,
344 "repeat interceptor {} is declared more than once",
345 interceptor.as_str()
346 ),
347 Self::NestingTooDeep { max } => {
348 write!(formatter, "repeat nesting exceeds depth {max}")
349 }
350 Self::DuplicateRepeatId { repeat } => write!(
351 formatter,
352 "repeat {} is declared more than once in one nesting chain",
353 repeat.as_str()
354 ),
355 }
356 }
357}
358
359impl Error for RepeatDefinitionError {}
360
361#[cfg(test)]
362mod tests {
363 #![allow(clippy::expect_used)]
364
365 use super::*;
366
367 fn interceptor(id: &str) -> RepeatInterceptorDefinition {
368 RepeatInterceptorDefinition::new(
369 RepeatInterceptorId::new(id).expect("interceptor id"),
370 RepeatInterceptorKind::new("audit").expect("interceptor kind"),
371 ComponentRevision::new("v1").expect("revision"),
372 )
373 }
374
375 fn leaf(id: &str, count: usize) -> Result<RepeatDefinition, RepeatDefinitionError> {
376 RepeatDefinition::new(
377 RepeatId::new(id).expect("repeat id"),
378 RepeatPolicyDefinition::new(
379 RepeatPolicyKind::new("count").expect("policy kind"),
380 ComponentRevision::new("v1").expect("revision"),
381 RepeatPolicyConfiguration::new("limit-10").expect("configuration"),
382 ),
383 (0..count)
384 .map(|index| interceptor(&format!("i{index}")))
385 .collect(),
386 RepeatStateSchema::new(
387 StateSchemaId::new("repeat.state").expect("schema"),
388 StateSchemaVersion::new(1).expect("version"),
389 ),
390 )
391 }
392
393 #[test]
394 fn interceptor_bound_is_exact() {
395 assert!(leaf("accepted", MAX_REPEAT_INTERCEPTORS).is_ok());
396 assert!(matches!(
397 leaf("rejected", MAX_REPEAT_INTERCEPTORS + 1),
398 Err(RepeatDefinitionError::TooManyInterceptors { .. })
399 ));
400 }
401
402 #[test]
403 fn nesting_bound_is_exact() {
404 let mut current = leaf("r8", 0).expect("leaf");
405 for depth in (1..8).rev() {
406 current = leaf(&format!("r{depth}"), 0)
407 .expect("wrapper")
408 .with_nested(current)
409 .expect("depth <= 8");
410 }
411 assert_eq!(current.nesting_depth(), MAX_REPEAT_NESTING_DEPTH);
412 assert!(matches!(
413 leaf("r0", 0).expect("wrapper").with_nested(current),
414 Err(RepeatDefinitionError::NestingTooDeep { .. })
415 ));
416 }
417}