1#![forbid(unsafe_code)]
27#![warn(missing_docs)]
28
29use std::error::Error as StdError;
30use std::fmt;
31use std::sync::Arc;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub enum TraceStatus {
36 Passed,
38 Blocked,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Hash)]
44pub struct TraceEntry {
45 stage: String,
46 status: TraceStatus,
47}
48
49impl TraceEntry {
50 fn new(stage: String, status: TraceStatus) -> Self {
51 Self { stage, status }
52 }
53
54 pub fn stage(&self) -> &str {
56 &self.stage
57 }
58
59 pub const fn status(&self) -> TraceStatus {
61 self.status
62 }
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
67pub enum StageOutcome<T, E> {
68 Pass(T),
70 Block {
72 value: T,
74 reason: E,
76 },
77}
78
79impl<T, E> StageOutcome<T, E> {
80 pub const fn pass(value: T) -> Self {
82 Self::Pass(value)
83 }
84
85 pub const fn block(value: T, reason: E) -> Self {
87 Self::Block { value, reason }
88 }
89
90 pub const fn is_pass(&self) -> bool {
92 matches!(self, Self::Pass(_))
93 }
94
95 pub fn into_value(self) -> T {
97 match self {
98 Self::Pass(value) | Self::Block { value, .. } => value,
99 }
100 }
101}
102
103type StageFn<T, E> = dyn Fn(T) -> StageOutcome<T, E> + Send + Sync + 'static;
104
105pub struct Stage<T, E> {
107 name: String,
108 operation: Arc<StageFn<T, E>>,
109}
110
111impl<T, E> Clone for Stage<T, E> {
112 fn clone(&self) -> Self {
113 Self {
114 name: self.name.clone(),
115 operation: Arc::clone(&self.operation),
116 }
117 }
118}
119
120impl<T, E> fmt::Debug for Stage<T, E> {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.debug_struct("Stage").field("name", &self.name).finish()
123 }
124}
125
126impl<T: 'static, E: 'static> Stage<T, E> {
127 pub fn new(
129 name: impl Into<String>,
130 operation: impl Fn(T) -> StageOutcome<T, E> + Send + Sync + 'static,
131 ) -> Result<Self, Error> {
132 let name = valid_name(name.into())?;
133 Ok(Self {
134 name,
135 operation: Arc::new(operation),
136 })
137 }
138
139 pub fn inspect(
143 name: impl Into<String>,
144 inspection: impl Fn(&T) -> Result<(), E> + Send + Sync + 'static,
145 ) -> Result<Self, Error> {
146 Self::new(name, move |value| match inspection(&value) {
147 Ok(()) => StageOutcome::Pass(value),
148 Err(reason) => StageOutcome::Block { value, reason },
149 })
150 }
151
152 pub fn transform(
154 name: impl Into<String>,
155 transformation: impl Fn(T) -> T + Send + Sync + 'static,
156 ) -> Result<Self, Error> {
157 Self::new(name, move |value| StageOutcome::Pass(transformation(value)))
158 }
159
160 pub fn name(&self) -> &str {
162 &self.name
163 }
164
165 pub fn apply(&self, value: T) -> StageOutcome<T, E> {
167 (self.operation)(value)
168 }
169}
170
171#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct Passed<T> {
174 value: T,
175 trace: Vec<TraceEntry>,
176}
177
178impl<T> Passed<T> {
179 pub const fn value(&self) -> &T {
181 &self.value
182 }
183
184 pub fn trace(&self) -> &[TraceEntry] {
186 &self.trace
187 }
188
189 pub fn into_value(self) -> T {
191 self.value
192 }
193}
194
195#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct Blocked<T, E> {
198 value: T,
199 reason: E,
200 trace: Vec<TraceEntry>,
201}
202
203impl<T, E> Blocked<T, E> {
204 pub const fn value(&self) -> &T {
206 &self.value
207 }
208
209 pub const fn reason(&self) -> &E {
211 &self.reason
212 }
213
214 pub fn trace(&self) -> &[TraceEntry] {
216 &self.trace
217 }
218
219 pub fn blocked_at(&self) -> &str {
221 self.trace
222 .last()
223 .expect("blocked results always contain one trace entry")
224 .stage()
225 }
226
227 pub fn into_parts(self) -> (T, E) {
229 (self.value, self.reason)
230 }
231}
232
233#[derive(Debug, Clone, PartialEq, Eq)]
235pub enum PassResult<T, E> {
236 Passed(Passed<T>),
238 Blocked(Blocked<T, E>),
240}
241
242impl<T, E> PassResult<T, E> {
243 pub const fn is_passed(&self) -> bool {
245 matches!(self, Self::Passed(_))
246 }
247
248 pub fn trace(&self) -> &[TraceEntry] {
250 match self {
251 Self::Passed(value) => value.trace(),
252 Self::Blocked(value) => value.trace(),
253 }
254 }
255
256 pub fn into_value(self) -> T {
258 match self {
259 Self::Passed(value) => value.into_value(),
260 Self::Blocked(value) => value.into_parts().0,
261 }
262 }
263}
264
265#[derive(Debug, Clone)]
267pub struct Passage<T, E> {
268 stages: Vec<Stage<T, E>>,
269}
270
271impl<T: 'static, E: 'static> Passage<T, E> {
272 pub const fn new() -> Self {
274 Self { stages: Vec::new() }
275 }
276
277 pub fn push(&mut self, stage: Stage<T, E>) -> Result<(), Error> {
279 if self
280 .stages
281 .iter()
282 .any(|existing| existing.name == stage.name)
283 {
284 return Err(Error::DuplicateStage(stage.name));
285 }
286 self.stages.push(stage);
287 Ok(())
288 }
289
290 pub fn with_stage(mut self, stage: Stage<T, E>) -> Result<Self, Error> {
292 self.push(stage)?;
293 Ok(self)
294 }
295
296 pub fn stages(&self) -> &[Stage<T, E>] {
298 &self.stages
299 }
300
301 pub fn run(&self, mut value: T) -> PassResult<T, E> {
303 let mut trace = Vec::with_capacity(self.stages.len());
304 for stage in &self.stages {
305 match stage.apply(value) {
306 StageOutcome::Pass(next) => {
307 trace.push(TraceEntry::new(stage.name.clone(), TraceStatus::Passed));
308 value = next;
309 }
310 StageOutcome::Block {
311 value: blocked,
312 reason,
313 } => {
314 trace.push(TraceEntry::new(stage.name.clone(), TraceStatus::Blocked));
315 return PassResult::Blocked(Blocked {
316 value: blocked,
317 reason,
318 trace,
319 });
320 }
321 }
322 }
323 PassResult::Passed(Passed { value, trace })
324 }
325
326 pub fn run_token(&self, token: PassToken<T>) -> PassResult<T, E> {
328 self.run(token.redeem())
329 }
330}
331
332impl<T: 'static, E: 'static> Default for Passage<T, E> {
333 fn default() -> Self {
334 Self::new()
335 }
336}
337
338#[derive(Debug, PartialEq, Eq, Hash)]
340pub struct PassToken<T> {
341 value: T,
342}
343
344impl<T> PassToken<T> {
345 pub const fn issue(value: T) -> Self {
347 Self { value }
348 }
349
350 pub fn redeem(self) -> T {
352 self.value
353 }
354
355 pub fn pass_to<U>(self, handoff: impl FnOnce(T) -> U) -> U {
357 handoff(self.value)
358 }
359}
360
361#[derive(Debug, Clone, PartialEq, Eq)]
363#[non_exhaustive]
364pub enum Error {
365 EmptyStageName,
367 DuplicateStage(String),
369}
370
371impl fmt::Display for Error {
372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373 match self {
374 Self::EmptyStageName => f.write_str("stage name cannot be empty"),
375 Self::DuplicateStage(name) => write!(f, "duplicate stage name: {name}"),
376 }
377 }
378}
379
380impl StdError for Error {}
381
382fn valid_name(name: String) -> Result<String, Error> {
383 if name.trim().is_empty() {
384 Err(Error::EmptyStageName)
385 } else {
386 Ok(name)
387 }
388}
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393 use std::sync::atomic::{AtomicUsize, Ordering};
394
395 #[test]
396 fn value_passes_and_transforms_in_order() {
397 let passage = Passage::new()
398 .with_stage(Stage::<String, &str>::transform("trim", |v| v.trim().to_owned()).unwrap())
399 .unwrap()
400 .with_stage(Stage::transform("uppercase", |v: String| v.to_uppercase()).unwrap())
401 .unwrap();
402 let result = passage.run(" pass ".to_owned());
403 assert!(result.is_passed());
404 assert_eq!(result.trace().len(), 2);
405 assert_eq!(result.into_value(), "PASS");
406 }
407
408 #[test]
409 fn block_preserves_value_reason_and_trace() {
410 let passage = Passage::new()
411 .with_stage(
412 Stage::inspect("positive", |value: &i32| {
413 if *value > 0 {
414 Ok(())
415 } else {
416 Err("not positive")
417 }
418 })
419 .unwrap(),
420 )
421 .unwrap();
422 let result = passage.run(-7);
423 let PassResult::Blocked(blocked) = result else {
424 panic!("expected block");
425 };
426 assert_eq!(*blocked.value(), -7);
427 assert_eq!(*blocked.reason(), "not positive");
428 assert_eq!(blocked.blocked_at(), "positive");
429 assert_eq!(blocked.trace()[0].status(), TraceStatus::Blocked);
430 }
431
432 #[test]
433 fn stages_after_block_are_not_called() {
434 let calls = Arc::new(AtomicUsize::new(0));
435 let later_calls = Arc::clone(&calls);
436 let passage = Passage::new()
437 .with_stage(
438 Stage::new("block", |value| {
439 StageOutcome::<i32, &str>::block(value, "stop")
440 })
441 .unwrap(),
442 )
443 .unwrap()
444 .with_stage(
445 Stage::transform("later", move |value| {
446 later_calls.fetch_add(1, Ordering::SeqCst);
447 value + 1
448 })
449 .unwrap(),
450 )
451 .unwrap();
452 assert!(!passage.run(1).is_passed());
453 assert_eq!(calls.load(Ordering::SeqCst), 0);
454 }
455
456 #[test]
457 fn empty_passage_is_identity() {
458 let passage = Passage::<Vec<u8>, ()>::new();
459 let result = passage.run(vec![1, 2, 3]);
460 assert!(result.is_passed());
461 assert!(result.trace().is_empty());
462 assert_eq!(result.into_value(), [1, 2, 3]);
463 }
464
465 #[test]
466 fn duplicate_and_empty_stage_names_are_rejected() {
467 assert!(matches!(
468 Stage::<i32, ()>::transform(" ", |value| value),
469 Err(Error::EmptyStageName)
470 ));
471 let mut passage = Passage::<i32, ()>::new();
472 passage
473 .push(Stage::transform("same", |value| value).unwrap())
474 .unwrap();
475 assert!(matches!(
476 passage.push(Stage::transform("same", |value| value).unwrap()),
477 Err(Error::DuplicateStage(_))
478 ));
479 }
480
481 #[test]
482 fn custom_stage_can_transform_before_blocking() {
483 let stage = Stage::new("cap", |value: String| {
484 let value = value.to_uppercase();
485 if value.len() <= 4 {
486 StageOutcome::Pass(value)
487 } else {
488 StageOutcome::Block {
489 value,
490 reason: "too long",
491 }
492 }
493 })
494 .unwrap();
495 let passage = Passage::new().with_stage(stage).unwrap();
496 let PassResult::Blocked(blocked) = passage.run("passes".to_owned()) else {
497 panic!("expected block");
498 };
499 assert_eq!(blocked.value(), "PASSES");
500 }
501
502 #[test]
503 fn passage_and_stages_are_cloneable_for_shared_rules() {
504 let passage = Passage::new()
505 .with_stage(
506 Stage::<i32, &str>::inspect("even", |value| {
507 if value % 2 == 0 { Ok(()) } else { Err("odd") }
508 })
509 .unwrap(),
510 )
511 .unwrap();
512 let cloned = passage.clone();
513 let handle = std::thread::spawn(move || cloned.run(4).is_passed());
514 assert!(handle.join().unwrap());
515 assert!(!passage.run(3).is_passed());
516 }
517
518 #[test]
519 fn pass_token_is_consumed_by_pipeline_or_handoff() {
520 let passage = Passage::<String, ()>::new();
521 let result = passage.run_token(PassToken::issue("once".to_owned()));
522 assert_eq!(result.into_value(), "once");
523 let length = PassToken::issue("handoff").pass_to(str::len);
524 assert_eq!(length, 7);
525 }
526}