📦 EqualifyEverything / equalify-reflow

📄 dependencies.py · 274 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274"""Dependency injection for shared clients and services."""

from collections.abc import AsyncGenerator
from functools import lru_cache
from typing import Any

import boto3
import redis.asyncio as redis
from botocore.config import Config
from fastapi import Depends

from .config import settings
from .services.document_processing_service import DocumentProcessingService
from .services.job_service import JobService
from .services.queue_service import QueueService
from .services.rate_limit_service import RateLimitService
from .services.s3_cleanup_service import S3CleanupService
from .services.s3_url_service import S3URLService
from .services.storage_service import StorageService

# Singleton S3 client for connection reuse
_s3_client = None


@lru_cache
def _get_s3_client_singleton() -> Any:
    """Create singleton S3 client for connection reuse across requests.

    In production AWS: Uses IAM role credentials (no keys needed)
    In local dev: Uses Floci endpoint with test credentials
    """
    retry_config = Config(
        retries={
            "mode": "adaptive",
            "max_attempts": 3,
        },
        connect_timeout=10,
        read_timeout=60,
        max_pool_connections=50,
    )

    # boto3 automatically reads AWS_ENDPOINT_URL_S3 from environment (points
    # at Floci in dev/CI). In production, it uses IAM role credentials.

    # Clear empty AWS_PROFILE to prevent boto3 profile lookup error
    import os

    if os.environ.get("AWS_PROFILE") == "":
        del os.environ["AWS_PROFILE"]

    return boto3.client(
        service_name="s3",
        region_name=settings.aws_region,
        config=retry_config,
    )


# Client dependencies with proper resource cleanup
async def get_s3_client() -> AsyncGenerator[Any, None]:
    """Get S3 client (Floci or AWS) with optimized retry configuration.

    Configures boto3 with:
    - Adaptive retry mode (intelligent throttling and backoff)
    - Connection pooling (50 connections)
    - Reasonable timeouts (10s connect, 60s read)

    Yields:
        Configured boto3 S3 client with production-ready settings

    Note:
        This returns a singleton client to enable connection pooling
        and circuit breaker state persistence across requests.
    """
    yield _get_s3_client_singleton()


# Singleton Redis connection pool for connection reuse across requests
_redis_pool: redis.ConnectionPool | None = None


def _get_redis_pool() -> redis.ConnectionPool:
    """Get or create singleton Redis connection pool.

    Returns a shared connection pool that persists across requests,
    eliminating per-request connection overhead.

    Returns:
        Singleton Redis ConnectionPool instance
    """
    global _redis_pool
    if _redis_pool is None:
        _redis_pool = redis.ConnectionPool.from_url(
            settings.redis_url,
            decode_responses=True,
            max_connections=settings.redis_max_connections,
        )
    return _redis_pool


async def get_redis_client() -> AsyncGenerator[Any, None]:
    """Get Redis client from singleton connection pool.

    Yields:
        Redis client using shared connection pool

    Note:
        Uses singleton connection pool for efficient connection reuse.
        Connections return to pool automatically - no explicit close needed.
    """
    client = redis.Redis(connection_pool=_get_redis_pool())
    yield client
    # No close - connection returns to pool automatically


# Singleton StorageService for circuit breaker persistence
@lru_cache
def _get_storage_service_singleton() -> StorageService:
    """Create singleton StorageService for circuit breaker persistence."""
    return StorageService(
        s3_client=_get_s3_client_singleton(),
        temp_bucket=settings.s3_temp_bucket,
        results_bucket=settings.s3_results_bucket,
    )


# Singleton S3URLService
@lru_cache
def _get_s3_url_service_singleton() -> S3URLService:
    """Create singleton S3URLService for URL generation."""
    return S3URLService(
        s3_client=_get_s3_client_singleton(),
        temp_bucket=settings.s3_temp_bucket,
        results_bucket=settings.s3_results_bucket,
    )


