Skip to content

02 components

Core Components

1. MongoConnectionManager

Manages MongoDB connections with async lifecycle. Methods:

  • connect(uri, db_name, **kwargs) - Connect to MongoDB
  • disconnect() - Close connection
  • get_database() - Get current database instance
  • get_client() - Get current client instance
  • lifespan(uri, db_name, **kwargs) - Context manager for FastAPI lifespan

2. BaseDocument

Base model for all MongoDB documents. Provides:

  • id (aliased to _id) - ObjectId
  • created_at - Auto-generated timestamp
  • updated_at - Auto-updated timestamp

3. BaseRepository[T]

Generic repository with CRUD operations:

  • create(data: T) -> T
  • get_by_id(id: str | ObjectId) -> Optional[T]
  • get_many(filter, skip, limit, sort) -> List[T]
  • update(id, data: Dict) -> Optional[T]
  • delete(id) -> bool
  • count(filter) -> int

4. TransactionManager

Handles multi-document transactions:

  • start_session() - Context manager for transactions
  • execute_transaction(operations) - Execute multiple operations atomically

5. ModelRegistry

Register and initialize models:

  • register(collection_name, model, indexes) - Register a model
  • initialize_all() - Create all indexes
  • get_model(collection_name) - Get registered model
  • list_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 CacheStats for hit/miss/size metrics and CircularReferenceError for 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 OrderedDict and 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 BaseRepository with 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, optional nested_rules, max_depth, filter, projection.

7.2 PopulationEngine

  • Recursively resolves references according to PopulateRule list.
  • Detects circular references and raises CircularReferenceError.
  • Supports per‑rule depth limits, filters and projections.

7.3 PopulatingRepository[T]

  • Extends BaseRepository to automatically populate related documents.
  • Accepts an optional PopulationEngine and a list of PopulateRule.
  • Provides _populate and _depopulate helpers used in get_by_id and elsewhere.