o
    ?7i2                     @   s   d Z ddlmZmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlZeeZde	d	efd
dZd	efddZe Zdd ZdS )z-
Rate limiting middleware for API endpoints.
    )Limiter_rate_limit_exceeded_handler)get_remote_address)RateLimitExceeded)Request)settingsNrequestreturnc                 C   s   | j dkrdS t| S )z
    Custom key function that skips rate limiting for OPTIONS requests.

    Args:
        request: FastAPI request object

    Returns:
        str: Client identifier for rate limiting
    OPTIONSskip)methodr   )r    r   A/lsinfo/ai/hellotax_ai/base_platform/app/middleware/rate_limit.pycustom_key_func   s   
r   c               
   C   s^  d} t tdr5tjr5ztj} tdtj  W n ty4 } ztd|  d} W Y d}~njd}~ww t tdrtjrz;ttdd}ttdd	}|r]d
| dtj dtj	 d| } ndtj dtj	 d| } tdtj dtj	  W n! ty } ztd|  d} W Y d}~n
d}~ww td t
ttj dtj dgtj| d}|S )zl
    Create and configure rate limiter instance.

    Returns:
        Limiter: Configured rate limiter
    z	memory://	REDIS_URLzUsing Redis for rate limiting: zEFailed to configure Redis for rate limiting, falling back to memory: N
REDIS_HOSTREDIS_PASSWORDREDIS_DBr   z	redis://:@:/zredis://zQRedis not configured, using in-memory rate limiting (not suitable for production)z/minutez/hour)key_funcdefault_limitsenabledstorage_uri)hasattrr   r   loggerinfo	Exceptionwarningr   getattr
REDIS_PORTr   r   RATE_LIMIT_PER_MINUTERATE_LIMIT_PER_HOURRATE_LIMIT_ENABLED)r   eredis_passwordredis_dblimiterr   r   r   get_limiter   sB   "


	r)   c                 C   s"   t jrt| j_| tt dS dS )zk
    Setup rate limiting for FastAPI application.

    Args:
        app: FastAPI application instance
    N)r   r$   r(   stateadd_exception_handlerr   r   )appr   r   r   setup_rate_limitingP   s   r-   )__doc__slowapir   r   slowapi.utilr   slowapi.errorsr   fastapir   
app.configr   logging	getLogger__name__r   strr   r)   r(   r-   r   r   r   r   <module>   s    
/