use std::fmt;
use crate::dedup::{NotKeyable, RecordKey};
use crate::lateness::Lateness;
use crate::party::UnattributableReason;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SuppressReason {
TestIdentity,
ZeroRated,
InternalTraffic,
ZeroUsage,
OperatorPolicy,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RejectReason {
BeyondDeadline,
FutureTimestamp,
Unattributable(UnattributableReason),
NotKeyable(NotKeyable),
Malformed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum HoldReason {
AwaitingPartial,
AwaitingCorrelation,
AwaitingReferenceData,
SequenceGap,
}
macro_rules! coded_enum {
($ty:ty, $all:expr, $($variant:pat => $code:literal),+ $(,)?) => {
impl $ty {
pub const ALL: &'static [Self] = $all;
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
$($variant => $code,)+
}
}
}
impl fmt::Display for $ty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl std::str::FromStr for $ty {
type Err = crate::error::ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let t = s.trim().to_ascii_uppercase();
Self::ALL
.iter()
.find(|v| v.as_str() == t)
.copied()
.ok_or_else(|| {
crate::error::ParseError::format(
stringify!($ty),
s,
concat!("one of the ", stringify!($ty), " codes"),
)
})
}
}
};
}
coded_enum!(
SuppressReason,
&[
Self::TestIdentity,
Self::ZeroRated,
Self::InternalTraffic,
Self::ZeroUsage,
Self::OperatorPolicy,
],
Self::TestIdentity => "TEST_IDENTITY",
Self::ZeroRated => "ZERO_RATED",
Self::InternalTraffic => "INTERNAL_TRAFFIC",
Self::ZeroUsage => "ZERO_USAGE",
Self::OperatorPolicy => "OPERATOR_POLICY",
);
coded_enum!(
HoldReason,
&[
Self::AwaitingPartial,
Self::AwaitingCorrelation,
Self::AwaitingReferenceData,
Self::SequenceGap,
],
Self::AwaitingPartial => "AWAITING_PARTIAL",
Self::AwaitingCorrelation => "AWAITING_CORRELATION",
Self::AwaitingReferenceData => "AWAITING_REFERENCE_DATA",
Self::SequenceGap => "SEQUENCE_GAP",
);
impl RejectReason {
#[must_use]
pub const fn from_lateness(lateness: Lateness) -> Option<Self> {
match lateness {
Lateness::BeyondDeadline(_) => Some(Self::BeyondDeadline),
Lateness::Future(_) => Some(Self::FutureTimestamp),
Lateness::OnTime | Lateness::Late(_) => None,
}
}
#[must_use]
pub const fn kind(self) -> &'static str {
match self {
Self::BeyondDeadline => "BEYOND_DEADLINE",
Self::FutureTimestamp => "FUTURE_TIMESTAMP",
Self::Unattributable(_) => "UNATTRIBUTABLE",
Self::NotKeyable(_) => "NOT_KEYABLE",
Self::Malformed => "MALFORMED",
}
}
}
impl fmt::Display for RejectReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unattributable(reason) => write!(f, "UNATTRIBUTABLE:{reason}"),
Self::NotKeyable(reason) => write!(f, "NOT_KEYABLE:{reason}"),
other => f.write_str(other.kind()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Outcome {
Billable,
Suppressed,
Duplicate,
Rejected,
Held,
}
impl Outcome {
pub const ALL: &'static [Self] = &[
Self::Billable,
Self::Suppressed,
Self::Duplicate,
Self::Rejected,
Self::Held,
];
pub const CODES: &'static [&'static str] =
&["BILLABLE", "SUPPRESSED", "DUPLICATE", "REJECTED", "HELD"];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Billable => "BILLABLE",
Self::Suppressed => "SUPPRESSED",
Self::Duplicate => "DUPLICATE",
Self::Rejected => "REJECTED",
Self::Held => "HELD",
}
}
#[must_use]
pub const fn is_released(self) -> bool {
matches!(self, Self::Billable)
}
#[must_use]
pub const fn may_return(self) -> bool {
matches!(self, Self::Held)
}
}
impl fmt::Display for Outcome {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl std::str::FromStr for Outcome {
type Err = crate::error::ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::ALL
.iter()
.find(|o| o.as_str().eq_ignore_ascii_case(s.trim()))
.copied()
.ok_or_else(|| crate::error::ParseError::one_of("Outcome", s, Self::CODES))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Disposition {
Billable,
Suppressed(SuppressReason),
Duplicate(RecordKey),
Rejected(RejectReason),
Held(HoldReason),
}
impl Disposition {
#[must_use]
pub const fn is_released(&self) -> bool {
matches!(self, Self::Billable)
}
#[must_use]
pub const fn may_return(&self) -> bool {
matches!(self, Self::Held(_))
}
#[must_use]
pub const fn is_finding(&self) -> bool {
matches!(self, Self::Rejected(_) | Self::Held(_))
}
#[must_use]
pub const fn outcome(&self) -> Outcome {
match self {
Self::Billable => Outcome::Billable,
Self::Suppressed(_) => Outcome::Suppressed,
Self::Duplicate(_) => Outcome::Duplicate,
Self::Rejected(_) => Outcome::Rejected,
Self::Held(_) => Outcome::Held,
}
}
#[must_use]
pub const fn kind(&self) -> &'static str {
self.outcome().as_str()
}
}
impl fmt::Display for Disposition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Billable => f.write_str("BILLABLE"),
Self::Suppressed(reason) => write!(f, "SUPPRESSED:{reason}"),
Self::Duplicate(key) => write!(f, "DUPLICATE:{key}"),
Self::Rejected(reason) => write!(f, "REJECTED:{reason}"),
Self::Held(reason) => write!(f, "HELD:{reason}"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct BatchReconciliation {
carried_in: u64,
ingested: u64,
billable: u64,
suppressed: u64,
duplicate: u64,
rejected: u64,
held: u64,
}
impl BatchReconciliation {
pub const EMPTY: Self = Self {
carried_in: 0,
ingested: 0,
billable: 0,
suppressed: 0,
duplicate: 0,
rejected: 0,
held: 0,
};
pub const fn observe(&mut self, disposition: &Disposition) {
self.ingested += 1;
self.count_outcome(disposition);
}
pub const fn observe_carried(&mut self, disposition: &Disposition) {
self.carried_in += 1;
self.count_outcome(disposition);
}
#[must_use]
pub const fn observe_many(mut self, outcome: Outcome, count: u64) -> Option<Self> {
self.ingested = match self.ingested.checked_add(count) {
Some(v) => v,
None => return None,
};
match self.add_outcome(outcome, count) {
Some(()) => Some(self),
None => None,
}
}
#[must_use]
pub const fn observe_carried_many(mut self, outcome: Outcome, count: u64) -> Option<Self> {
self.carried_in = match self.carried_in.checked_add(count) {
Some(v) => v,
None => return None,
};
match self.add_outcome(outcome, count) {
Some(()) => Some(self),
None => None,
}
}
#[must_use]
pub const fn count_of(&self, outcome: Outcome) -> u64 {
match outcome {
Outcome::Billable => self.billable,
Outcome::Suppressed => self.suppressed,
Outcome::Duplicate => self.duplicate,
Outcome::Rejected => self.rejected,
Outcome::Held => self.held,
}
}
#[must_use]
pub const fn reclassify(mut self, from: Outcome, to: Outcome, count: u64) -> Option<Self> {
if self.count_of(from) < count {
return None;
}
self.take_outcome(from, count);
match self.add_outcome(to, count) {
Some(()) => Some(self),
None => None,
}
}
const fn add_outcome(&mut self, outcome: Outcome, count: u64) -> Option<()> {
let slot = match outcome {
Outcome::Billable => &mut self.billable,
Outcome::Suppressed => &mut self.suppressed,
Outcome::Duplicate => &mut self.duplicate,
Outcome::Rejected => &mut self.rejected,
Outcome::Held => &mut self.held,
};
match slot.checked_add(count) {
Some(v) => {
*slot = v;
Some(())
}
None => None,
}
}
const fn take_outcome(&mut self, outcome: Outcome, count: u64) {
let slot = match outcome {
Outcome::Billable => &mut self.billable,
Outcome::Suppressed => &mut self.suppressed,
Outcome::Duplicate => &mut self.duplicate,
Outcome::Rejected => &mut self.rejected,
Outcome::Held => &mut self.held,
};
*slot -= count;
}
const fn count_outcome(&mut self, disposition: &Disposition) {
let _ = self.add_outcome(disposition.outcome(), 1);
}
#[must_use]
pub const fn ingested(&self) -> u64 {
self.ingested
}
#[must_use]
pub const fn carried_in(&self) -> u64 {
self.carried_in
}
#[must_use]
pub const fn presented(&self) -> Option<u64> {
self.carried_in.checked_add(self.ingested)
}
#[must_use]
pub const fn released(&self) -> u64 {
self.billable
}
#[must_use]
pub const fn suppressed(&self) -> u64 {
self.suppressed
}
#[must_use]
pub const fn duplicate(&self) -> u64 {
self.duplicate
}
#[must_use]
pub const fn rejected(&self) -> u64 {
self.rejected
}
#[must_use]
pub const fn held(&self) -> u64 {
self.held
}
#[must_use]
pub const fn balances(&self) -> bool {
macro_rules! accumulate {
($acc:expr, $field:ident) => {
match $acc.checked_add(self.$field) {
Some(value) => value,
None => return false,
}
};
}
let total = self.billable;
let total = accumulate!(total, suppressed);
let total = accumulate!(total, duplicate);
let total = accumulate!(total, rejected);
let total = accumulate!(total, held);
match self.presented() {
Some(presented) => total == presented,
None => false,
}
}
#[must_use]
pub const fn is_final(&self) -> bool {
self.balances() && self.held == 0
}
#[must_use]
pub const fn checked_add(self, other: Self) -> Option<Self> {
macro_rules! add {
($field:ident) => {
match self.$field.checked_add(other.$field) {
Some(v) => v,
None => return None,
}
};
}
Some(Self {
carried_in: add!(carried_in),
ingested: add!(ingested),
billable: add!(billable),
suppressed: add!(suppressed),
duplicate: add!(duplicate),
rejected: add!(rejected),
held: add!(held),
})
}
}
impl fmt::Display for BatchReconciliation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"carried_in={} + ingested={} = billable={} + suppressed={} + duplicate={} + rejected={} + held={} [{}]",
self.carried_in,
self.ingested,
self.billable,
self.suppressed,
self.duplicate,
self.rejected,
self.held,
if self.balances() {
"balanced"
} else {
"UNBALANCED"
}
)
}
}
impl FromIterator<Disposition> for BatchReconciliation {
fn from_iter<I: IntoIterator<Item = Disposition>>(iter: I) -> Self {
let mut counts = Self::EMPTY;
for disposition in iter {
counts.observe(&disposition);
}
counts
}
}
impl<'a> FromIterator<&'a Disposition> for BatchReconciliation {
fn from_iter<I: IntoIterator<Item = &'a Disposition>>(iter: I) -> Self {
let mut counts = Self::EMPTY;
for disposition in iter {
counts.observe(disposition);
}
counts
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChainBreak {
Unbalanced {
batch: usize,
},
TotalsOverflow {
batch: usize,
},
CarryMismatch {
batch: usize,
expected: u64,
found: u64,
},
}
impl fmt::Display for ChainBreak {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unbalanced { batch } => write!(f, "batch {batch} does not balance"),
Self::TotalsOverflow { batch } => {
write!(f, "period totals overflowed at batch {batch}")
}
Self::CarryMismatch {
batch,
expected,
found,
} => write!(
f,
"batch {batch} carried in {found}, but {expected} were outstanding"
),
}
}
}
impl std::error::Error for ChainBreak {}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PeriodLedger {
totals: BatchReconciliation,
batches: usize,
outstanding: u64,
breaks: Vec<ChainBreak>,
}
impl PeriodLedger {
#[must_use]
pub const fn new() -> Self {
Self {
totals: BatchReconciliation::EMPTY,
batches: 0,
outstanding: 0,
breaks: Vec::new(),
}
}
pub fn append(&mut self, batch: BatchReconciliation) -> Result<(), ChainBreak> {
let index = self.batches;
self.batches += 1;
let mut first_break = None;
if !batch.balances() {
let broken = ChainBreak::Unbalanced { batch: index };
self.breaks.push(broken);
first_break = Some(broken);
}
if batch.carried_in() != self.outstanding {
let broken = ChainBreak::CarryMismatch {
batch: index,
expected: self.outstanding,
found: batch.carried_in(),
};
self.breaks.push(broken);
first_break = first_break.or(Some(broken));
}
self.outstanding = batch.held();
match self.totals.checked_add(batch) {
Some(totals) => self.totals = totals,
None => {
let broken = ChainBreak::TotalsOverflow { batch: index };
self.breaks.push(broken);
first_break = first_break.or(Some(broken));
}
}
match first_break {
Some(broken) => Err(broken),
None => Ok(()),
}
}
#[must_use]
pub const fn outstanding(&self) -> u64 {
self.outstanding
}
#[must_use]
pub const fn batches(&self) -> usize {
self.batches
}
#[must_use]
pub fn breaks(&self) -> &[ChainBreak] {
&self.breaks
}
#[must_use]
pub const fn totals(&self) -> BatchReconciliation {
self.totals
}
#[must_use]
pub const fn period_totals(&self) -> PeriodTotals {
PeriodTotals {
ingested: self.totals.ingested(),
billable: self.totals.released(),
suppressed: self.totals.suppressed(),
duplicate: self.totals.duplicate(),
rejected: self.totals.rejected(),
outstanding: self.outstanding,
}
}
#[must_use]
pub fn is_closable(&self) -> bool {
self.breaks.is_empty() && self.outstanding == 0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PeriodTotals {
pub ingested: u64,
pub billable: u64,
pub suppressed: u64,
pub duplicate: u64,
pub rejected: u64,
pub outstanding: u64,
}
impl PeriodTotals {
#[must_use]
pub const fn finalised(&self) -> Option<u64> {
let Some(total) = self.billable.checked_add(self.suppressed) else {
return None;
};
let Some(total) = total.checked_add(self.duplicate) else {
return None;
};
total.checked_add(self.rejected)
}
#[must_use]
pub const fn balances(&self) -> bool {
let Some(finalised) = self.finalised() else {
return false;
};
match finalised.checked_add(self.outstanding) {
Some(total) => total == self.ingested,
None => false,
}
}
#[must_use]
pub const fn is_closable(&self) -> bool {
self.balances() && self.outstanding == 0
}
}
impl fmt::Display for PeriodTotals {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"ingested={} = billable={} + suppressed={} + duplicate={} + rejected={} + outstanding={} [{}]",
self.ingested,
self.billable,
self.suppressed,
self.duplicate,
self.rejected,
self.outstanding,
if self.balances() {
"balanced"
} else {
"UNBALANCED"
}
)
}
}
impl fmt::Display for PeriodLedger {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} batch(es), {} outstanding, {} break(s) [{}]",
self.batches,
self.outstanding,
self.breaks.len(),
if self.is_closable() {
"closable"
} else {
"OPEN"
}
)
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::{BatchReconciliation, HoldReason, Outcome, SuppressReason};
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
macro_rules! string_serde {
($ty:ty, $expecting:literal) => {
impl Serialize for $ty {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for $ty {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V;
impl Visitor<'_> for V {
type Value = $ty;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str($expecting)
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<$ty, E> {
v.parse().map_err(de::Error::custom)
}
}
deserializer.deserialize_str(V)
}
}
};
}
string_serde!(SuppressReason, "a suppression reason code");
string_serde!(HoldReason, "a hold reason code");
string_serde!(Outcome, "an outcome code such as \"BILLABLE\"");
#[derive(Serialize, Deserialize)]
#[serde(rename = "BatchReconciliation")]
struct Repr {
#[serde(default)]
carried_in: u64,
ingested: u64,
billable: u64,
suppressed: u64,
duplicate: u64,
rejected: u64,
held: u64,
}
impl Serialize for BatchReconciliation {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
Repr {
carried_in: self.carried_in(),
ingested: self.ingested(),
billable: self.released(),
suppressed: self.suppressed(),
duplicate: self.duplicate(),
rejected: self.rejected(),
held: self.held(),
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for BatchReconciliation {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = Repr::deserialize(deserializer)?;
Ok(BatchReconciliation {
carried_in: r.carried_in,
ingested: r.ingested,
billable: r.billable,
suppressed: r.suppressed,
duplicate: r.duplicate,
rejected: r.rejected,
held: r.held,
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lateness::Lateness;
use time::Duration;
fn key() -> RecordKey {
RecordKey::RecordingEntity {
entity: "msc-01".parse().unwrap(),
local_sequence: 1,
}
}
#[test]
fn every_outcome_counts_exactly_once() {
let dispositions = [
Disposition::Billable,
Disposition::Billable,
Disposition::Suppressed(SuppressReason::TestIdentity),
Disposition::Duplicate(key()),
Disposition::Rejected(RejectReason::BeyondDeadline),
Disposition::Held(HoldReason::AwaitingPartial),
];
let counts: BatchReconciliation = dispositions.iter().collect();
assert_eq!(counts.ingested(), 6);
assert_eq!(counts.released(), 2);
assert_eq!(counts.suppressed(), 1);
assert_eq!(counts.duplicate(), 1);
assert_eq!(counts.rejected(), 1);
assert_eq!(counts.held(), 1);
assert!(counts.balances());
}
#[test]
fn holding_a_record_balances_but_does_not_finish_the_batch() {
let counts: BatchReconciliation = vec![
Disposition::Billable,
Disposition::Held(HoldReason::AwaitingCorrelation),
]
.into_iter()
.collect();
assert!(counts.balances());
assert!(!counts.is_final());
let settled: BatchReconciliation = vec![Disposition::Billable].into_iter().collect();
assert!(settled.is_final());
}
#[test]
fn counting_through_observe_always_balances() {
let mut counts = BatchReconciliation::EMPTY;
for reason in SuppressReason::ALL {
counts.observe(&Disposition::Suppressed(*reason));
}
for reason in HoldReason::ALL {
counts.observe(&Disposition::Held(*reason));
}
counts.observe(&Disposition::Billable);
counts.observe(&Disposition::Duplicate(key()));
counts.observe(&Disposition::Rejected(RejectReason::Malformed));
assert!(counts.balances());
assert_eq!(
counts.ingested(),
(SuppressReason::ALL.len() + HoldReason::ALL.len() + 3) as u64
);
}
#[test]
fn a_deserialised_imbalance_is_readable_and_reported() {
let broken = BatchReconciliation {
carried_in: 0,
ingested: 10,
billable: 3,
suppressed: 0,
duplicate: 0,
rejected: 0,
held: 0,
};
assert!(!broken.balances());
assert!(!broken.is_final());
assert!(broken.to_string().contains("UNBALANCED"), "{broken}");
}
#[test]
fn a_carried_record_is_not_counted_as_a_new_arrival() {
let mut first = BatchReconciliation::EMPTY;
first.observe(&Disposition::Billable);
first.observe(&Disposition::Held(HoldReason::AwaitingPartial));
assert_eq!(first.held(), 1);
let mut correct = BatchReconciliation::EMPTY;
correct.observe_carried(&Disposition::Billable);
assert_eq!(correct.carried_in(), 1);
assert_eq!(correct.ingested(), 0);
assert!(correct.balances());
let mut ledger = PeriodLedger::new();
ledger.append(first).unwrap();
ledger.append(correct).unwrap();
assert!(ledger.is_closable());
assert_eq!(
ledger.totals().ingested(),
2,
"two records arrived, in the first batch"
);
assert_eq!(
ledger.totals().carried_in(),
1,
"one of them crossed a boundary rather than arriving twice"
);
assert_eq!(ledger.totals().released(), 2);
}
#[test]
fn counting_a_carried_record_as_new_breaks_the_chain() {
let mut first = BatchReconciliation::EMPTY;
first.observe(&Disposition::Held(HoldReason::AwaitingPartial));
let mut wrong = BatchReconciliation::EMPTY;
wrong.observe(&Disposition::Billable);
assert!(wrong.balances(), "the batch is internally consistent");
let mut ledger = PeriodLedger::new();
ledger.append(first).unwrap();
assert_eq!(
ledger.append(wrong),
Err(ChainBreak::CarryMismatch {
batch: 1,
expected: 1,
found: 0,
})
);
assert!(!ledger.is_closable());
}
#[test]
fn dropping_a_held_record_breaks_the_chain() {
let mut first = BatchReconciliation::EMPTY;
for _ in 0..3 {
first.observe(&Disposition::Held(HoldReason::AwaitingCorrelation));
}
let mut second = BatchReconciliation::EMPTY;
second.observe_carried(&Disposition::Billable);
second.observe_carried(&Disposition::Billable);
let mut ledger = PeriodLedger::new();
ledger.append(first).unwrap();
assert!(matches!(
ledger.append(second),
Err(ChainBreak::CarryMismatch { found: 2, .. })
));
}
#[test]
fn a_period_with_outstanding_records_is_not_closable() {
let mut batch = BatchReconciliation::EMPTY;
batch.observe(&Disposition::Billable);
batch.observe(&Disposition::Held(HoldReason::SequenceGap));
let mut ledger = PeriodLedger::new();
ledger.append(batch).unwrap();
assert_eq!(ledger.outstanding(), 1);
assert!(!ledger.is_closable());
assert!(ledger.breaks().is_empty(), "outstanding is not a break");
assert!(ledger.to_string().contains("OPEN"), "{ledger}");
}
#[test]
fn a_break_survives_a_caller_that_continues() {
let mut first = BatchReconciliation::EMPTY;
first.observe(&Disposition::Held(HoldReason::AwaitingPartial));
let mut wrong = BatchReconciliation::EMPTY;
wrong.observe(&Disposition::Billable);
let mut clean = BatchReconciliation::EMPTY;
clean.observe(&Disposition::Billable);
let mut ledger = PeriodLedger::new();
ledger.append(first).unwrap();
let _ = ledger.append(wrong);
ledger.append(clean).unwrap();
assert_eq!(ledger.breaks().len(), 1);
assert!(!ledger.is_closable(), "a past break is never forgiven");
}
#[test]
fn a_totals_overflow_is_not_reported_as_an_imbalance() {
let mut huge = BatchReconciliation::EMPTY;
for _ in 0..2 {
huge.observe(&Disposition::Billable);
}
let mut period = PeriodLedger::new();
period.totals = BatchReconciliation {
carried_in: 0,
ingested: u64::MAX,
billable: u64::MAX,
suppressed: 0,
duplicate: 0,
rejected: 0,
held: 0,
};
assert_eq!(
period.append(huge),
Err(ChainBreak::TotalsOverflow { batch: 0 })
);
assert!(!period.is_closable());
assert!(period.to_string().contains("break"), "{period}");
}
#[test]
fn an_empty_period_is_closable_and_says_nothing_else() {
let ledger = PeriodLedger::new();
assert!(ledger.is_closable());
assert_eq!(ledger.batches(), 0);
assert_eq!(ledger.outstanding(), 0);
}
#[test]
fn merging_recombines_parallel_work() {
let left: BatchReconciliation = vec![Disposition::Billable].into_iter().collect();
let right: BatchReconciliation = vec![
Disposition::Billable,
Disposition::Rejected(RejectReason::Malformed),
]
.into_iter()
.collect();
let merged = left.checked_add(right).unwrap();
assert_eq!(merged.ingested(), 3);
assert_eq!(merged.released(), 2);
assert!(merged.balances());
}
#[test]
fn merging_is_checked() {
let huge = BatchReconciliation {
carried_in: 0,
ingested: u64::MAX,
billable: u64::MAX,
suppressed: 0,
duplicate: 0,
rejected: 0,
held: 0,
};
let one: BatchReconciliation = vec![Disposition::Billable].into_iter().collect();
assert_eq!(huge.checked_add(one), None);
}
#[test]
fn only_terminal_lateness_verdicts_become_rejections() {
assert_eq!(RejectReason::from_lateness(Lateness::OnTime), None);
assert_eq!(
RejectReason::from_lateness(Lateness::Late(Duration::days(1))),
None
);
assert_eq!(
RejectReason::from_lateness(Lateness::BeyondDeadline(Duration::days(40))),
Some(RejectReason::BeyondDeadline)
);
assert_eq!(
RejectReason::from_lateness(Lateness::Future(Duration::hours(1))),
Some(RejectReason::FutureTimestamp)
);
}
#[test]
fn dispositions_report_their_own_finality() {
assert!(Disposition::Billable.is_released());
assert!(!Disposition::Billable.may_return());
assert!(!Disposition::Billable.is_finding());
let held = Disposition::Held(HoldReason::SequenceGap);
assert!(!held.is_released());
assert!(held.may_return());
assert!(held.is_finding());
let rejected = Disposition::Rejected(RejectReason::Malformed);
assert!(!rejected.may_return(), "a rejection is terminal");
assert!(rejected.is_finding());
}
#[test]
fn reason_codes_round_trip() {
for reason in SuppressReason::ALL {
assert_eq!(reason.as_str().parse::<SuppressReason>().unwrap(), *reason);
}
for reason in HoldReason::ALL {
assert_eq!(reason.as_str().parse::<HoldReason>().unwrap(), *reason);
}
assert!("NOPE".parse::<SuppressReason>().is_err());
}
#[test]
fn dispositions_render_legibly() {
assert_eq!(
Disposition::Suppressed(SuppressReason::ZeroRated).to_string(),
"SUPPRESSED:ZERO_RATED"
);
assert_eq!(
Disposition::Rejected(RejectReason::NotKeyable(NotKeyable::NoCorrelatorPresent))
.to_string(),
"REJECTED:NOT_KEYABLE:NO_CORRELATOR_PRESENT"
);
assert_eq!(
Disposition::Held(HoldReason::SequenceGap).to_string(),
"HELD:SEQUENCE_GAP"
);
}
}