Stillwater
A Rust library for pragmatic effect composition and validation, emphasizing the pure core, imperative shell pattern.
Philosophy
Stillwater embodies a simple idea:
- Still = Pure functions (unchanging, referentially transparent)
- Water = Effects (flowing, performing I/O)
Keep your business logic pure and calm like still water. Let effects flow at the boundaries.
What Problems Does It Solve?
1. "I want ALL validation errors, not just the first one"
use Validation;
// Standard Result: stops at first error โ
let email = validate_email?; // Stops here
let age = validate_age?; // Never reached if email fails
// Stillwater: accumulates all errors โ
let user = all?;
// Returns: Err(vec![EmailError, AgeError, NameError])
2. "How do I validate that all items have the same type before combining?"
use validate_homogeneous;
use discriminant;
// Without validation: runtime panic ๐ฅ
let mixed = vec!;
// items.into_iter().reduce(|a, b| a.combine(b)) // PANIC!
// With validation: type-safe error accumulation โ
let result = validate_homogeneous;
match result
3. "How do I test code with database calls?"
use *;
// Pure business logic (no DB, easy to test)
// Effects at boundaries (mockable)
// Test with mock environment
async
4. "My errors lose context as they bubble up"
use *;
fetch_user
.context
.and_then
.context
.run.await?;
// Error output:
// Error: UserNotFound(12345)
// -> Loading user profile
// -> Processing user data
5. "I need clean dependency injection without passing parameters everywhere"
use *;
// Functions don't need explicit config parameters
# block_on;
6. "Retry logic is scattered and hard to test"
use ;
use Duration;
// Traditional approach: retry logic mixed with business logic โ
// - Can't test retry behavior without calling the API
// - Can't reuse the same policy across different operations
// - Hard to tune or modify without code changes
// Stillwater: Policy as Data โ
// Define retry policies as pure, composable, testable values
let api_policy = exponential
.with_max_retries
.with_max_delay
.with_jitter;
// Test the policy without any I/O
assert_eq!;
assert_eq!;
assert_eq!;
// Reuse the same policy across different effects
retry;
retry;
// Conditional retry: only retry transient failures
retry_if;
// Observability: hook into retry events for logging/metrics
retry_with_hooks;
Why "Policy as Data" matters:
- Testable: Test retry timing without mocks or network calls
- Reusable: One policy definition, many use sites
- Composable: Builder pattern for flexible configuration
- Inspectable: Query policy parameters before execution
- Safe: Enforces bounds (max_retries OR max_delay required)
Core Features
Validation<T, E>- Accumulate all errors instead of short-circuitingNonEmptyVec<T>- Type-safe non-empty collections with guaranteed head elementEffecttrait - Zero-cost effect composition following thefuturescrate pattern- Zero heap allocations by default
- Explicit
.boxed()when type erasure is needed - Returns
impl Effectfor optimal performance
- Parallel effect execution - Run independent effects concurrently
- Zero-cost:
par2(),par3(),par4()for heterogeneous effects - Boxed:
par_all(),race(),par_all_limit()for homogeneous collections
- Zero-cost:
- Retry and resilience - Policy-as-data approach: define retry policies as pure, testable values with exponential, linear, constant, and Fibonacci backoff strategies. Includes jitter (proportional, full, decorrelated), conditional retry with predicates, retry hooks for observability, and timeout support
- Traverse and sequence - Transform collections with
traverse()andsequence()for both validations and effects- Validate entire collections with error accumulation
- Process collections with effects using fail-fast semantics
- Reader pattern helpers - Clean dependency injection with
ask(),asks(), andlocal() Semigrouptrait - Associative combination of values- Extended implementations for
HashMap,HashSet,BTreeMap,BTreeSet,Option - Wrapper types:
First,Last,Intersectionfor alternative semantics
- Extended implementations for
Monoidtrait - Identity elements for powerful composition patterns- Testing utilities - Ergonomic test helpers
MockEnvbuilder for composing test environments- Assertion macros:
assert_success!,assert_failure!,assert_validation_errors! TestEffectwrapper for deterministic effect testing- Optional
proptestfeature for property-based testing
- Context chaining - Never lose error context
- Tracing integration - Instrument effects with semantic spans using the standard
tracingcrate - Zero-cost abstractions - Follows
futurescrate pattern: concrete types, no allocation by default - Works with
?operator - Integrates with Rust idioms - No heavy macros - Clear types, obvious behavior
Quick Start
use *;
// 1. Validation with error accumulation
// 2. Effect composition (zero-cost by default)
// 3. Run at application boundary
let env = AppEnv ;
let result = create_user.run.await?;
Why Stillwater?
Compared to existing solutions:
vs. frunk:
- โ Focused on practical use cases, not type-level programming
- โ Better documentation and examples
- โ Effect composition, not just validation
vs. monadic:
- โ No awkward macro syntax (
rdrdo! { ... }) - โ Zero-cost by default (follows
futurescrate pattern) - โ Idiomatic Rust, not Haskell port
vs. hand-rolling:
- โ Validation accumulation built-in
- โ Error context handling
- โ Testability patterns established
- โ Composable, reusable
What makes it "Rust-first":
- โ No attempt at full monad abstraction (impossible without HKTs)
- โ Works with
?operator viaTrytrait - โ Zero-cost via concrete types and monomorphization (like
futures) - โ Integrates with async/await
- โ Borrows checker friendly
- โ Clear error messages
Installation
Add to your Cargo.toml:
[]
= "0.8"
# Optional: async support
= { = "0.8", = ["async"] }
# Optional: tracing integration
= { = "0.8", = ["tracing"] }
# Optional: property-based testing
= { = "0.8", = ["proptest"] }
# Optional: multiple features
= { = "0.8", = ["async", "tracing", "proptest"] }
Examples
Run any example with cargo run --example <name>:
| Example | Demonstrates |
|---|---|
| form_validation | Validation error accumulation |
| homogeneous_validation | Type-safe validation for discriminated unions before combining |
| nonempty | NonEmptyVec type for guaranteed non-empty collections |
| user_registration | Effect composition and I/O separation |
| error_context | Error trails for debugging |
| data_pipeline | Real-world ETL pipeline |
| testing_patterns | Testing pure vs effectful code |
| reader_pattern | Reader pattern with ask(), asks(), and local() |
| validation | Validation type and error accumulation patterns |
| effects | Effect type and composition patterns |
| parallel_effects | Parallel execution with par_all, race, and par_all_limit |
| retry_patterns | Retry policies, backoff strategies, timeouts, and resilience patterns |
| io_patterns | IO module helpers for reading/writing |
| pipeline | Data transformation pipelines |
| traverse | Traverse and sequence for collections of validations and effects |
| monoid | Monoid and Semigroup traits for composition |
| extended_semigroup | Semigroup for HashMap, HashSet, Option, and wrapper types |
| tracing_demo | Tracing integration with semantic spans and context |
| boxing_decisions | When to use .boxed() vs zero-cost effects |
See examples/ directory for full code.
Production Readiness
Status: 0.8 - Production Ready for Early Adopters
- โ 295 unit tests passing (includes property-based tests)
- โ 122 documentation tests passing
- โ Zero clippy warnings
- โ Comprehensive examples (16 runnable examples)
- โ Full async support
- โ Homogeneous validation for type-safe combining
- โ Testing utilities with MockEnv and assertion macros
- โ CI/CD pipeline with security audits
This library is stable and ready for use. The 0.x version indicates the API may evolve based on community feedback.
Documentation
- ๐ User Guide - Comprehensive tutorials
- ๐ API Docs - Full API reference
- ๐ค FAQ - Common questions
- ๐๏ธ Design - Architecture and decisions
- ๐ญ Philosophy - Core principles
- ๐ฏ Patterns - Common patterns and recipes
- ๐ Comparison - vs other libraries
- ๐ Migration Guide - Upgrading from 0.10.x to 0.11.0
Migrating from Result
Already using Result everywhere? No problem! Stillwater integrates seamlessly:
// Your existing code works as-is
// Upgrade to accumulation when you need it
// Convert back to Result when needed
let result: = validation.into_result;
Start small, adopt progressively. Use Validation only where you need error accumulation.
Contributing
Contributions welcome! This is a young library with room to grow:
- ๐ Bug reports and feature requests via issues
- ๐ Documentation improvements
- ๐งช More examples and use cases
- ๐ก API feedback and design discussions
Before submitting PRs, please open an issue to discuss the change.
License
MIT ยฉ Glen Baker iepathos@gmail.com
"Like a still pond with water flowing through it, stillwater keeps your pure business logic calm and testable while effects flow at the boundaries."