1use 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#[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 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 pub const fn max_total(self) -> usize {
52 self.max_total.get()
53 }
54
55 pub const fn max_per_material(self) -> usize {
57 self.max_per_material.get()
58 }
59
60 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
74pub enum AudienceReaction {
75 Positive,
77 Neutral,
79 Rejected,
81}
82
83#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct Performance {
86 number: usize,
87 material: String,
88}
89
90impl Performance {
91 pub const fn number(&self) -> usize {
93 self.number
94 }
95
96 pub fn material(&self) -> &str {
98 &self.material
99 }
100}
101
102#[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 pub const fn performance(&self) -> &Performance {
114 &self.performance
115 }
116
117 pub const fn reaction(&self) -> AudienceReaction {
119 self.reaction
120 }
121
122 pub fn stop_record(&self) -> Option<&StopRecord> {
124 self.stop_record.as_ref()
125 }
126
127 pub const fn caused_stop(&self) -> bool {
129 self.caused_stop
130 }
131}
132
133#[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 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 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 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 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 pub fn is_stopped(&self) -> bool {
256 self.stop.is_stopped()
257 }
258
259 pub fn stop_record(&self) -> Option<StopRecord> {
261 self.stop.record()
262 }
263
264 pub const fn total_performances(&self) -> usize {
266 self.total_performances
267 }
268
269 pub const fn consecutive_rejections(&self) -> usize {
271 self.consecutive_rejections
272 }
273
274 pub fn performances_of(&self, material: &str) -> usize {
276 self.material_counts.get(material).copied().unwrap_or(0)
277 }
278
279 pub const fn pending(&self) -> Option<&Performance> {
281 self.pending.as_ref()
282 }
283
284 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
313#[non_exhaustive]
314pub enum PolicyError {
315 ZeroTotal,
317 ZeroPerMaterial,
319 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#[derive(Clone, Debug, PartialEq, Eq)]
339#[non_exhaustive]
340pub enum QuaseluError {
341 EmptyMaterial,
343 AwaitingReaction,
345 NoPerformance,
347 Stopped(StopRecord),
349 StopRequest(RequestError),
351 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}