o
    i
                     @  s   d Z ddl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mZ ddlmZ dd	lmZmZ ed
ZdddZdddZd ddZdS )!z:Request context builder for the SaaS gateway runtime flow.    )annotations)Path)uuid4)Request)select)Session)get_control_plane_engine)	TenantAppTenantLimitz/var/www/html/flask_serverrequestr   tenant_datadict[str, str]returndict[str, object]c              
   C  s  | j dpd ptt }| j dpd }|std| j dp&d p*d}|dp8|dp8|d	 }td
 d | }td d | }t }t|dd}	t	|	|d	 |d}
t
|	|d	 |d}W d   n1 sow   Y  |||dp|dt|t||||
|d	S )z?Build a normalized request context for downstream app handlers.zX-Request-ID zX-App-IDzMissing X-App-ID headerz	X-User-IDNstorage_keyslug	tenant_idstoragetenantslogsT)future)r   app_iddb_name)	
request_idtenantdbr   r   r   user_idlimits
app_config)headersgetstripstrr   
ValueErrorBASE_DIRr   r   _load_limits_load_app_config)r   r   r   r   r   
tenant_keystorage_path	logs_pathenginesessionr   r    r-   #platform/gateway/request_context.pybuild_request_context   s.   r/   r,   r   r   r#   r   dict[str, dict[str, object]]c                C  sd   t ttj|k}| |  }i }|D ]}|jd |fvr!q|j|j	|j
|jd||j< q|S )N)limit_valuewindow_secondsoverage_policyr   )r   r
   wherer   executescalarsallr   r1   r2   r3   
limit_name)r,   r   r   stmtrecordsscopedrecordr-   r-   r.   r&   2   s   r&   c                C  sV   t ttj|ktj|kd}| | }|d u r ddiS t|j	|j
p(i dS )N   enabledF)r>   config)r   r	   r4   r   r   limitr5   scalar_one_or_nonebool
is_enabledconfig_json)r,   r   r   r9   r<   r-   r-   r.   r'   C   s   r'   N)r   r   r   r   r   r   )r,   r   r   r#   r   r#   r   r0   )r,   r   r   r#   r   r#   r   r   )__doc__
__future__r   pathlibr   uuidr   flaskr   
sqlalchemyr   sqlalchemy.ormr   config.control_planer   platform.tenants.modelsr	   r
   r%   r/   r&   r'   r-   r-   r-   r.   <module>   s    

