Skip to content

Run the Transactional Stock Ledger

The Course
•
26 min study

The intermediate reading queue applied one command at a time. This project is a small library that accepts a batch of ordered changes under an ID and commits it only after every change succeeds. It brings together the whole week: validated types from Day 1, owned rules from Day 2, bounded input from Day 3, staging and receipts from Day 4, error sources and borrowed queries from Day 5, and the failure-injection tests from Day 6. Today you run it, trace it, test it and extend it.

Each input line is one batch, such as 1 Widget:5;gadget:2: a positive u32 ID, whitespace, then one to eight item:delta changes separated by semicolons. Deltas are nonzero i64 values. Item names contain 1–24 ASCII letters, digits, hyphens or underscores, and normalize to lowercase, so Widget and widget are the same item. Whitespace around names and numbers is trimmed.

The console application sets three resource limits: a maximum quantity of 1000 per item, 32 distinct items, and 32 accepted batch IDs. Each limit exists so that no input, however hostile, can make the ledger grow without bound. An item whose stock falls to zero keeps its slot, because removing it would let a client cycle through unlimited names. Each line may be at most 256 bytes, counting the newline.

Errors fall into two groups, and they are handled differently on purpose. A command error, such as bad syntax or a rejected quantity, is reported with its line number, and processing continues with the next line, because the line boundary is still known. An oversized line, invalid UTF-8 or an I/O failure stops the stream. After an oversized line, the rest of that line is still unread; continuing would parse a fragment of it as if it were a new batch. Each Run starts a fresh ledger, so receipts never carry over.

Predict and run

The second batch would increase widget before taking too much gadget. Which values survive that rejection? Does repeating batch 1 add five more widgets?

