io-pass 0.1.0

Owned pass-or-block pipelines with named stages, traces, and single-use pass tokens
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! The logic of passing values through named stages.
//!
//! `io-pass` keeps ownership explicit: every stage either passes a value onward
//! or blocks it while returning the value and a reason. A [`Passage`] records a
//! trace, stops at the first block, and never silently discards input.
//!
//! # Example
//!
//! ```
//! use io_pass::{PassResult, Passage, Stage};
//!
//! let mut passage = Passage::<String, &'static str>::new();
//! passage.push(Stage::inspect("not empty", |value: &String| {
//!     if value.is_empty() { Err("empty") } else { Ok(()) }
//! })?)?;
//! passage.push(Stage::transform("normalize", |value: String| value.trim().to_lowercase())?)?;
//!
//! let result = passage.run("  PASS  ".to_owned());
//! match result {
//!     PassResult::Passed(done) => assert_eq!(done.value(), "pass"),
//!     PassResult::Blocked(_) => unreachable!(),
//! }
//! # Ok::<(), io_pass::Error>(())
//! ```

#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::error::Error as StdError;
use std::fmt;
use std::sync::Arc;

/// Whether one pipeline stage passed or blocked a value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TraceStatus {
    /// The value continued to the next stage.
    Passed,
    /// The value stopped at this stage.
    Blocked,
}

/// One immutable entry in a passage trace.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TraceEntry {
    stage: String,
    status: TraceStatus,
}

impl TraceEntry {
    fn new(stage: String, status: TraceStatus) -> Self {
        Self { stage, status }
    }

    /// Returns the stage name.
    pub fn stage(&self) -> &str {
        &self.stage
    }

    /// Returns whether the stage passed or blocked.
    pub const fn status(&self) -> TraceStatus {
        self.status
    }
}

/// A stage's ownership-preserving decision.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StageOutcome<T, E> {
    /// Pass the value onward.
    Pass(T),
    /// Stop and return both value and reason.
    Block {
        /// Value at the point it was blocked.
        value: T,
        /// Application-defined block reason.
        reason: E,
    },
}

impl<T, E> StageOutcome<T, E> {
    /// Creates a passing outcome.
    pub const fn pass(value: T) -> Self {
        Self::Pass(value)
    }

    /// Creates a blocking outcome without discarding the value.
    pub const fn block(value: T, reason: E) -> Self {
        Self::Block { value, reason }
    }

    /// Returns whether this outcome passes.
    pub const fn is_pass(&self) -> bool {
        matches!(self, Self::Pass(_))
    }

    /// Consumes the outcome and returns its value regardless of decision.
    pub fn into_value(self) -> T {
        match self {
            Self::Pass(value) | Self::Block { value, .. } => value,
        }
    }
}

type StageFn<T, E> = dyn Fn(T) -> StageOutcome<T, E> + Send + Sync + 'static;

/// A named, cloneable, thread-safe pass-or-block stage.
pub struct Stage<T, E> {
    name: String,
    operation: Arc<StageFn<T, E>>,
}

impl<T, E> Clone for Stage<T, E> {
    fn clone(&self) -> Self {
        Self {
            name: self.name.clone(),
            operation: Arc::clone(&self.operation),
        }
    }
}

impl<T, E> fmt::Debug for Stage<T, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Stage").field("name", &self.name).finish()
    }
}

impl<T: 'static, E: 'static> Stage<T, E> {
    /// Creates a fully custom stage.
    pub fn new(
        name: impl Into<String>,
        operation: impl Fn(T) -> StageOutcome<T, E> + Send + Sync + 'static,
    ) -> Result<Self, Error> {
        let name = valid_name(name.into())?;
        Ok(Self {
            name,
            operation: Arc::new(operation),
        })
    }

    /// Creates a read-only gate from an inspection returning `Ok` or a reason.
    ///
    /// The value is returned unchanged in both branches.
    pub fn inspect(
        name: impl Into<String>,
        inspection: impl Fn(&T) -> Result<(), E> + Send + Sync + 'static,
    ) -> Result<Self, Error> {
        Self::new(name, move |value| match inspection(&value) {
            Ok(()) => StageOutcome::Pass(value),
            Err(reason) => StageOutcome::Block { value, reason },
        })
    }

    /// Creates an infallible same-type transformation stage.
    pub fn transform(
        name: impl Into<String>,
        transformation: impl Fn(T) -> T + Send + Sync + 'static,
    ) -> Result<Self, Error> {
        Self::new(name, move |value| StageOutcome::Pass(transformation(value)))
    }

    /// Returns the stage name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Applies only this stage.
    pub fn apply(&self, value: T) -> StageOutcome<T, E> {
        (self.operation)(value)
    }
}

/// A value that passed every stage.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Passed<T> {
    value: T,
    trace: Vec<TraceEntry>,
}

