karma_cigarette_stopping/
lib.rs1use 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#[derive(Clone, Debug, Default)]
40pub struct StoppingLedger {
41 ledger: KarmaLedger,
42 stop: CocoshigaStop,
43}
44
45impl StoppingLedger {
46 pub fn new() -> Self {
48 Self::default()
49 }
50
51 pub fn from_ledger(ledger: KarmaLedger) -> Self {
53 Self {
54 ledger,
55 stop: CocoshigaStop::new(),
56 }
57 }
58
59 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 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 pub fn is_stopped(&self) -> bool {
92 self.stop.is_stopped()
93 }
94
95 pub fn stop_record(&self) -> Option<StopRecord> {
97 self.stop.record()
98 }
99
100 pub fn ledger(&self) -> &KarmaLedger {
102 &self.ledger
103 }
104
105 pub fn balances(&self) -> Result<BTreeMap<PartyId, i128>, StoppingError> {
107 self.ledger.balances().map_err(StoppingError::Karma)
108 }
109
110 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 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#[derive(Clone, Debug, PartialEq, Eq)]
144pub struct FinalSettlement {
145 stop_record: StopRecord,
146 plan: SettlementPlan,
147 accepted_entries: usize,
148}
149
150impl FinalSettlement {
151 pub fn stop_record(&self) -> &StopRecord {
153 &self.stop_record
154 }
155
156 pub fn plan(&self) -> &SettlementPlan {
158 &self.plan
159 }
160
161 pub fn accepted_entries(&self) -> usize {
163 self.accepted_entries
164 }
165
166 pub fn into_parts(self) -> (StopRecord, SettlementPlan) {
168 (self.stop_record, self.plan)
169 }
170}
171
172#[derive(Clone, Debug, PartialEq, Eq)]
174#[non_exhaustive]
175pub enum StoppingError {
176 Karma(KarmaError),
178 Request(RequestError),
180 AlreadyStopped(StopRecord),
182 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}