Skip to main content

quaselu_stop/
lib.rs

1//! A policy-driven state machine for stopping a comedy bit.
2//!
3//! The workflow requires one audience observation after each performance.
4//! Total performances, repeated material, consecutive rejection, and manual
5//! intervention can establish an immutable STOP.
6//!
7//! ```
8//! use quaselu_stop::{AudienceReaction, QuaseluStop, StopPolicy};
9//!
10//! let mut show = QuaseluStop::new(StopPolicy::new(5, 2, 2)?);
11//! show.start("静かなダジャレ")?;
12//! show.observe(AudienceReaction::Rejected)?;
13//! show.start("静かなダジャレ")?;
14//! let observation = show.observe(AudienceReaction::Rejected)?;
15//! assert!(observation.caused_stop());
16//! # Ok::<(), Box<dyn std::error::Error>>(())
17//! ```
18
19use std::collections::BTreeMap;
20use std::error::Error;
21use std::fmt::{self, Display, Formatter};
22use std::num::NonZeroUsize;
23
24pub use stop_cigarette::{CocoshigaStop, RequestError, StopOutcome, StopRecord, StopStatus};
25
26/// Boundaries that decide when performance must stop.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub struct StopPolicy {
29    max_total: NonZeroUsize,
30    max_per_material: NonZeroUsize,
31    max_consecutive_rejections: NonZeroUsize,
32}
33
34impl StopPolicy {
35    /// Creates a policy from three non-zero limits.
36    pub fn new(
37        max_total: usize,
38        max_per_material: usize,
39        max_consecutive_rejections: usize,
40    ) -> Result<Self, PolicyError> {
41        Ok(Self {
42            max_total: NonZeroUsize::new(max_total).ok_or(PolicyError::ZeroTotal)?,
43            max_per_material: NonZeroUsize::new(max_per_material)
44                .ok_or(PolicyError::ZeroPerMaterial)?,
45            max_consecutive_rejections: NonZeroUsize::new(max_consecutive_rejections)
46                .ok_or(PolicyError::ZeroConsecutiveRejections)?,
47        })
48    }
49
50    /// Maximum number of performances in the show.
51    pub const fn max_total(self) -> usize {
52        self.max_total.get()
53    }
54
55    /// Maximum allowed starts for one material identifier.
56    pub const fn max_per_material(self) -> usize {
57        self.max_per_material.get()
58    }
59
60    /// Number of consecutive rejected reactions that establishes STOP.
61    pub const fn max_consecutive_rejections(self) -> usize {
62        self.max_consecutive_rejections.get()
63    }
64}
65
66impl Default for StopPolicy {
67    fn default() -> Self {
68        Self::new(10, 2, 2).expect("default limits are non-zero")
69    }
70}
71
72/// Audience response recorded after a performance.
73#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
74pub enum AudienceReaction {
75    /// Positive response; resets the rejection streak.
76    Positive,
77    /// Inconclusive response; preserves the current rejection streak.
78    Neutral,
79    /// Negative boundary signal; increments the rejection streak.
80    Rejected,
81}
82
83/// One started performance awaiting an observation.
84#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct Performance {
86    number: usize,
87    material: String,
88}
89
90impl Performance {
91    /// One-based position in this show.
92    pub const fn number(&self) -> usize {
93        self.number
94    }
95
96    /// Application-provided material identifier.
97    pub fn material(&self) -> &str {
98        &self.material
99    }
100}
101
102/// Result of observing one performance.
103#[derive(Clone, Debug, PartialEq, Eq)]
104pub struct Observation {
105    performance: Performance,
106    reaction: AudienceReaction,
107    stop_record: Option<StopRecord>,
108    caused_stop: bool,
109}
110
111impl Observation {
112    /// Performance that received the reaction.
113    pub const fn performance(&self) -> &Performance {
114        &self.performance
115    }
116
117    /// Recorded audience reaction.
118    pub const fn reaction(&self) -> AudienceReaction {
119        self.reaction
120    }
121
122    /// STOP record when the show is now stopped.
123    pub fn stop_record(&self) -> Option<&StopRecord> {
124        self.stop_record.as_ref()
125    }
126
127    /// Whether this observation established the first STOP.
128    pub const fn caused_stop(&self) -> bool {
129        self.caused_stop
130    }
131}
132
133/// Stateful coordinator for performing, observing, and stopping.
134#[derive(Debug)]
135pub struct QuaseluStop {
136    policy: StopPolicy,
137    stop: CocoshigaStop,
138    total_performances: usize,
139    material_counts: BTreeMap<String, usize>,
140    consecutive_rejections: usize,
141    pending: Option<Performance>,
142}
143
144impl QuaseluStop {
145    /// Creates an open show with the supplied policy.
146    pub fn new(policy: StopPolicy) -> Self {
147        Self {
148            policy,
149            stop: CocoshigaStop::new(),
150            total_performances: 0,
151            material_counts: BTreeMap::new(),
152            consecutive_rejections: 0,
153            pending: None,
154        }
155    }
156
157    /// Starts one performance.
158    ///
159    /// A reaction must be observed before another performance can start.
160    /// Crossing the total or repetition boundary establishes STOP.
161    pub fn start(&mut self, material: impl Into<String>) -> Result<Performance, QuaseluError> {
162        self.ensure_running()?;
163        if self.pending.is_some() {
164            return Err(QuaseluError::AwaitingReaction);
165        }
166
167        let material = material.into();
168        if material.trim().is_empty() {
169            return Err(QuaseluError::EmptyMaterial);
170        }
171        if self.total_performances >= self.policy.max_total() {
172            let record = self.stop_by_policy("total performance budget exhausted")?;
173            return Err(QuaseluError::Stopped(record));
174        }
175
176        let material_count = self.material_counts.get(&material).copied().unwrap_or(0);
177        if material_count >= self.policy.max_per_material() {
178            let record =
179                self.stop_by_policy(format!("material repetition limit reached: {material}"))?;
180            return Err(QuaseluError::Stopped(record));
181        }
182
183        self.total_performances = self
184            .total_performances
185            .checked_add(1)
186            .ok_or(QuaseluError::CounterOverflow)?;
187        let next_material_count = material_count
188            .checked_add(1)
189            .ok_or(QuaseluError::CounterOverflow)?;
190        self.material_counts
191            .insert(material.clone(), next_material_count);
192
193        let performance = Performance {
194            number: self.total_performances,
195            material,
196        };
197        self.pending = Some(performance.clone());
198        Ok(performance)
199    }
200
201    /// Records the required reaction for the pending performance.
202    ///
203    /// Rejection has priority over the total budget when both boundaries are
204    /// reached by the same observation.
205    pub fn observe(&mut self, reaction: AudienceReaction) -> Result<Observation, QuaseluError> {
206        self.ensure_running()?;
207        let performance = self.pending.take().ok_or(QuaseluError::NoPerformance)?;
208
209        match reaction {
210            AudienceReaction::Positive => self.consecutive_rejections = 0,
211            AudienceReaction::Neutral => {}
212            AudienceReaction::Rejected => {
213                self.consecutive_rejections = self
214                    .consecutive_rejections
215                    .checked_add(1)
216                    .ok_or(QuaseluError::CounterOverflow)?;
217            }
218        }
219
220        let reason = if self.consecutive_rejections >= self.policy.max_consecutive_rejections() {
221            Some("consecutive audience rejection limit reached")
222        } else if self.total_performances >= self.policy.max_total() {
223            Some("total performance budget exhausted")
224        } else {
225            None
226        };
227
228        let (stop_record, caused_stop) = match reason {
229            Some(reason) => (Some(self.stop_by_policy(reason)?), true),
230            None => (None, false),
231        };
232        Ok(Observation {
233            performance,
234            reaction,
235            stop_record,
236            caused_stop,
237        })
238    }
239
240    /// Manually establishes STOP and discards any pending performance.
241    pub fn request_stop(
242        &mut self,
243        actor: impl Into<String>,
244        reason: impl Into<String>,
245    ) -> Result<StopOutcome, QuaseluError> {
246        let outcome = self
247            .stop
248            .request_stop(actor, reason)
249            .map_err(QuaseluError::StopRequest)?;
250        self.pending = None;
251        Ok(outcome)
252    }
253
254    /// Returns whether the show has stopped.
255    pub fn is_stopped(&self) -> bool {
256        self.stop.is_stopped()
257    }
258
259    /// Canonical first STOP record.
260    pub fn stop_record(&self) -> Option<StopRecord> {
261        self.stop.record()
262    }
263
264    /// Number of performances started.
265    pub const fn total_performances(&self) -> usize {
266        self.total_performances
267    }
268
269    /// Current consecutive rejection count.
270    pub const fn consecutive_rejections(&self) -> usize {
271        self.consecutive_rejections
272    }
273
274    /// Number of times one material identifier has started.
275    pub fn performances_of(&self, material: &str) -> usize {
276        self.material_counts.get(material).copied().unwrap_or(0)
277    }
278
279    /// Performance currently awaiting a reaction.
280    pub const fn pending(&self) -> Option<&Performance> {
281        self.pending.as_ref()
282    }
283
284    /// Active stop policy.
285    pub const fn policy(&self) -> StopPolicy {
286        self.policy
287    }
288
289    fn ensure_running(&self) -> Result<(), QuaseluError> {
290        match self.stop.record() {
291            Some(record) => Err(QuaseluError::Stopped(record)),
292            None => Ok(()),
293        }
294    }
295
296    fn stop_by_policy(&self, reason: impl Into<String>) -> Result<StopRecord, QuaseluError> {
297        let outcome = self
298            .stop
299            .request_stop("quaselu-policy", reason)
300            .map_err(QuaseluError::StopRequest)?;
301        Ok(outcome.record().clone())
302    }
303}
304
305impl Default for QuaseluStop {
306    fn default() -> Self {
307        Self::new(StopPolicy::default())
308    }
309}
310
311/// Invalid stop-policy configuration.
312#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
313#[non_exhaustive]
314pub enum PolicyError {
315    /// Total performance limit was zero.
316    ZeroTotal,
317    /// Per-material limit was zero.
318    ZeroPerMaterial,
319    /// Consecutive rejection limit was zero.
320    ZeroConsecutiveRejections,
321}
322
323impl Display for PolicyError {
324    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
325        f.write_str(match self {
326            Self::ZeroTotal => "total performance limit must be greater than zero",
327            Self::ZeroPerMaterial => "per-material limit must be greater than zero",
328            Self::ZeroConsecutiveRejections => {
329                "consecutive rejection limit must be greater than zero"
330            }
331        })
332    }
333}
334
335impl Error for PolicyError {}
336
337/// Runtime workflow failure.
338#[derive(Clone, Debug, PartialEq, Eq)]
339#[non_exhaustive]
340pub enum QuaseluError {
341    /// Material identifier was empty or whitespace-only.
342    EmptyMaterial,
343    /// Another performance is waiting for its reaction.
344    AwaitingReaction,
345    /// A reaction was supplied without a pending performance.
346    NoPerformance,
347    /// The show has stopped with this canonical record.
348    Stopped(StopRecord),
349    /// A manually supplied STOP request was invalid.
350    StopRequest(RequestError),
351    /// A checked performance counter overflowed.
352    CounterOverflow,
353}
354
355impl Display for QuaseluError {
356    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
357        match self {
358            Self::EmptyMaterial => f.write_str("material identifier cannot be empty"),
359            Self::AwaitingReaction => {
360                f.write_str("observe the pending performance before starting another")
361            }
362            Self::NoPerformance => f.write_str("there is no performance awaiting a reaction"),
363            Self::Stopped(record) => {
364                write!(f, "stopped by {}: {}", record.actor(), record.reason())
365            }
366            Self::StopRequest(error) => write!(f, "STOP request error: {error}"),
367            Self::CounterOverflow => f.write_str("performance counter overflowed"),
368        }
369    }
370}
371
372impl Error for QuaseluError {
373    fn source(&self) -> Option<&(dyn Error + 'static)> {
374        match self {
375            Self::StopRequest(error) => Some(error),
376            _ => None,
377        }
378    }
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384
385    #[test]
386    fn every_performance_requires_a_reaction() {
387        let mut show = QuaseluStop::default();
388        show.start("bit-a").unwrap();
389        assert_eq!(
390            show.start("bit-b").unwrap_err(),
391            QuaseluError::AwaitingReaction
392        );
393        show.observe(AudienceReaction::Positive).unwrap();
394        assert!(show.start("bit-b").is_ok());
395    }
396
397    #[test]
398    fn positive_reaction_resets_rejection_streak() {
399        let mut show = QuaseluStop::new(StopPolicy::new(10, 5, 2).unwrap());
400        show.start("a").unwrap();
401        show.observe(AudienceReaction::Rejected).unwrap();
402        show.start("b").unwrap();
403        show.observe(AudienceReaction::Positive).unwrap();
404        assert_eq!(show.consecutive_rejections(), 0);
405        assert!(!show.is_stopped());
406    }
407
408    #[test]
409    fn rejection_boundary_stops_the_show() {
410        let mut show = QuaseluStop::new(StopPolicy::new(10, 5, 2).unwrap());
411        show.start("a").unwrap();
412        assert!(
413            !show
414                .observe(AudienceReaction::Rejected)
415                .unwrap()
416                .caused_stop()
417        );
418        show.start("b").unwrap();
419        let observation = show.observe(AudienceReaction::Rejected).unwrap();
420        assert!(observation.caused_stop());
421        assert!(show.is_stopped());
422        assert_eq!(observation.stop_record().unwrap().actor(), "quaselu-policy");
423    }
424
425    #[test]
426    fn total_budget_stops_after_last_allowed_performance() {
427        let mut show = QuaseluStop::new(StopPolicy::new(1, 2, 2).unwrap());
428        show.start("a").unwrap();
429        let observation = show.observe(AudienceReaction::Positive).unwrap();
430        assert!(observation.caused_stop());
431        assert!(show.is_stopped());
432    }
433
434    #[test]
435    fn repeating_material_beyond_limit_stops() {
436        let mut show = QuaseluStop::new(StopPolicy::new(10, 1, 3).unwrap());
437        show.start("a").unwrap();
438        show.observe(AudienceReaction::Positive).unwrap();
439        let error = show.start("a").unwrap_err();
440        assert!(matches!(error, QuaseluError::Stopped(_)));
441        assert!(show.is_stopped());
442    }
443
444    #[test]
445    fn manual_stop_keeps_first_reason() {
446        let mut show = QuaseluStop::default();
447        let first = show.request_stop("operator", "enough").unwrap();
448        let second = show.request_stop("other", "later").unwrap();
449        assert_eq!(first.status(), StopStatus::StoppedNow);
450        assert_eq!(second.status(), StopStatus::AlreadyStopped);
451        assert_eq!(show.stop_record().unwrap().actor(), "operator");
452    }
453
454    #[test]
455    fn invalid_material_does_not_increment_counters() {
456        let mut show = QuaseluStop::default();
457        assert_eq!(show.start(" ").unwrap_err(), QuaseluError::EmptyMaterial);
458        assert_eq!(show.total_performances(), 0);
459        assert!(show.pending().is_none());
460    }
461}