Predict, then run Rust
include!("lib.rs"); fn main() -> std::io::Result<()> { app::run(std::io::stdin().lock(), std::io::stdout().lock()) } pub mod app; pub mod codec; pub mod ledger; pub mod types; #[cfg(test)] mod checks; #[cfg(test)] mod tests { #[test] fn ledger_contract() { super::checks::run(); } } use std::borrow::Cow; use std::fmt; pub const MAX_CHANGES: usize = 8; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Item(String); #[derive(Clone, Debug, PartialEq, Eq)] pub enum ValidationError { Item, ZeroDelta, ZeroId, BatchSize, } impl fmt::Display for ValidationError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { let message = match self { Self::Item => "use an item of 1–24 ASCII letters, digits, hyphens or underscores", Self::ZeroDelta => "delta must be nonzero", Self::ZeroId => "batch ID must be positive", Self::BatchSize => "use 1–8 changes per batch", }; formatter.write_str(message) } } impl std::error::Error for ValidationError {} impl TryFrom<&str> for Item { type Error = ValidationError; fn try_from(text: &str) -> Result<Self, Self::Error> { let text = text.trim(); if text.is_empty() || text.len() > 24 || !text.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_') { return Err(ValidationError::Item); } let normalized: Cow<'_, str> = if text.bytes().any(|byte| byte.is_ascii_uppercase()) { Cow::Owned(text.to_ascii_lowercase()) } else { Cow::Borrowed(text) }; Ok(Self(normalized.into_owned())) } } impl Item { pub fn as_str(&self) -> &str { &self.0 } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Change { item: Item, delta: i64, } impl Change { pub fn new(item: Item, delta: i64) -> Result<Self, ValidationError> { if delta == 0 { return Err(ValidationError::ZeroDelta); } Ok(Self { item, delta }) } pub fn item(&self) -> &Item { &self.item } pub fn delta(&self) -> i64 { self.delta } } pub struct Draft { pub id: u32, pub changes: Vec<Change>, } #[derive(Debug)] pub struct Batch { id: u32, changes: Vec<Change>, } impl Draft { pub fn validate(self) -> Result<Batch, ValidationError> { if self.id == 0 { return Err(ValidationError::ZeroId); } if self.changes.is_empty() || self.changes.len() > MAX_CHANGES { return Err(ValidationError::BatchSize); } Ok(Batch { id: self.id, changes: self.changes }) } } impl Batch { pub fn id(&self) -> u32 { self.id } pub fn changes(&self) -> &[Change] { &self.changes } } use crate::types::{Batch, Change, Item}; use std::collections::BTreeMap; use std::fmt; #[derive(Debug, PartialEq, Eq)] pub enum ApplyError { RetryConflict, ReceiptLimit, Arithmetic, Quantity, Policy, ItemLimit, } impl fmt::Display for ApplyError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { let message = match self { Self::RetryConflict => "batch ID was used for different changes", Self::ReceiptLimit => "receipt limit reached", Self::Arithmetic => "arithmetic overflow", Self::Quantity => "quantity must fit a nonnegative u32", Self::Policy => "quantity rejected by policy", Self::ItemLimit => "item limit reached", }; formatter.write_str(message) } } impl std::error::Error for ApplyError {} pub trait Rule { fn allows(&self, item: &Item, quantity: u32) -> bool; } pub struct MaxQuantity(pub u32); impl Rule for MaxQuantity { fn allows(&self, _item: &Item, quantity: u32) -> bool { quantity <= self.0 } } #[derive(Debug, PartialEq, Eq)] pub enum Outcome { Applied, Replayed, } pub struct Ledger { stock: BTreeMap<Item, u32>, receipts: BTreeMap<u32, Vec<Change>>, rule: Box<dyn Rule>, max_items: usize, max_receipts: usize, } impl Ledger { pub fn new(rule: Box<dyn Rule>, max_items: usize, max_receipts: usize) -> Self { Self { stock: BTreeMap::new(), receipts: BTreeMap::new(), rule, max_items, max_receipts } } pub fn apply(&mut self, batch: &Batch) -> Result<Outcome, ApplyError> { if let Some(previous) = self.receipts.get(&batch.id()) { return if previous == batch.changes() { Ok(Outcome::Replayed) } else { Err(ApplyError::RetryConflict) }; } if self.receipts.len() >= self.max_receipts { return Err(ApplyError::ReceiptLimit); } let mut staged = self.stock.clone(); for change in batch.changes() { let old = i64::from(*staged.get(change.item()).unwrap_or(&0)); let next = old.checked_add(change.delta()).ok_or(ApplyError::Arithmetic)?; let next = u32::try_from(next).map_err(|_| ApplyError::Quantity)?; if !self.rule.allows(change.item(), next) { return Err(ApplyError::Policy); } staged.insert(change.item().clone(), next); if staged.len() > self.max_items { return Err(ApplyError::ItemLimit); } } self.stock = staged; self.receipts.insert(batch.id(), batch.changes().to_vec()); Ok(Outcome::Applied) } pub fn entries(&self) -> impl Iterator<Item = (&Item, u32)> { self.stock.iter().map(|(item, quantity)| (item, *quantity)) } pub fn receipt_count(&self) -> usize { self.receipts.len() } } use crate::types::{Batch, Change, Draft, Item, ValidationError, MAX_CHANGES}; use std::fmt; use std::io::{self, BufRead, Read}; pub const MAX_LINE_BYTES: usize = 256; #[derive(Debug)] pub enum ParseError { Syntax, Number, Validation(ValidationError), } impl fmt::Display for ParseError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Syntax => formatter.write_str("use ID item:delta;item:delta"), Self::Number => formatter.write_str("invalid batch ID or delta"), Self::Validation(error) => write!(formatter, "{error}"), } } } impl std::error::Error for ParseError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Self::Validation(error) => Some(error), _ => None, } } } impl From<ValidationError> for ParseError { fn from(error: ValidationError) -> Self { Self::Validation(error) } } pub fn parse(text: &str) -> Result<Batch, ParseError> { let text = text.trim(); let (id, body) = text.split_once(char::is_whitespace).ok_or(ParseError::Syntax)?; let id = id.parse::<u32>().map_err(|_| ParseError::Number)?; let mut changes = Vec::new(); for part in body.split(';') { if changes.len() == MAX_CHANGES { return Err(ValidationError::BatchSize.into()); } let (item, delta) = part.trim().split_once(':').ok_or(ParseError::Syntax)?; let item = Item::try_from(item)?; let delta = delta.trim().parse::<i64>().map_err(|_| ParseError::Number)?; changes.push(Change::new(item, delta)?); } Ok(Draft { id, changes }.validate()?) } pub fn read_line(input: &mut impl BufRead) -> io::Result<Option<String>> { let mut bytes = Vec::new(); let count = input.take((MAX_LINE_BYTES + 1) as u64).read_until(b'\n', &mut bytes)?; if count == 0 { return Ok(None); } if count > MAX_LINE_BYTES { return Err(io::Error::new(io::ErrorKind::InvalidData, "line exceeds 256 bytes")); } let line = String::from_utf8(bytes) .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "input must be UTF-8"))?; Ok(Some(line)) } use crate::codec; use crate::ledger::{Ledger, MaxQuantity}; use std::io::{self, BufRead, Write}; pub fn run(mut input: impl BufRead, mut output: impl Write) -> io::Result<()> { let mut ledger = Ledger::new(Box::new(MaxQuantity(1000)), 32, 32); let mut line_number = 0; while let Some(line) = codec::read_line(&mut input)? { line_number += 1; if line.trim().is_empty() { continue; } match codec::parse(&line) { Ok(batch) => match ledger.apply(&batch) { Ok(outcome) => writeln!(output, "Batch {}: {outcome:?}", batch.id())?, Err(error) => writeln!(output, "Line {line_number}: {error}")?, }, Err(error) => writeln!(output, "Line {line_number}: {error}")?, } } writeln!(output, "Stock")?; for (item, quantity) in ledger.entries() { writeln!(output, "{}={quantity}", item.as_str())?; } writeln!(output, "Receipts: {}", ledger.receipt_count())?; output.flush() } 1 Widget:5;gadget:2 2 widget:1;gadget:-3 1 widget:5;gadget:2 3 widget:-2
Check your prediction
Text
Batch 1: Applied
Line 2: quantity must fit a nonnegative u32
Batch 1: Replayed
Batch 3: Applied
Stock
gadget=2
widget=3
Receipts: 2

