o
    i                     @   s   d dl m Z mZ d dlm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mZmZmZ dd
lmZ defddZdefddZdefddZdS )    )datetimetimezone)
HTTPStatus)RequestResponse)HTTPException   )logger   )get_session_manager)SESSION_DISABLED_ERROR_DETAILSESSION_DISABLED_LOG_MESSAGESageMakerSessionHeaderSessionRequestType)get_session_id_from_requestrequest_typec                 C   s    | t jkrtS | t jkrtS dS )zMap session request type to the appropriate handler function.

    Args:
        request_type: The type of session request

    Returns:
        Handler function for the request type, or None if no handler
    N)r   NEW_SESSIONcreate_sessionCLOSEclose_session)r    r   q/home/ubuntu/.local/lib/python3.10/site-packages/model_hosting_container_standards/sagemaker/sessions/handlers.pyget_handler_for_request_type   s
   
	
r   raw_requestc              
      s   t | }t }|du rtt ttjjt	dz |
| td| d ttjjd| dtj| idW S  ty\ } ztdt|  ttjjdt| dd}~ww )aA  Close an existing session and clean up its resources.

    Args:
        raw_request: FastAPI Request object containing session ID in headers

    Returns:
        Response with 200 status and closed session ID in headers

    Raises:
        HTTPException: If session closure fails with 424 FAILED_DEPENDENCY status
    Nstatus_codedetailSession z closedr   contentheaderszFailed to close session: )r   r   r	   errorr   r   r   BAD_REQUESTvaluer   r   infor   OKr   CLOSED_SESSION_ID	Exception	exceptionstrFAILED_DEPENDENCY)r   
session_idsession_managerer   r   r   r   #   s2   



r   c              
      s   t  }|du rtt ttjjtdz9|	 }|j
dus!J tj|j
tjdd}td|j d ttjjd|j dtj|j d| idW S  tyq } ztd	t|  ttjjd	t| dd}~ww )
aO  Create a new stateful session with expiration tracking.

    Args:
        raw_request: FastAPI Request object (unused but part of handler signature)

    Returns:
        Response with 200 status, session ID and expiration in headers

    Raises:
        HTTPException: If session creation fails with 424 FAILED_DEPENDENCY status
    Nr   )tzz%Y-%m-%dT%H:%M:%SZr   z createdz
; Expires=r   zFailed to create session: )r   r	   r!   r   r   r   r"   r#   r   r   expiration_tsr   fromtimestampr   utcstrftimer$   r+   r   r%   r   NEW_SESSION_IDr'   r(   r)   r*   )r   r,   sessionr/   r-   r   r   r   r   G   s>   
r   N)r   r   httpr   fastapir   r   fastapi.exceptionsr   logging_configr	   managerr   modelsr   r   r   r   utilsr   r   r   r   r   r   r   r   <module>   s    $