# Singleton S3CleanupService
@lru_cache
def _get_s3_cleanup_service_singleton() -> S3CleanupService:
    """Create singleton S3CleanupService for cleanup operations."""
    return S3CleanupService(
        s3_client=_get_s3_client_singleton(),
        temp_bucket=settings.s3_temp_bucket,
    )


# Service dependencies
async def get_storage_service() -> StorageService:
    """Get storage service instance.

    Returns:
        Singleton StorageService instance with persistent circuit breakers

    Note:
        This returns a singleton service to ensure:
        - Circuit breaker state persists across requests
        - S3 connection pooling is effective
        - Health checks are fast and reliable

        In FastAPI routes, use: storage_service: StorageService = Depends(get_storage_service)

        For workers, do NOT use this function. Instead:
        s3_client = await anext(get_s3_client())
        storage_service = StorageService(s3_client=s3_client, ...)
    """
    return _get_storage_service_singleton()


async def get_s3_url_service() -> S3URLService:
    """Get S3 URL service instance.

    Returns:
        Singleton S3URLService instance for URL generation

    Note:
        In FastAPI routes, use: url_service: S3URLService = Depends(get_s3_url_service)

        For workers, do NOT use this function. Instead:
        s3_client = await anext(get_s3_client())
        url_service = S3URLService(s3_client=s3_client, ...)
    """
    return _get_s3_url_service_singleton()


async def get_s3_cleanup_service() -> S3CleanupService:
    """Get S3 cleanup service instance.

    Returns:
        Singleton S3CleanupService instance for cleanup operations

    Note:
        In FastAPI routes, use: cleanup: S3CleanupService = Depends(get_s3_cleanup_service)

        For workers, do NOT use this function. Instead:
        s3_client = await anext(get_s3_client())
        cleanup = S3CleanupService(s3_client=s3_client, ...)
    """
    return _get_s3_cleanup_service_singleton()


async def get_queue_service(redis_client: Any = Depends(get_redis_client)) -> QueueService:
    """Get queue service instance.

    Args:
        redis_client: Redis client (auto-injected by FastAPI Depends)

    Returns:
        Configured QueueService instance

    Note:
        In FastAPI routes, use: queue_service: QueueService = Depends(get_queue_service)

        For workers, do NOT use this function. Instead:
        redis_client = await anext(get_redis_client())
        queue_service = QueueService(redis_client=redis_client)
    """
    return QueueService(redis_client=redis_client)


async def get_job_service(redis_client: Any = Depends(get_redis_client)) -> JobService:
    """Get job service instance.

    Args:
        redis_client: Redis client (auto-injected by FastAPI Depends)

    Returns:
        Configured JobService instance

    Note:
        In FastAPI routes, use: job_service: JobService = Depends(get_job_service)

        For workers, do NOT use this function. Instead:
        redis_client = await anext(get_redis_client())
        job_service = JobService(redis_client=redis_client)
    """
    return JobService(redis_client=redis_client)


async def get_rate_limit_service(
    redis_client: Any = Depends(get_redis_client),
) -> AsyncGenerator[RateLimitService, None]:
    """Get rate limit service instance.

    Args:
        redis_client: Redis client (auto-injected by FastAPI Depends)

    Yields:
        Configured RateLimitService instance

    Note:
        In FastAPI routes, use: rate_limiter: RateLimitService = Depends(get_rate_limit_service)

        For workers, do NOT use this function. Instead:
        redis_client = await anext(get_redis_client())
        rate_limiter = RateLimitService(redis=redis_client)
    """
    # RateLimitService expects 'redis' parameter, not 'redis_client'
    yield RateLimitService(redis=redis_client)


async def get_document_processing_service(
    redis_client: Any = Depends(get_redis_client),
    storage: StorageService = Depends(get_storage_service),
    s3_url: S3URLService = Depends(get_s3_url_service),
) -> DocumentProcessingService:
    """Get document processing service instance."""
    return DocumentProcessingService(
        redis_client=redis_client,
        storage_service=storage,
        s3_url_service=s3_url,
    )