State Management
info
The State Manager provides read access to current state and query capabilities for your domain entities.
Overview
The State Manager (statemgr) is the primary interface for reading domain state. It provides:
- Entity fetching by ID
- Querying with filters
- Transaction management
- Read-only access to current state
Basic Operations
Fetch Entity
Fetch a single entity by resource and identifier:
# Fetch by ID
user = await domain.statemgr.fetch('user', user_id)
# Fetch with transaction
async with domain.statemgr.transaction():
user = await domain.statemgr.fetch('user', user_id)
Find Entities
Find entities matching criteria:
# Find all matching
users = await domain.statemgr.find('user', active=True)
# Find one
user = await domain.statemgr.find_one('user', email='john@example.com')
Query Entities
Build complex queries:
from fluvius.query import QueryManager
query_manager = QueryManager()
query = query_manager.build_query('user', {
'filter': {
'and': [
{'active': True},
{'created_at': {'gte': '2024-01-01'}}
]
},
'sort': [{'field': 'name', 'order': 'asc'}],
'limit': 10
})
users = await domain.statemgr.query(query)
Data Query Decorator
Use the data_query decorator for custom query methods:
from fluvius.domain import data_query
class UserDomain(Domain):
@data_query('user-by-email')
async def find_user_by_email(self, email: str):
return await self.statemgr.find_one('user', email=email)
Transactions
State Manager supports transactions:
# Use transaction context
async with domain.statemgr.transaction():
user1 = await domain.statemgr.fetch('user', user_id_1)
user2 = await domain.statemgr.fetch('user', user_id_2)
# All reads are within the same transaction
Read-Only Access
The State Manager provides read-only access:
- No mutations: Cannot modify state directly
- Consistent reads: Always reads current state
- Transaction isolation: Reads are isolated within transactions
Integration with Aggregates
Aggregates can access state through the State Manager:
class UserAggregate(Aggregate):
async def update_user(self, name: str):
# Fetch current state
user = await self.statemgr.fetch('user', self.aggroot.identifier)
# Update state
updated = await self.statemgr.update(user, name=name)
return updated
Best Practices
- Use for Reads: State Manager is for reading, not writing
- Transactions: Use transactions for consistent reads
- Caching: Consider caching for frequently accessed data
- Queries: Use query builder for complex filtering
- Error Handling: Handle cases where entities don't exist
Next Steps
- Learn about Query Module
- Read the Domain API Reference
- Check out Examples