impl<T> Passed<T> {
    /// Borrows the final value.
    pub const fn value(&self) -> &T {
        &self.value
    }

    /// Returns the complete all-passed trace.
    pub fn trace(&self) -> &[TraceEntry] {
        &self.trace
    }

    /// Consumes the result and returns the final value.
    pub fn into_value(self) -> T {
        self.value
    }
}

/// A value stopped at one stage with an application-defined reason.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Blocked<T, E> {
    value: T,
    reason: E,
    trace: Vec<TraceEntry>,
}

impl<T, E> Blocked<T, E> {
    /// Borrows the value as it existed at the blocking stage.
    pub const fn value(&self) -> &T {
        &self.value
    }

    /// Borrows the reason.
    pub const fn reason(&self) -> &E {
        &self.reason
    }

    /// Returns passed stages followed by the blocking stage.
    pub fn trace(&self) -> &[TraceEntry] {
        &self.trace
    }

    /// Returns the blocking stage name.
    pub fn blocked_at(&self) -> &str {
        self.trace
            .last()
            .expect("blocked results always contain one trace entry")
            .stage()
    }

    /// Consumes the block and returns value and reason.
    pub fn into_parts(self) -> (T, E) {
        (self.value, self.reason)
    }
}

/// The final result of running a [`Passage`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PassResult<T, E> {
    /// Every stage passed.
    Passed(Passed<T>),
    /// One stage blocked and later stages were not called.
    Blocked(Blocked<T, E>),
}

impl<T, E> PassResult<T, E> {
    /// Returns whether all stages passed.
    pub const fn is_passed(&self) -> bool {
        matches!(self, Self::Passed(_))
    }

    /// Returns the trace for either result.
    pub fn trace(&self) -> &[TraceEntry] {
        match self {
            Self::Passed(value) => value.trace(),
            Self::Blocked(value) => value.trace(),
        }
    }

    /// Consumes the result and returns its value, preserving no hidden copy.
    pub fn into_value(self) -> T {
        match self {
            Self::Passed(value) => value.into_value(),
            Self::Blocked(value) => value.into_parts().0,
        }
    }
}

/// An ordered pipeline that stops at the first block.
#[derive(Debug, Clone)]
pub struct Passage<T, E> {
    stages: Vec<Stage<T, E>>,
}

impl<T: 'static, E: 'static> Passage<T, E> {
    /// Creates an empty identity passage.
    pub const fn new() -> Self {
        Self { stages: Vec::new() }
    }

    /// Adds a stage, rejecting duplicate names so traces remain unambiguous.
    pub fn push(&mut self, stage: Stage<T, E>) -> Result<(), Error> {
        if self
            .stages
            .iter()
            .any(|existing| existing.name == stage.name)
        {
            return Err(Error::DuplicateStage(stage.name));
        }
        self.stages.push(stage);
        Ok(())
    }

    /// Adds a stage and returns the updated passage for builder-style use.
    pub fn with_stage(mut self, stage: Stage<T, E>) -> Result<Self, Error> {
        self.push(stage)?;
        Ok(self)
    }

    /// Returns stages in execution order.
    pub fn stages(&self) -> &[Stage<T, E>] {
        &self.stages
    }

    /// Passes an owned value through stages until completion or first block.
    pub fn run(&self, mut value: T) -> PassResult<T, E> {
        let mut trace = Vec::with_capacity(self.stages.len());
        for stage in &self.stages {
            match stage.apply(value) {
                StageOutcome::Pass(next) => {
                    trace.push(TraceEntry::new(stage.name.clone(), TraceStatus::Passed));
                    value = next;
                }
                StageOutcome::Block {
                    value: blocked,
                    reason,
                } => {
                    trace.push(TraceEntry::new(stage.name.clone(), TraceStatus::Blocked));
                    return PassResult::Blocked(Blocked {
                        value: blocked,
                        reason,
                        trace,
                    });
                }
            }
        }
        PassResult::Passed(Passed { value, trace })
    }

    /// Redeems a single-use token into this passage.
    pub fn run_token(&self, token: PassToken<T>) -> PassResult<T, E> {
        self.run(token.redeem())
    }
}

impl<T: 'static, E: 'static> Default for Passage<T, E> {
    fn default() -> Self {
        Self::new()
    }
}

/// A value wrapper that can be redeemed only by consuming the token.
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct PassToken<T> {
    value: T,
}

impl<T> PassToken<T> {
    /// Issues a token holding one value.
    pub const fn issue(value: T) -> Self {
        Self { value }
    }

    /// Consumes the token and returns its value.
    pub fn redeem(self) -> T {
        self.value
    }

    /// Consumes the token through a one-time handoff function.
    pub fn pass_to<U>(self, handoff: impl FnOnce(T) -> U) -> U {
        handoff(self.value)
    }
}

