Configuration
Configure the State module inconfig.yaml:
config.yaml
Configuration Options
- KvStore (Default)
- Custom Adapter
File-based persistent storage:Or in-memory (development only):
State Concepts
State is organized by scope and key:- Scope: Namespace for related data (e.g., ‘users’, ‘config’)
- Key: Unique identifier within scope (e.g., ‘user_123’, ‘app_settings’)
State Functions
Set
Store a value in state:Get
Retrieve a value from state:Delete
Remove a value from state:Update (Atomic)
Atomically update a value with multiple operations:List
List all keys in a scope:List Groups
List all scopes (groups):Update Operations
Atomic update operations available:State Triggers
React to state changes automatically:index.ts
Event Format
State triggers receive events with this structure:Conditional Triggers
Filter state events with conditions:Example: User Management
index.ts
Example: Configuration Management
Example: Caching with TTL
Scope Patterns
Recommended scope naming conventions:- users - User profiles and data
- config - Application configuration
- cache - Temporary cached data
- sessions - User session data
- analytics - Analytics counters and stats
- features - Feature flags
Performance Considerations
- Use scopes to organize data logically
- Use atomic updates for concurrent modifications
- Implement caching for frequently accessed data
- Use triggers for async processing instead of synchronous updates
- Consider TTL patterns for temporary data
Data Persistence
With the KvStore adapter usingfile_based storage:
- Data persists across restarts
- Stored in the configured
file_path - Automatically saved at intervals (configurable in kv_server module)
Best Practices
- Use Scopes: Organize data into logical scopes
- Atomic Updates: Use
state.updatefor concurrent modifications - Triggers: React to changes asynchronously
- Error Handling: Always handle missing keys gracefully
- TTL Pattern: Implement expiration for temporary data
Migration from Other Storage
Migrating from another storage system:Source Code Reference
- Module:
src/modules/state/state.rs:36 - State functions:
src/modules/state/state.rs:254 - Trigger invocation:
src/modules/state/state.rs:110 - State adapter trait:
src/modules/state/adapters/mod.rs