lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

stock.rs (19904B)


      1 use radroots_domain::stock::{
      2     PhysicalBalances, PoolBalances, PoolSnapshot, PoolUnit, StockError, StockTicks,
      3 };
      4 use radroots_domain::{Decimal, PoolId, Quantity, Sequence, listing::MeasurementUnit::*};
      5 
      6 fn ticks(value: u64) -> StockTicks {
      7     StockTicks::new(value).unwrap()
      8 }
      9 
     10 #[test]
     11 fn preparatory_release_preserves_other_claims_and_cumulative_physical_history() {
     12     let physical = PhysicalBalances {
     13         available: ticks(4),
     14         preparatory_hold: ticks(3),
     15         committed_hold: ticks(5),
     16         physical_quarantine: ticks(7),
     17         consumed: ticks(11),
     18         waste: ticks(13),
     19         removed: ticks(17),
     20     };
     21     let original = PoolBalances::new(ticks(60), physical).unwrap();
     22     let partial = original.release_preparatory(ticks(2)).unwrap();
     23     assert_eq!(partial.introduced(), ticks(60));
     24     assert_eq!(
     25         partial.physical(),
     26         PhysicalBalances {
     27             available: ticks(6),
     28             preparatory_hold: ticks(1),
     29             ..physical
     30         }
     31     );
     32     let complete = partial.release_preparatory(ticks(1)).unwrap();
     33     assert_eq!(complete.introduced(), ticks(60));
     34     assert_eq!(
     35         complete.physical(),
     36         PhysicalBalances {
     37             available: ticks(7),
     38             preparatory_hold: StockTicks::ZERO,
     39             ..physical
     40         }
     41     );
     42     assert_eq!(
     43         complete.release_preparatory(ticks(1)),
     44         Err(StockError::Underflow)
     45     );
     46     assert_eq!(
     47         original.release_preparatory(ticks(4)),
     48         Err(StockError::Underflow)
     49     );
     50     assert_eq!(
     51         original.release_preparatory(StockTicks::ZERO),
     52         Err(StockError::ZeroMovement)
     53     );
     54     assert_eq!(original.physical(), physical);
     55 }
     56 
     57 #[test]
     58 fn preparatory_release_at_introduced_maximum_does_not_mint_or_exhaust_capacity() {
     59     let original = PoolBalances::new(
     60         StockTicks::MAX,
     61         PhysicalBalances {
     62             preparatory_hold: StockTicks::MAX,
     63             ..PhysicalBalances::ZERO
     64         },
     65     )
     66     .unwrap();
     67     let released = original.release_preparatory(StockTicks::MAX).unwrap();
     68     assert_eq!(released.introduced(), StockTicks::MAX);
     69     assert_eq!(
     70         released.physical(),
     71         PhysicalBalances {
     72             available: StockTicks::MAX,
     73             ..PhysicalBalances::ZERO
     74         }
     75     );
     76     assert_eq!(
     77         released
     78             .hold_available(StockTicks::MAX)
     79             .unwrap()
     80             .release_preparatory(StockTicks::MAX)
     81             .unwrap(),
     82         released
     83     );
     84 }
     85 
     86 #[test]
     87 fn installation_moves_only_exact_preparatory_backing_and_preserves_all_other_categories() {
     88     let physical = PhysicalBalances {
     89         available: ticks(30),
     90         preparatory_hold: ticks(10),
     91         committed_hold: ticks(20),
     92         physical_quarantine: ticks(5),
     93         consumed: ticks(15),
     94         waste: ticks(10),
     95         removed: ticks(10),
     96     };
     97     let original = PoolBalances::new(ticks(100), physical).unwrap();
     98     let installed = original.install_preparatory(ticks(3)).unwrap();
     99     assert_eq!(installed.introduced(), ticks(100));
    100     assert_eq!(
    101         installed.physical(),
    102         PhysicalBalances {
    103             preparatory_hold: ticks(7),
    104             committed_hold: ticks(23),
    105             ..physical
    106         }
    107     );
    108     assert_eq!(
    109         original.install_preparatory(ticks(11)),
    110         Err(StockError::Underflow)
    111     );
    112     assert_eq!(
    113         original.install_preparatory(StockTicks::ZERO),
    114         Err(StockError::ZeroMovement)
    115     );
    116     let maximum = PoolBalances::new(
    117         StockTicks::MAX,
    118         PhysicalBalances {
    119             preparatory_hold: StockTicks::MAX,
    120             ..PhysicalBalances::ZERO
    121         },
    122     )
    123     .unwrap();
    124     assert_eq!(
    125         maximum
    126             .install_preparatory(StockTicks::MAX)
    127             .unwrap()
    128             .physical()
    129             .committed_hold,
    130         StockTicks::MAX
    131     );
    132     assert_eq!(original.physical(), physical);
    133 }
    134 
    135 #[test]
    136 fn proposed_holds_conserve_stock_and_cannot_borrow_other_physical_categories() {
    137     let physical = PhysicalBalances {
    138         available: ticks(30),
    139         preparatory_hold: ticks(10),
    140         committed_hold: ticks(20),
    141         physical_quarantine: ticks(5),
    142         consumed: ticks(15),
    143         waste: ticks(10),
    144         removed: ticks(10),
    145     };
    146     let original = PoolBalances::new(ticks(100), physical).unwrap();
    147     let first = original.hold_available(ticks(10)).unwrap();
    148     assert_eq!(first.introduced(), original.introduced());
    149     assert_eq!(
    150         first.physical(),
    151         PhysicalBalances {
    152             available: ticks(20),
    153             preparatory_hold: ticks(20),
    154             ..physical
    155         }
    156     );
    157     let full = first.hold_available(ticks(20)).unwrap();
    158     assert_eq!(full.introduced(), original.introduced());
    159     assert_eq!(
    160         full.physical(),
    161         PhysicalBalances {
    162             available: StockTicks::ZERO,
    163             preparatory_hold: ticks(40),
    164             ..physical
    165         }
    166     );
    167     assert_eq!(
    168         original.hold_available(ticks(31)),
    169         Err(StockError::Underflow)
    170     );
    171     assert_eq!(full.hold_available(ticks(1)), Err(StockError::Underflow));
    172     assert_eq!(
    173         original.hold_available(StockTicks::ZERO),
    174         Err(StockError::ZeroMovement)
    175     );
    176     assert_eq!(original.physical(), physical);
    177 }
    178 
    179 #[test]
    180 fn proposed_holds_reach_the_exact_supported_capacity_without_wrap_or_float() {
    181     let original = PoolBalances::new(
    182         StockTicks::MAX,
    183         PhysicalBalances {
    184             available: ticks(1),
    185             preparatory_hold: ticks(StockTicks::MAX.get() - 1),
    186             ..PhysicalBalances::ZERO
    187         },
    188     )
    189     .unwrap();
    190     assert_eq!(
    191         original.hold_available(ticks(2)),
    192         Err(StockError::Underflow)
    193     );
    194     let held = original.hold_available(ticks(1)).unwrap();
    195     assert_eq!(held.introduced(), StockTicks::MAX);
    196     assert_eq!(
    197         held.physical(),
    198         PhysicalBalances {
    199             preparatory_hold: StockTicks::MAX,
    200             ..PhysicalBalances::ZERO
    201         }
    202     );
    203     assert_eq!(held.hold_available(ticks(1)), Err(StockError::Underflow));
    204 }
    205 
    206 #[test]
    207 fn available_corrections_conserve_audited_totals_without_touching_backed_claims() {
    208     use radroots_domain::stock::AvailableStockCorrection::{Add, Remove, Spoil};
    209     let original = PoolBalances::new(
    210         ticks(100),
    211         PhysicalBalances {
    212             available: ticks(30),
    213             preparatory_hold: ticks(10),
    214             committed_hold: ticks(20),
    215             physical_quarantine: ticks(5),
    216             consumed: ticks(15),
    217             waste: ticks(10),
    218             removed: ticks(10),
    219         },
    220     )
    221     .unwrap();
    222     let added = original.correct_available(Add, ticks(7)).unwrap();
    223     assert_eq!(added.introduced(), ticks(107));
    224     assert_eq!(
    225         added.physical(),
    226         PhysicalBalances {
    227             available: ticks(37),
    228             ..original.physical()
    229         }
    230     );
    231     let removed = added.correct_available(Remove, ticks(11)).unwrap();
    232     assert_eq!(removed.introduced(), ticks(107));
    233     assert_eq!(
    234         removed.physical(),
    235         PhysicalBalances {
    236             available: ticks(26),
    237             removed: ticks(21),
    238             ..original.physical()
    239         }
    240     );
    241     let wasted = removed.correct_available(Spoil, ticks(26)).unwrap();
    242     assert_eq!(wasted.introduced(), ticks(107));
    243     assert_eq!(
    244         wasted.physical(),
    245         PhysicalBalances {
    246             available: StockTicks::ZERO,
    247             removed: ticks(21),
    248             waste: ticks(36),
    249             ..original.physical()
    250         }
    251     );
    252     for kind in [Remove, Spoil] {
    253         assert_eq!(
    254             original.correct_available(kind, ticks(31)),
    255             Err(StockError::Underflow)
    256         );
    257         assert_eq!(
    258             wasted.correct_available(kind, ticks(1)),
    259             Err(StockError::Underflow)
    260         );
    261     }
    262     for kind in [Add, Remove, Spoil] {
    263         assert_eq!(
    264             original.correct_available(kind, StockTicks::ZERO),
    265             Err(StockError::ZeroMovement)
    266         );
    267     }
    268     assert_eq!(original.physical().available, ticks(30));
    269 }
    270 
    271 #[test]
    272 fn introduced_capacity_is_not_reused_after_removal_or_spoilage() {
    273     use radroots_domain::stock::AvailableStockCorrection::{Add, Remove, Spoil};
    274     let full = PoolBalances::new(
    275         StockTicks::MAX,
    276         PhysicalBalances {
    277             available: StockTicks::MAX,
    278             ..PhysicalBalances::ZERO
    279         },
    280     )
    281     .unwrap();
    282     for kind in [Remove, Spoil] {
    283         let depleted = full.correct_available(kind, StockTicks::MAX).unwrap();
    284         assert_eq!(depleted.physical().available, StockTicks::ZERO);
    285         assert_eq!(depleted.introduced(), StockTicks::MAX);
    286         assert_eq!(
    287             depleted.correct_available(Add, ticks(1)),
    288             Err(StockError::OutOfRange)
    289         );
    290     }
    291     assert_eq!(
    292         full.correct_available(Add, ticks(1)),
    293         Err(StockError::OutOfRange)
    294     );
    295 }
    296 
    297 #[test]
    298 fn tick_bounds_and_canonical_integer_strings_never_round_or_wrap() {
    299     for value in [
    300         0,
    301         1,
    302         9_007_199_254_740_991,
    303         9_007_199_254_740_993,
    304         StockTicks::MAX.get(),
    305     ] {
    306         let exact = ticks(value);
    307         assert_eq!(
    308             exact.to_string().parse::<StockTicks>().unwrap().get(),
    309             value
    310         );
    311     }
    312     for value in [StockTicks::MAX.get() + 1, u64::MAX] {
    313         assert_eq!(StockTicks::new(value), Err(StockError::OutOfRange));
    314     }
    315     for value in [
    316         "",
    317         "00",
    318         "01",
    319         "+1",
    320         "-1",
    321         "1.0",
    322         "1e3",
    323         " 1",
    324         "1\n",
    325         "1",
    326         "١",
    327         "10000000000000000000",
    328     ] {
    329         assert!(value.parse::<StockTicks>().is_err(), "{value:?}");
    330     }
    331     assert_eq!(
    332         "1000000000000000001".parse::<StockTicks>(),
    333         Err(StockError::OutOfRange)
    334     );
    335     assert_eq!(
    336         StockTicks::MAX.checked_add(ticks(1)),
    337         Err(StockError::OutOfRange)
    338     );
    339     assert_eq!(
    340         StockTicks::ZERO.checked_sub(ticks(1)),
    341         Err(StockError::Underflow)
    342     );
    343     assert_eq!(
    344         StockTicks::MAX.checked_sub(StockTicks::MAX),
    345         Ok(StockTicks::ZERO)
    346     );
    347 }
    348 
    349 #[test]
    350 fn every_physical_unit_has_explicit_precision_and_each_is_integral() {
    351     for unit in [Gram, Kilogram, Millilitre, Litre, Each] {
    352         for scale in 0..=6 {
    353             let result = PoolUnit::new(unit, scale);
    354             if unit == Each && scale != 0 {
    355                 assert_eq!(result, Err(StockError::FractionalCount));
    356             } else {
    357                 let value = result.unwrap();
    358                 assert_eq!(value.unit(), unit);
    359                 assert_eq!(value.scale(), scale);
    360             }
    361         }
    362         for scale in [7, u8::MAX] {
    363             assert_eq!(PoolUnit::new(unit, scale), Err(StockError::InvalidScale));
    364         }
    365     }
    366 }
    367 
    368 #[test]
    369 fn quantities_convert_to_integral_ticks_only_with_exact_explicit_pool_units() {
    370     for unit in [Gram, Kilogram, Millilitre, Litre] {
    371         for (amount, scale, expected) in [
    372             ("0", 0, 0),
    373             ("1.25", 2, 125),
    374             ("0.000001", 6, 1),
    375             ("999999999999", 6, 999_999_999_999_000_000),
    376         ] {
    377             let quantity = Quantity::new(amount.parse().unwrap(), unit).unwrap();
    378             let pool = PoolUnit::new(unit, scale).unwrap();
    379             assert_eq!(pool.ticks_for(quantity).unwrap().get(), expected);
    380         }
    381         let quantity = Quantity::new("1.000001".parse().unwrap(), unit).unwrap();
    382         for scale in 0..6 {
    383             assert_eq!(
    384                 PoolUnit::new(unit, scale).unwrap().ticks_for(quantity),
    385                 Err(StockError::PrecisionLoss)
    386             );
    387         }
    388         let quantity = Quantity::new(Decimal::ONE, unit).unwrap();
    389         for other in [Gram, Kilogram, Millilitre, Litre, Each] {
    390             if other != unit {
    391                 assert_eq!(
    392                     PoolUnit::new(other, 0).unwrap().ticks_for(quantity),
    393                     Err(StockError::UnitMismatch)
    394                 );
    395             }
    396         }
    397     }
    398     let kg = Quantity::new("1.25".parse().unwrap(), Kilogram).unwrap();
    399     let gram_pool = PoolUnit::new(Gram, 0).unwrap();
    400     assert_eq!(gram_pool.ticks_for(kg), Err(StockError::UnitMismatch));
    401     assert_eq!(
    402         gram_pool.ticks_for(kg.convert(Gram).unwrap()).unwrap(),
    403         ticks(1250)
    404     );
    405     let each = Quantity::new("999999999999".parse().unwrap(), Each).unwrap();
    406     assert_eq!(
    407         PoolUnit::new(Each, 0).unwrap().ticks_for(each).unwrap(),
    408         ticks(999_999_999_999)
    409     );
    410 }
    411 
    412 #[test]
    413 fn every_category_is_counted_once_and_released_stock_is_a_movement() {
    414     for position in 0..7 {
    415         let mut physical = PhysicalBalances::ZERO;
    416         let target = match position {
    417             0 => &mut physical.available,
    418             1 => &mut physical.preparatory_hold,
    419             2 => &mut physical.committed_hold,
    420             3 => &mut physical.physical_quarantine,
    421             4 => &mut physical.consumed,
    422             5 => &mut physical.waste,
    423             6 => &mut physical.removed,
    424             _ => unreachable!(),
    425         };
    426         *target = StockTicks::MAX;
    427         let exact = PoolBalances::new(StockTicks::MAX, physical).unwrap();
    428         assert_eq!(exact.physical(), physical);
    429         assert_eq!(exact.introduced(), StockTicks::MAX);
    430         assert!(PoolBalances::new(ticks(StockTicks::MAX.get() - 1), physical).is_err());
    431     }
    432     let before = PhysicalBalances {
    433         available: ticks(70),
    434         preparatory_hold: ticks(30),
    435         ..PhysicalBalances::ZERO
    436     };
    437     let after = PhysicalBalances {
    438         available: ticks(100),
    439         ..PhysicalBalances::ZERO
    440     };
    441     assert!(PoolBalances::new(ticks(100), before).is_ok());
    442     assert!(PoolBalances::new(ticks(100), after).is_ok());
    443     // Treating the release as introduced stock would double count it.
    444     assert_eq!(
    445         PoolBalances::new(ticks(130), after),
    446         Err(StockError::ConservationViolation)
    447     );
    448 }
    449 
    450 #[test]
    451 fn mixed_physical_categories_conserve_and_promises_or_deficits_cannot_fill_a_gap() {
    452     let physical = PhysicalBalances {
    453         available: ticks(1),
    454         preparatory_hold: ticks(2),
    455         committed_hold: ticks(3),
    456         physical_quarantine: ticks(4),
    457         consumed: ticks(5),
    458         waste: ticks(6),
    459         removed: ticks(7),
    460     };
    461     let balances = PoolBalances::new(ticks(28), physical).unwrap();
    462     assert_eq!(balances.physical(), physical);
    463     for introduced in [0, 27, 29] {
    464         assert_eq!(
    465             PoolBalances::new(ticks(introduced), physical),
    466             Err(StockError::ConservationViolation)
    467         );
    468     }
    469     let over = PhysicalBalances {
    470         available: StockTicks::MAX,
    471         waste: StockTicks::MAX,
    472         ..PhysicalBalances::ZERO
    473     };
    474     assert_eq!(
    475         PoolBalances::new(StockTicks::MAX, over),
    476         Err(StockError::OutOfRange)
    477     );
    478     assert_eq!(
    479         PoolBalances::new(ticks(1), PhysicalBalances::ZERO),
    480         Err(StockError::ConservationViolation)
    481     );
    482 }
    483 
    484 #[test]
    485 fn snapshots_keep_pool_identity_precision_and_declared_version_distinct() {
    486     let id = PoolId::from_bytes([7; 32]);
    487     let balances = PoolBalances::new(
    488         ticks(5),
    489         PhysicalBalances {
    490             available: ticks(5),
    491             ..PhysicalBalances::ZERO
    492         },
    493     )
    494     .unwrap();
    495     let unit = PoolUnit::new(Kilogram, 3).unwrap();
    496     let version = Sequence::new(0).unwrap();
    497     let snapshot = PoolSnapshot::new(id, unit, balances, version);
    498     assert_eq!(snapshot.id(), id);
    499     assert_eq!(snapshot.unit(), unit);
    500     assert_eq!(snapshot.balances(), balances);
    501     assert_eq!(snapshot.version(), version);
    502     assert!(
    503         !format!(
    504             "{snapshot:?} {balances:?} {:?} {:?}",
    505             balances.physical(),
    506             ticks(123456789)
    507         )
    508         .contains("123456789")
    509     );
    510 }
    511 
    512 #[cfg(feature = "serde")]
    513 #[test]
    514 fn foreign_tick_serialization_uses_exact_strings_and_rejects_json_numbers() {
    515     for value in [
    516         StockTicks::ZERO,
    517         ticks(9_007_199_254_740_993),
    518         StockTicks::MAX,
    519     ] {
    520         let wire = serde_json::to_string(&value).unwrap();
    521         assert_eq!(wire, format!("\"{value}\""));
    522         assert_eq!(serde_json::from_str::<StockTicks>(&wire).unwrap(), value);
    523     }
    524     for value in [
    525         "0",
    526         "9007199254740993",
    527         "1.0",
    528         "null",
    529         "true",
    530         "[]",
    531         "{}",
    532         "\"01\"",
    533         "\"1e3\"",
    534         "\"1000000000000000001\"",
    535     ] {
    536         assert!(
    537             serde_json::from_str::<StockTicks>(value).is_err(),
    538             "{value}"
    539         );
    540     }
    541 }
    542 
    543 #[cfg(feature = "serde")]
    544 #[test]
    545 fn protected_projection_value_codec_is_lossless_and_checks_conservation() {
    546     use serde_json::{Value, json};
    547     let amount = StockTicks::MAX;
    548     let snapshot = PoolSnapshot::new(
    549         PoolId::from_bytes([9; 32]),
    550         PoolUnit::new(Kilogram, 6).unwrap(),
    551         PoolBalances::new(
    552             amount,
    553             PhysicalBalances {
    554                 available: amount,
    555                 ..PhysicalBalances::ZERO
    556             },
    557         )
    558         .unwrap(),
    559         Sequence::new(i64::MAX as u64).unwrap(),
    560     );
    561     let value = serde_json::to_value(snapshot).unwrap();
    562     assert_eq!(value["unit"], json!({"unit":"kg","scale":"6"}));
    563     assert_eq!(
    564         value["balances"]["introduced"],
    565         json!("1000000000000000000")
    566     );
    567     assert_eq!(value["version"], json!("9223372036854775807"));
    568     assert_eq!(
    569         serde_json::from_value::<PoolSnapshot>(value.clone()).unwrap(),
    570         snapshot
    571     );
    572     for (path, bad) in [
    573         ("/balances/physical/available", json!("999999999999999999")),
    574         ("/balances/physical/available", json!("1000000000000000001")),
    575         ("/balances/physical/available", json!(100)),
    576         ("/balances/introduced", json!("-1")),
    577         ("/version", json!("01")),
    578         ("/unit/scale", json!(6)),
    579         ("/unit/scale", json!("06")),
    580         ("/unit/scale", json!("7")),
    581         ("/unit/unit", json!("each")),
    582         ("/unit", json!(["kg", "6"])),
    583         ("/balances", json!(["1000000000000000000", {}])),
    584         (
    585             "/balances/physical",
    586             json!(["1000000000000000000", "0", "0", "0", "0", "0", "0"]),
    587         ),
    588     ] {
    589         let mut changed = value.clone();
    590         *changed.pointer_mut(path).unwrap() = bad;
    591         assert!(
    592             serde_json::from_value::<PoolSnapshot>(changed).is_err(),
    593             "{path}"
    594         );
    595     }
    596     for path in ["", "/unit", "/balances", "/balances/physical"] {
    597         let mut changed = value.clone();
    598         changed
    599             .pointer_mut(path)
    600             .unwrap()
    601             .as_object_mut()
    602             .unwrap()
    603             .insert("extra".into(), Value::Null);
    604         assert!(
    605             serde_json::from_value::<PoolSnapshot>(changed).is_err(),
    606             "{path}"
    607         );
    608     }
    609     assert!(
    610         serde_json::from_value::<PoolSnapshot>(json!([
    611             value["id"],
    612             value["unit"],
    613             value["balances"],
    614             value["version"]
    615         ]))
    616         .is_err()
    617     );
    618 }
    619 #[cfg(feature = "serde")]
    620 #[test]
    621 fn unit_codecs_accept_only_exact_symbols_and_canonical_precision_strings() {
    622     use serde_json::json;
    623     for unit in [Gram, Kilogram, Millilitre, Litre, Each] {
    624         for scale in 0..=6 {
    625             if unit == Each && scale != 0 {
    626                 continue;
    627             }
    628             let value = PoolUnit::new(unit, scale).unwrap();
    629             assert_eq!(
    630                 serde_json::from_str::<PoolUnit>(&serde_json::to_string(&value).unwrap()).unwrap(),
    631                 value
    632             );
    633         }
    634     }
    635     for symbol in [
    636         json!("ml"),
    637         json!("l"),
    638         json!("KG"),
    639         json!("piece"),
    640         json!({"g":null}),
    641         json!(["g"]),
    642     ] {
    643         assert!(
    644             serde_json::from_value::<radroots_domain::listing::MeasurementUnit>(symbol).is_err()
    645         );
    646     }
    647 }