02 components
Core Components
1. MongoConnectionManager
Manages MongoDB connections with async lifecycle. Methods:
connect(uri, db_name, **kwargs)- Connect to MongoDBdisconnect()- Close connectionget_database()- Get current database instanceget_client()- Get current client instancelifespan(uri, db_name, **kwargs)- Context manager for FastAPI lifespan
2. BaseDocument
Base model for all MongoDB documents. Provides:
id(aliased to_id) - ObjectIdcreated_at- Auto-generated timestampupdated_at- Auto-updated timestamp
3. BaseRepository[T]
Generic repository with CRUD operations:
create(data: T) -> Tget_by_id(id: str | ObjectId) -> Optional[T]get_many(filter, skip, limit, sort) -> List[T]update(id, data: Dict) -> Optional[T]delete(id) -> boolcount(filter) -> int
4. TransactionManager
Handles multi-document transactions:
start_session()- Context manager for transactionsexecute_transaction(operations)- Execute multiple operations atomically
5. ModelRegistry
Register and initialize models:
register(collection_name, model, indexes)- Register a modelinitialize_all()- Create all indexesget_model(collection_name)- Get registered modellist_collections()- List all registered collections
6. Cache Backend
6.1 CacheBackend (abstract)
- Defines the async interface for cache operations:
get,set,delete,exists,clear_pattern,get_stats,initialize,shutdown. - Provides
CacheStatsfor hit/miss/size metrics andCircularReferenceErrorfor cycle detection.
6.2 CacheConfig
- Dataclass to configure caching (
enabled,backend,redis_client,default_ttl,max_entries,key_prefix,cleanup_interval).
6.3 InMemoryCacheBackend
- In‑process cache using an LRU
OrderedDictand a TTL heap. - Background task periodically evicts expired entries.
6.4 RedisCacheBackend
- Distributed cache based on
redis.asyncio. - JSON serialisation, optional pub/sub invalidation.
6.5 CachedBaseRepository[T]
- Extends
BaseRepositorywith transparent ID‑based caching. - Methods:
get_by_id– cache‑first lookup.create– stores newly created doc in cache.update/delete– invalidate or refresh cache.warm_cache(ids)– pre‑load a list of IDs.invalidate_cache(id)– manual invalidation.
7. Population Engine
7.1 PopulateRule
- Dataclass defining a population rule:
field_name,collection_name,ref_field, optionalnested_rules,max_depth,filter,projection.
7.2 PopulationEngine
- Recursively resolves references according to
PopulateRulelist. - Detects circular references and raises
CircularReferenceError. - Supports per‑rule depth limits, filters and projections.
7.3 PopulatingRepository[T]
- Extends
BaseRepositoryto automatically populate related documents. - Accepts an optional
PopulationEngineand a list ofPopulateRule. - Provides
_populateand_depopulatehelpers used inget_by_idand elsewhere.