Skip to main content

karma_cigarette_stopping/
lib.rs

1//! Freeze-on-STOP karma settlement.
2//!
3//! This crate composes `karma-cigarette` and `stop-cigarette` into a
4//! one-way workflow:
5//!
6//! ```text
7//! collecting entries -> STOP freezes boundary -> final settlement
8//! ```
9//!
10//! ```
11//! use karma_cigarette_stopping::StoppingLedger;
12//!
13//! let mut session = StoppingLedger::new();
14//! session.record("aya", "ben", 8, "helped")?;
15//! session.record("ben", "aya", 3, "returned help")?;
16//! session.request_stop("operator", "period closed")?;
17//!
18//! let final_settlement = session.finalize()?;
19//! assert_eq!(final_settlement.plan().total_units(), 5);
20//! assert_eq!(final_settlement.stop_record().actor(), "operator");
21//! # Ok::<(), karma_cigarette_stopping::StoppingError>(())
22//! ```
23
24use std::collections::BTreeMap;
25use std::error::Error;
26use std::fmt::{self, Display, Formatter};
27
28pub use karma_cigarette::{
29    Cocoshiga, KarmaEntry, KarmaError, KarmaLedger, PartyId, SettlementPlan, SettlementTransfer,
30};
31pub use stop_cigarette::{
32    CocoshigaStop, RequestError, StopOutcome, StopRecord, StopStatus, Stopped,
33};
34
35/// A karma ledger with an irreversible STOP boundary.
36///
37/// Mutation requires exclusive access. Once `request_stop` accepts a valid
38/// request, no new entry can be recorded and the session can be finalized.
39#[derive(Clone, Debug, Default)]
40pub struct StoppingLedger {
41    ledger: KarmaLedger,
42    stop: CocoshigaStop,
43}
44
45impl StoppingLedger {
46    /// Creates an empty, open session.
47    pub fn new() -> Self {
48        Self::default()
49    }
50
51    /// Creates an open session from an existing ledger.
52    pub fn from_ledger(ledger: KarmaLedger) -> Self {
53        Self {
54            ledger,
55            stop: CocoshigaStop::new(),
56        }
57    }
58
59    /// Records karma while the session is open.
60    ///
61    /// Once STOP has been established, this returns
62    /// [`StoppingError::AlreadyStopped`] without mutating the ledger.
63    pub fn record(
64        &mut self,
65        giver: impl Into<String>,
66        receiver: impl Into<String>,
67        units: u64,
68        memo: impl Into<String>,
69    ) -> Result<&KarmaEntry, StoppingError> {
70        self.ensure_open()?;
71        self.ledger
72            .record(giver, receiver, units, memo)
73            .map_err(StoppingError::Karma)
74    }
75
76    /// Establishes the immutable STOP boundary.
77    ///
78    /// Repeated valid calls are idempotent and return the canonical first STOP
79    /// record through [`StopOutcome`].
80    pub fn request_stop(
81        &mut self,
82        actor: impl Into<String>,
83        reason: impl Into<String>,
84    ) -> Result<StopOutcome, StoppingError> {
85        self.stop
86            .request_stop(actor, reason)
87            .map_err(StoppingError::Request)
88    }
89
90    /// Returns whether a valid STOP has frozen the session.
91    pub fn is_stopped(&self) -> bool {
92        self.stop.is_stopped()
93    }
94
95    /// Returns a snapshot of the canonical STOP record.
96    pub fn stop_record(&self) -> Option<StopRecord> {
97        self.stop.record()
98    }
99
100    /// Returns the frozen-or-open ledger for inspection.
101    pub fn ledger(&self) -> &KarmaLedger {
102        &self.ledger
103    }
104
105    /// Computes current net positions without changing session state.
106    pub fn balances(&self) -> Result<BTreeMap<PartyId, i128>, StoppingError> {
107        self.ledger.balances().map_err(StoppingError::Karma)
108    }
109
110    /// Consumes a stopped session and produces its auditable final settlement.
111    ///
112    /// Calling this before STOP returns [`StoppingError::NotStopped`].
113    pub fn finalize(self) -> Result<FinalSettlement, StoppingError> {
114        let stop_record = self.stop.record().ok_or(StoppingError::NotStopped)?;
115        let accepted_entries = self.ledger.len();
116        let plan = Cocoshiga::settle(&self.ledger).map_err(StoppingError::Karma)?;
117        Ok(FinalSettlement {
118            stop_record,
119            plan,
120            accepted_entries,
121        })
122    }
123
124    /// Establishes STOP and immediately finalizes the frozen ledger.
125    pub fn stop_and_finalize(
126        mut self,
127        actor: impl Into<String>,
128        reason: impl Into<String>,
129    ) -> Result<FinalSettlement, StoppingError> {
130        self.request_stop(actor, reason)?;
131        self.finalize()
132    }
133
134    fn ensure_open(&self) -> Result<(), StoppingError> {
135        match self.stop.record() {
136            Some(record) => Err(StoppingError::AlreadyStopped(record)),
137            None => Ok(()),
138        }
139    }
140}
141
142/// Final, auditable output of the stopping workflow.
143#[derive(Clone, Debug, PartialEq, Eq)]
144pub struct FinalSettlement {
145    stop_record: StopRecord,
146    plan: SettlementPlan,
147    accepted_entries: usize,
148}
149
150impl FinalSettlement {
151    /// The immutable STOP that defined the settlement boundary.
152    pub fn stop_record(&self) -> &StopRecord {
153        &self.stop_record
154    }
155
156    /// Settlement of exactly the entries accepted before STOP.
157    pub fn plan(&self) -> &SettlementPlan {
158        &self.plan
159    }
160
161    /// Number of ledger entries included in the final settlement.
162    pub fn accepted_entries(&self) -> usize {
163        self.accepted_entries
164    }
165
166    /// Separates the final value into its STOP record and settlement plan.
167    pub fn into_parts(self) -> (StopRecord, SettlementPlan) {
168        (self.stop_record, self.plan)
169    }
170}
171
172/// Failure returned by the stopping workflow.
173#[derive(Clone, Debug, PartialEq, Eq)]
174#[non_exhaustive]
175pub enum StoppingError {
176    /// The underlying karma ledger rejected an entry or settlement.
177    Karma(KarmaError),
178    /// The STOP request had an invalid actor or reason.
179    Request(RequestError),
180    /// An entry was attempted after this canonical STOP.
181    AlreadyStopped(StopRecord),
182    /// Finalization was attempted before STOP.
183    NotStopped,
184}
185
186impl Display for StoppingError {
187    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
188        match self {
189            Self::Karma(error) => write!(f, "karma error: {error}"),
190            Self::Request(error) => write!(f, "STOP request error: {error}"),
191            Self::AlreadyStopped(record) => {
192                write!(
193                    f,
194                    "already stopped by {}: {}",
195                    record.actor(),
196                    record.reason()
197                )
198            }
199            Self::NotStopped => f.write_str("cannot finalize before STOP"),
200        }
201    }
202}
203
204impl Error for StoppingError {
205    fn source(&self) -> Option<&(dyn Error + 'static)> {
206        match self {
207            Self::Karma(error) => Some(error),
208            Self::Request(error) => Some(error),
209            Self::AlreadyStopped(_) | Self::NotStopped => None,
210        }
211    }
212}
213
214impl From<KarmaError> for StoppingError {
215    fn from(value: KarmaError) -> Self {
216        Self::Karma(value)
217    }
218}
219
220impl From<RequestError> for StoppingError {
221    fn from(value: RequestError) -> Self {
222        Self::Request(value)
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn stop_freezes_then_finalizes_exact_entries() {
232        let mut session = StoppingLedger::new();
233        session.record("alice", "bob", 10, "lunch").unwrap();
234        session.record("bob", "alice", 4, "coffee").unwrap();
235        session.request_stop("operator", "day closed").unwrap();
236
237        let error = session
238            .record("carol", "alice", 99, "too late")
239            .unwrap_err();
240        assert!(matches!(error, StoppingError::AlreadyStopped(_)));
241        assert_eq!(session.ledger().len(), 2);
242
243        let final_settlement = session.finalize().unwrap();
244        assert_eq!(final_settlement.accepted_entries(), 2);
245        assert_eq!(final_settlement.plan().total_units(), 6);
246        assert!(final_settlement.plan().is_conserved());
247    }
248
249    #[test]
250    fn finalize_before_stop_is_rejected() {
251        let mut session = StoppingLedger::new();
252        session.record("alice", "bob", 1, "").unwrap();
253        assert_eq!(session.finalize().unwrap_err(), StoppingError::NotStopped);
254    }
255
256    #[test]
257    fn invalid_stop_does_not_freeze() {
258        let mut session = StoppingLedger::new();
259        assert_eq!(
260            session.request_stop("", "reason").unwrap_err(),
261            StoppingError::Request(RequestError::EmptyActor)
262        );
263        assert!(!session.is_stopped());
264        assert!(session.record("alice", "bob", 1, "").is_ok());
265    }
266
267    #[test]
268    fn repeated_stop_preserves_first_provenance() {
269        let mut session = StoppingLedger::new();
270        let first = session.request_stop("alice", "first").unwrap();
271        let second = session.request_stop("bob", "second").unwrap();
272
273        assert_eq!(first.status(), StopStatus::StoppedNow);
274        assert_eq!(second.status(), StopStatus::AlreadyStopped);
275        assert_eq!(second.record().actor(), "alice");
276        assert_eq!(second.record().reason(), "first");
277    }
278
279    #[test]
280    fn invalid_karma_never_enters_the_ledger() {
281        let mut session = StoppingLedger::new();
282        assert_eq!(
283            session.record("alice", "alice", 1, "").unwrap_err(),
284            StoppingError::Karma(KarmaError::SameParty)
285        );
286        assert!(session.ledger().is_empty());
287    }
288
289    #[test]
290    fn stop_and_finalize_is_a_safe_shortcut() {
291        let mut session = StoppingLedger::new();
292        session.record("alice", "bob", 12, "").unwrap();
293        let result = session
294            .stop_and_finalize("operator", "batch complete")
295            .unwrap();
296
297        assert_eq!(result.stop_record().actor(), "operator");
298        assert_eq!(result.plan().total_units(), 12);
299        assert_eq!(result.accepted_entries(), 1);
300    }
301}