Batch 2 staged widget=6 and then failed on gadget=-1, so the stage was dropped and widget stayed at 5. Line 3 repeats batch 1 with different capitalization; after normalization the changes are identical, so it replays. Batch 3 then takes widget from 5 to 3. Only two receipts exist, because the failed batch 2 never recorded one.

Now experiment in the stdin panel. Change the repeated batch to 1 widget:6;gadget:2 and predict the line: its ID is already associated with different changes, so it should conflict. Then change batch 2 to a valid correction, such as 2 widget:1;gadget:-1. It is accepted under the same ID that was rejected a moment ago, because a failed batch leaves no receipt behind.

Each layer rejects its own mistakes

The same program with a different input shows which layer catches which mistake. Read each line of input and predict the message before running.

Reject input at each layer Rust
include!("lib.rs"); fn main() -> std::io::Result<()> { app::run(std::io::stdin().lock(), std::io::stdout().lock()) } pub mod app; pub mod codec; pub mod ledger; pub mod types; #[cfg(test)] mod checks; #[cfg(test)] mod tests { #[test] fn ledger_contract() { super::checks::run(); } } use std::borrow::Cow; use std::fmt; pub const MAX_CHANGES: usize = 8; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Item(String); #[derive(Clone, Debug, PartialEq, Eq)] pub enum ValidationError { Item, ZeroDelta, ZeroId, BatchSize, } impl fmt::Display for ValidationError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { let message = match self { Self::Item => "use an item of 1–24 ASCII letters, digits, hyphens or underscores", Self::ZeroDelta => "delta must be nonzero", Self::ZeroId => "batch ID must be positive", Self::BatchSize => "use 1–8 changes per batch", }; formatter.write_str(message) } } impl std::error::Error for ValidationError {} impl TryFrom<&str> for Item { type Error = ValidationError; fn try_from(text: &str) -> Result<Self, Self::Error> { let text = text.trim(); if text.is_empty() || text.len() > 24 || !text.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_') { return Err(ValidationError::Item); } let normalized: Cow<'_, str> = if text.bytes().any(|byte| byte.is_ascii_uppercase()) { Cow::Owned(text.to_ascii_lowercase()) } else { Cow::Borrowed(text) }; Ok(Self(normalized.into_owned())) } } impl Item { pub fn as_str(&self) -> &str { &self.0 } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Change { item: Item, delta: i64, } impl Change { pub fn new(item: Item, delta: i64) -> Result<Self, ValidationError> { if delta == 0 { return Err(ValidationError::ZeroDelta); } Ok(Self { item, delta }) } pub fn item(&self) -> &Item { &self.item } pub fn delta(&self) -> i64 { self.delta } } pub struct Draft { pub id: u32, pub changes: Vec<Change>, } #[derive(Debug)] pub struct Batch { id: u32, changes: Vec<Change>, } impl Draft { pub fn validate(self) -> Result<Batch, ValidationError> { if self.id == 0 { return Err(ValidationError::ZeroId); } if self.changes.is_empty() || self.changes.len() > MAX_CHANGES { return Err(ValidationError::BatchSize); } Ok(Batch { id: self.id, changes: self.changes }) } } impl Batch { pub fn id(&self) -> u32 { self.id } pub fn changes(&self) -> &[Change] { &self.changes } } use crate::types::{Batch, Change, Item}; use std::collections::BTreeMap; use std::fmt; #[derive(Debug, PartialEq, Eq)] pub enum ApplyError { RetryConflict, ReceiptLimit, Arithmetic, Quantity, Policy, ItemLimit, } impl fmt::Display for ApplyError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { let message = match self { Self::RetryConflict => "batch ID was used for different changes", Self::ReceiptLimit => "receipt limit reached", Self::Arithmetic => "arithmetic overflow", Self::Quantity => "quantity must fit a nonnegative u32", Self::Policy => "quantity rejected by policy", Self::ItemLimit => "item limit reached", }; formatter.write_str(message) } } impl std::error::Error for ApplyError {} pub trait Rule { fn allows(&self, item: &Item, quantity: u32) -> bool; } pub struct MaxQuantity(pub u32); impl Rule for MaxQuantity { fn allows(&self, _item: &Item, quantity: u32) -> bool { quantity <= self.0 } } #[derive(Debug, PartialEq, Eq)] pub enum Outcome { Applied, Replayed, } pub struct Ledger { stock: BTreeMap<Item, u32>, receipts: BTreeMap<u32, Vec<Change>>, rule: Box<dyn Rule>, max_items: usize, max_receipts: usize, } impl Ledger { pub fn new(rule: Box<dyn Rule>, max_items: usize, max_receipts: usize) -> Self { Self { stock: BTreeMap::new(), receipts: BTreeMap::new(), rule, max_items, max_receipts } } pub fn apply(&mut self, batch: &Batch) -> Result<Outcome, ApplyError> { if let Some(previous) = self.receipts.get(&batch.id()) { return if previous == batch.changes() { Ok(Outcome::Replayed) } else { Err(ApplyError::RetryConflict) }; } if self.receipts.len() >= self.max_receipts { return Err(ApplyError::ReceiptLimit); } let mut staged = self.stock.clone(); for change in batch.changes() { let old = i64::from(*staged.get(change.item()).unwrap_or(&0)); let next = old.checked_add(change.delta()).ok_or(ApplyError::Arithmetic)?; let next = u32::try_from(next).map_err(|_| ApplyError::Quantity)?; if !self.rule.allows(change.item(), next) { return Err(ApplyError::Policy); } staged.insert(change.item().clone(), next); if staged.len() > self.max_items { return Err(ApplyError::ItemLimit); } } self.stock = staged; self.receipts.insert(batch.id(), batch.changes().to_vec()); Ok(Outcome::Applied) } pub fn entries(&self) -> impl Iterator<Item = (&Item, u32)> { self.stock.iter().map(|(item, quantity)| (item, *quantity)) } pub fn receipt_count(&self) -> usize { self.receipts.len() } } use crate::types::{Batch, Change, Draft, Item, ValidationError, MAX_CHANGES}; use std::fmt; use std::io::{self, BufRead, Read}; pub const MAX_LINE_BYTES: usize = 256; #[derive(Debug)] pub enum ParseError { Syntax, Number, Validation(ValidationError), } impl fmt::Display for ParseError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Syntax => formatter.write_str("use ID item:delta;item:delta"), Self::Number => formatter.write_str("invalid batch ID or delta"), Self::Validation(error) => write!(formatter, "{error}"), } } } impl std::error::Error for ParseError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Self::Validation(error) => Some(error), _ => None, } } } impl From<ValidationError> for ParseError { fn from(error: ValidationError) -> Self { Self::Validation(error) } } pub fn parse(text: &str) -> Result<Batch, ParseError> { let text = text.trim(); let (id, body) = text.split_once(char::is_whitespace).ok_or(ParseError::Syntax)?; let id = id.parse::<u32>().map_err(|_| ParseError::Number)?; let mut changes = Vec::new(); for part in body.split(';') { if changes.len() == MAX_CHANGES { return Err(ValidationError::BatchSize.into()); } let (item, delta) = part.trim().split_once(':').ok_or(ParseError::Syntax)?; let item = Item::try_from(item)?; let delta = delta.trim().parse::<i64>().map_err(|_| ParseError::Number)?; changes.push(Change::new(item, delta)?); } Ok(Draft { id, changes }.validate()?) } pub fn read_line(input: &mut impl BufRead) -> io::Result<Option<String>> { let mut bytes = Vec::new(); let count = input.take((MAX_LINE_BYTES + 1) as u64).read_until(b'\n', &mut bytes)?; if count == 0 { return Ok(None); } if count > MAX_LINE_BYTES { return Err(io::Error::new(io::ErrorKind::InvalidData, "line exceeds 256 bytes")); } let line = String::from_utf8(bytes) .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "input must be UTF-8"))?; Ok(Some(line)) } use crate::codec; use crate::ledger::{Ledger, MaxQuantity}; use std::io::{self, BufRead, Write}; pub fn run(mut input: impl BufRead, mut output: impl Write) -> io::Result<()> { let mut ledger = Ledger::new(Box::new(MaxQuantity(1000)), 32, 32); let mut line_number = 0; while let Some(line) = codec::read_line(&mut input)? { line_number += 1; if line.trim().is_empty() { continue; } match codec::parse(&line) { Ok(batch) => match ledger.apply(&batch) { Ok(outcome) => writeln!(output, "Batch {}: {outcome:?}", batch.id())?, Err(error) => writeln!(output, "Line {line_number}: {error}")?, }, Err(error) => writeln!(output, "Line {line_number}: {error}")?, } } writeln!(output, "Stock")?; for (item, quantity) in ledger.entries() { writeln!(output, "{}={quantity}", item.as_str())?; } writeln!(output, "Receipts: {}", ledger.receipt_count())?; output.flush() } hello 0 bolt:1 1 bolt:0 1 bolt:1001 1 bolt:1000 2 bolt:-1001
Text
Line 1: use ID item:delta;item:delta
Line 2: batch ID must be positive
Line 3: delta must be nonzero
Line 4: quantity rejected by policy
Batch 1: Applied
Line 6: quantity must fit a nonnegative u32
Stock
bolt=1000
Receipts: 1

Line 1 fails in the parser, before any types are built. Lines 2 and 3 parse as text but fail validation of the ID and the change. Line 4 is a perfectly valid batch that the ledger's MaxQuantity(1000) rule rejects, which leaves ID 1 free for line 5 to use at the exact boundary of 1000. Line 6 would take the stock below zero. Every rejected line left the stock exactly as it was.

Read the outcome, then the state

For every line you change, predict two things: the message, and what the final Stock section will show. A correct message with the wrong final stock is the bug this whole course has been guarding against.

The next lesson opens the source tabs and finds the line of code responsible for each of these guarantees.

Was this article helpful?

Your response is saved on this device.