/// Pipeline definition errors.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// A stage name contained only whitespace.
    EmptyStageName,
    /// The same stage name was inserted twice.
    DuplicateStage(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyStageName => f.write_str("stage name cannot be empty"),
            Self::DuplicateStage(name) => write!(f, "duplicate stage name: {name}"),
        }
    }
}

impl StdError for Error {}

fn valid_name(name: String) -> Result<String, Error> {
    if name.trim().is_empty() {
        Err(Error::EmptyStageName)
    } else {
        Ok(name)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[test]
    fn value_passes_and_transforms_in_order() {
        let passage = Passage::new()
            .with_stage(Stage::<String, &str>::transform("trim", |v| v.trim().to_owned()).unwrap())
            .unwrap()
            .with_stage(Stage::transform("uppercase", |v: String| v.to_uppercase()).unwrap())
            .unwrap();
        let result = passage.run("  pass  ".to_owned());
        assert!(result.is_passed());
        assert_eq!(result.trace().len(), 2);
        assert_eq!(result.into_value(), "PASS");
    }

    #[test]
    fn block_preserves_value_reason_and_trace() {
        let passage = Passage::new()
            .with_stage(
                Stage::inspect("positive", |value: &i32| {
                    if *value > 0 {
                        Ok(())
                    } else {
                        Err("not positive")
                    }
                })
                .unwrap(),
            )
            .unwrap();
        let result = passage.run(-7);
        let PassResult::Blocked(blocked) = result else {
            panic!("expected block");
        };
        assert_eq!(*blocked.value(), -7);
        assert_eq!(*blocked.reason(), "not positive");
        assert_eq!(blocked.blocked_at(), "positive");
        assert_eq!(blocked.trace()[0].status(), TraceStatus::Blocked);
    }

    #[test]
    fn stages_after_block_are_not_called() {
        let calls = Arc::new(AtomicUsize::new(0));
        let later_calls = Arc::clone(&calls);
        let passage = Passage::new()
            .with_stage(
                Stage::new("block", |value| {
                    StageOutcome::<i32, &str>::block(value, "stop")
                })
                .unwrap(),
            )
            .unwrap()
            .with_stage(
                Stage::transform("later", move |value| {
                    later_calls.fetch_add(1, Ordering::SeqCst);
                    value + 1
                })
                .unwrap(),
            )
            .unwrap();
        assert!(!passage.run(1).is_passed());
        assert_eq!(calls.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn empty_passage_is_identity() {
        let passage = Passage::<Vec<u8>, ()>::new();
        let result = passage.run(vec![1, 2, 3]);
        assert!(result.is_passed());
        assert!(result.trace().is_empty());
        assert_eq!(result.into_value(), [1, 2, 3]);
    }

    #[test]
    fn duplicate_and_empty_stage_names_are_rejected() {
        assert!(matches!(
            Stage::<i32, ()>::transform("  ", |value| value),
            Err(Error::EmptyStageName)
        ));
        let mut passage = Passage::<i32, ()>::new();
        passage
            .push(Stage::transform("same", |value| value).unwrap())
            .unwrap();
        assert!(matches!(
            passage.push(Stage::transform("same", |value| value).unwrap()),
            Err(Error::DuplicateStage(_))
        ));
    }

    #[test]
    fn custom_stage_can_transform_before_blocking() {
        let stage = Stage::new("cap", |value: String| {
            let value = value.to_uppercase();
            if value.len() <= 4 {
                StageOutcome::Pass(value)
            } else {
                StageOutcome::Block {
                    value,
                    reason: "too long",
                }
            }
        })
        .unwrap();
        let passage = Passage::new().with_stage(stage).unwrap();
        let PassResult::Blocked(blocked) = passage.run("passes".to_owned()) else {
            panic!("expected block");
        };
        assert_eq!(blocked.value(), "PASSES");
    }

    #[test]
    fn passage_and_stages_are_cloneable_for_shared_rules() {
        let passage = Passage::new()
            .with_stage(
                Stage::<i32, &str>::inspect("even", |value| {
                    if value % 2 == 0 { Ok(()) } else { Err("odd") }
                })
                .unwrap(),
            )
            .unwrap();
        let cloned = passage.clone();
        let handle = std::thread::spawn(move || cloned.run(4).is_passed());
        assert!(handle.join().unwrap());
        assert!(!passage.run(3).is_passed());
    }

    #[test]
    fn pass_token_is_consumed_by_pipeline_or_handoff() {
        let passage = Passage::<String, ()>::new();
        let result = passage.run_token(PassToken::issue("once".to_owned()));
        assert_eq!(result.into_value(), "once");
        let length = PassToken::issue("handoff").pass_to(str::len);
        assert_eq!(length, 7);
    }
}