core.container.infrastructure¶
src.core.container.infrastructure
¶
Infrastructure dependency factories.
Application-scoped singletons for core infrastructure services: - Cache (Redis) - Secrets (env/AWS) - Encryption (AES-256-GCM) - Database (PostgreSQL) - Password hashing (bcrypt) - Token generation (JWT) - Email (stub/AWS SES) - Rate limiting (token bucket) - Logging (console/CloudWatch)
Reference
See docs/architecture/dependency-injection-architecture.md for complete patterns and usage examples.
Classes¶
Functions¶
get_cache_keys
cached
¶
Get cache keys utility singleton (app-scoped).
Returns CacheKeys instance for consistent cache key construction. Uses configurable prefix from settings.
Returns:
| Type | Description |
|---|---|
CacheKeys
|
CacheKeys utility for key construction. |
Usage
Application Layer (direct use)¶
keys = get_cache_keys() cache_key = keys.user(user_id)
Presentation Layer (FastAPI Depends)¶
from fastapi import Depends keys: CacheKeys = Depends(get_cache_keys)
Source code in src/core/container/infrastructure.py
get_cache_metrics
cached
¶
Get cache metrics singleton (app-scoped).
Returns CacheMetrics instance for tracking cache hit/miss/error rates. Metrics are in-memory and thread-safe.
Returns:
| Type | Description |
|---|---|
CacheMetrics
|
CacheMetrics instance for metrics tracking. |
Usage
Application Layer (direct use)¶
metrics = get_cache_metrics() metrics.record_hit("user") stats = metrics.get_stats("user")
Presentation Layer (FastAPI Depends)¶
from fastapi import Depends metrics: CacheMetrics = Depends(get_cache_metrics)
Source code in src/core/container/infrastructure.py
get_cache
cached
¶
Get cache client singleton (app-scoped).
Returns RedisAdapter with connection pooling. Connection pool is shared across entire application.
Returns:
| Type | Description |
|---|---|
CacheProtocol
|
Cache client implementing CacheProtocol. |
Usage
Application Layer (direct use)¶
cache = get_cache() await cache.set("key", "value")
Presentation Layer (FastAPI Depends)¶
from fastapi import Depends cache: CacheProtocol = Depends(get_cache)
Source code in src/core/container/infrastructure.py
get_secrets
cached
¶
Get secrets manager singleton (app-scoped).
Container owns factory logic - decides which adapter based on SECRETS_BACKEND. This follows the Composition Root pattern (industry best practice).
Returns correct adapter based on SECRETS_BACKEND environment variable
- 'env': EnvAdapter (local development)
- 'aws': AWSAdapter (production)
Returns:
| Type | Description |
|---|---|
SecretsProtocol
|
Secrets manager implementing SecretsProtocol. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If SECRETS_BACKEND is unsupported or required env vars missing. |
Usage
Application Layer (direct use)¶
secrets = get_secrets() db_url = secrets.get_secret("database/url")
Presentation Layer (FastAPI Depends)¶
from fastapi import Depends secrets: SecretsProtocol = Depends(get_secrets)
Source code in src/core/container/infrastructure.py
get_encryption_service
cached
¶
Get encryption service singleton (app-scoped).
Returns EncryptionService for encrypting/decrypting provider credentials. Uses settings.encryption_key for AES-256-GCM encryption.
Returns:
| Type | Description |
|---|---|
EncryptionService
|
EncryptionService instance. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If encryption key is invalid. |
Usage
Application Layer (direct use)¶
encryption = get_encryption_service() result = encryption.encrypt({"access_token": "..."})
Presentation Layer (FastAPI Depends)¶
from fastapi import Depends encryption: EncryptionService = Depends(get_encryption_service)
Source code in src/core/container/infrastructure.py
get_database
cached
¶
Get database manager singleton (app-scoped).
Returns Database instance with connection pool. Use get_db_session() for per-request sessions.
Returns:
| Type | Description |
|---|---|
Database
|
Database manager instance. |
Note
This is rarely used directly. Prefer get_db_session() for sessions.
Usage
Application Layer (direct use)¶
db = get_database()
Presentation Layer - use get_db_session() instead¶
Source code in src/core/container/infrastructure.py
get_db_session
async
¶
Get database session (request-scoped).
Creates new session per request with automatic transaction management
- Commits on success
- Rolls back on exception
- Always closes session
Yields:
| Type | Description |
|---|---|
AsyncGenerator[AsyncSession, None]
|
Database session for request duration. |
Usage
Presentation Layer (FastAPI endpoint)¶
from fastapi import Depends from sqlalchemy.ext.asyncio import AsyncSession
@router.post("/users") async def create_user( session: AsyncSession = Depends(get_db_session) ): # Use session ...
Source code in src/core/container/infrastructure.py
get_audit_session
async
¶
Get audit session (request-scoped, independent lifecycle).
Creates separate session ONLY for audit logging with immediate commits to ensure audit logs persist regardless of request outcome.
CRITICAL: Audit logs MUST persist even when business transactions fail (PCI-DSS 10.2.4, SOC 2 CC6.1, GDPR Article 30 requirements).
Separate from get_db_session() to prevent audit logs from being lost when business transactions roll back.
Yields:
| Type | Description |
|---|---|
AsyncGenerator[AsyncSession, None]
|
Database session for audit operations only. |
See Also
docs/architecture/audit-trail-architecture.md Section 5.2 for complete audit session architecture.
Source code in src/core/container/infrastructure.py
get_audit
async
¶
Get audit trail adapter (request-scoped with separate session).
Creates audit adapter instance per request with SEPARATE audit session that commits immediately to ensure durability.
CRITICAL: Uses get_audit_session() (NOT get_db_session()) to ensure audit logs persist even when business transactions fail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audit_session
|
AsyncSession
|
Independent database session for audit operations. Injected via Depends(get_audit_session). |
Depends(get_audit_session)
|
Returns:
| Type | Description |
|---|---|
AuditProtocol
|
Audit adapter implementing AuditProtocol. |
See Also
docs/architecture/audit-trail-architecture.md Section 5.2 for complete audit session architecture and compliance impact.
Source code in src/core/container/infrastructure.py
get_password_service
cached
¶
Get password hashing service singleton (app-scoped).
Returns BcryptPasswordService with cost factor 12 (~250ms per hash). Service instance is shared across entire application.
Returns:
| Type | Description |
|---|---|
PasswordHashingProtocol
|
Password hashing service implementing PasswordHashingProtocol. |
Reference
- docs/architecture/authentication-architecture.md (Lines 853-875)
Source code in src/core/container/infrastructure.py
get_token_service
cached
¶
Get JWT token service singleton (app-scoped).
Returns JWTService with HMAC-SHA256 and configurable expiration. Service instance is shared across entire application.
Configuration
- access_token_expire_minutes: Configurable via settings (default: 30)
- For stricter security, reduce to 15 minutes via environment variable
Returns:
| Type | Description |
|---|---|
TokenGenerationProtocol
|
Token generation service implementing TokenGenerationProtocol. |
Reference
- docs/architecture/authentication-architecture.md (Lines 131-173)
- F6.5 Security Audit Item 2: Config/Container alignment
Source code in src/core/container/infrastructure.py
get_email_service
cached
¶
Get email service singleton (app-scoped).
Container owns factory logic - decides which adapter based on ENVIRONMENT. This follows the Composition Root pattern (industry best practice).
Returns correct adapter based on environment
- development/testing/ci: StubEmailService (logs to console)
- production: AWSEmailService (real AWS SES)
Returns:
| Type | Description |
|---|---|
EmailProtocol
|
Email service implementing EmailProtocol. |
Reference
- docs/architecture/authentication-architecture.md (Lines 272-278)
Source code in src/core/container/infrastructure.py
get_rate_limit
cached
¶
Get rate limiter singleton (app-scoped).
Creates TokenBucketAdapter with: - RedisStorage for atomic token bucket operations - Centralized rules configuration from RATE_LIMIT_RULES - Event bus for domain event publishing - Logger for structured logging
Fail-Open Design
All rate limit operations return allowed=True on infrastructure failures. Rate limiting should NEVER cause denial of service.
Returns:
| Type | Description |
|---|---|
RateLimitProtocol
|
Rate limiter implementing RateLimitProtocol. |
Reference
- docs/architecture/rate-limit-architecture.md
Source code in src/core/container/infrastructure.py
get_logger
cached
¶
Return the application-scoped logger singleton.
Adapter selection is centralized here (composition root): - development: ConsoleAdapter (human-readable) - testing/ci: ConsoleAdapter (JSON) - production: CloudWatchAdapter (AWS CloudWatch)
Returns:
| Name | Type | Description |
|---|---|---|
LoggerProtocol |
LoggerProtocol
|
Logger instance implementing the protocol. |
Source code in src/core/container/infrastructure.py
get_session_cache
cached
¶
Get session cache singleton (app-scoped).
Returns RedisSessionCache for session storage with user indexing. Uses shared Redis connection pool.
Returns:
| Type | Description |
|---|---|
SessionCache
|
Session cache implementing SessionCache protocol. |
Source code in src/core/container/infrastructure.py
get_provider_connection_cache
cached
¶
Get provider connection cache singleton (app-scoped).
Returns RedisProviderConnectionCache for connection storage. Uses shared Redis connection pool.
Returns:
| Type | Description |
|---|---|
ProviderConnectionCache
|
Provider connection cache implementing ProviderConnectionCache protocol. |
Source code in src/core/container/infrastructure.py
get_device_enricher
cached
¶
Get device enricher singleton (app-scoped).
Returns UserAgentDeviceEnricher for parsing user agent strings.
Returns:
| Type | Description |
|---|---|
DeviceEnricher
|
Device enricher implementing DeviceEnricher protocol. |
Source code in src/core/container/infrastructure.py
get_location_enricher
cached
¶
Get location enricher singleton (app-scoped).
Returns IPLocationEnricher for IP geolocation.
Returns:
| Type | Description |
|---|---|
LocationEnricher
|
Location enricher implementing LocationEnricher protocol. |
Source code in src/core/container/infrastructure.py
get_refresh_token_service
cached
¶
Get refresh token service singleton (app-scoped).
Returns RefreshTokenService for generating and verifying refresh tokens.
Returns:
| Type | Description |
|---|---|
RefreshTokenServiceProtocol
|
Refresh token service implementing RefreshTokenServiceProtocol. |
Source code in src/core/container/infrastructure.py
get_password_reset_token_service
cached
¶
Get password reset token service singleton (app-scoped).
Returns PasswordResetTokenService for generating password reset tokens.
Returns:
| Type | Description |
|---|---|
PasswordResetTokenServiceProtocol
|
Password reset token service implementing PasswordResetTokenServiceProtocol. |
Source code in src/core/container/infrastructure.py
get_provider_factory
cached
¶
Get provider factory singleton (app-scoped).
Returns ProviderFactory for runtime provider resolution. Used by handlers that need to resolve providers dynamically.
Returns:
| Type | Description |
|---|---|
ProviderFactoryProtocol
|
Provider factory implementing ProviderFactoryProtocol. |
Source code in src/core/container/infrastructure.py
get_jobs_monitor
cached
¶
Get background jobs monitor singleton (app-scoped).
Returns JobsMonitor for querying the dashtam-jobs background worker service. Uses JOBS_REDIS_URL if configured, otherwise falls back to main REDIS_URL.
The jobs monitor allows the API to check job queue health and status without depending on dashtam-jobs code.
Returns:
| Type | Description |
|---|---|
JobsMonitor
|
JobsMonitor instance for job queue monitoring. |
Usage
Application Layer (direct use)¶
monitor = get_jobs_monitor() health = await monitor.check_health()
Presentation Layer (FastAPI Depends)¶
from fastapi import Depends monitor: JobsMonitor = Depends(get_jobs_monitor)