
    bi2                        d Z ddlmZ ddlmZmZ ddlZddlmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZ ddZddZddZdd	Zdd
ZddZddZddZddZddZy)zShared helper functions for error handling.

These functions are used by both sync and async clients to parse error responses
and raise appropriate exceptions. They contain no I/O operations.
    )annotations)AnyOptionalN)QuotaExceededErrorResourceAlreadyExistsErrorResourceNotFoundErrorResourceTimeoutErrorSandboxAPIErrorSandboxAuthenticationErrorSandboxClientErrorSandboxConnectionErrorSandboxCreationErrorSandboxNotReadyErrorSandboxOperationErrorValidationErrorc           	        	 | j                   j                         }|j                  d      }t        |t              r-|j                  d      |j                  dt        |             dS t        |t              r^|r\|D cg c].  }t        |t              s|j                  dt        |            0 }}d|rdj                  |      dS t        |       dS d|xs t        |       dS c c}w # t        $ r dt        |       dcY S w xY w)zParse standardized error response.

    Expected format: {"detail": {"error": "...", "message": "..."}}

    Returns a dict with:
    - error_type: The error type (e.g., "ImagePull", "CrashLoop")
    - message: Human-readable error message
    detailerrormessage
error_typer   msgNz; )	responsejsonget
isinstancedictstrlistjoin	Exception)r   datar   dmessagess        d/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/langsmith/sandbox/_helpers.pyparse_error_responser&   !   s    ;~~""$(# fd#$jj1!::iU<  fd#6<T
1d@SeSV,THT"2:499X. @CE
  #v/CUDD U  ;"s5z::;s<   A'C/ *C/  C*C*3C/ C/ C/ *C/ /D	D	c                2   	 | j                   j                         }|j                  d      }t        |t              r-|j                  d      |j                  dt        |             dS d|xs t        |       dS # t        $ r dt        |       dcY S w xY w)zParse error response (simplified version for sandbox operations).

    Returns a dict with:
    - error_type: The error type
    - message: Human-readable error message
    r   r   r   r   N)r   r   r   r   r   r   r!   r   r"   r   s      r%   parse_error_response_simpler)   C   s    ;~~""$(#fd#$jj1!::iU< 
 #v/CUDD ;"s5z::;s   A'A< *A< <BBc                    	 | j                   j                         }|j                  dg       }t        |t              r|S g S # t
        $ r g cY S w xY w)a  Parse Pydantic validation error response.

    Returns a list of validation error details, each containing:
    - loc: Location of the error (e.g., ["body", "resources", "cpu"])
    - msg: Human-readable error message
    - type: Error type (e.g., "value_error")
    r   )r   r   r   r   r   r!   r(   s      r%   parse_validation_errorr+   Y   sQ    ~~""$(B'fd#M	 	s   =A  A AAc                v    | j                         }d|v r	d|v sd|v ryd|v ryd|v ryd|v r	d|v sd|v ryd	|v ry	y
)zExtract quota type from error message.

    Returns one of: "sandbox_count", "cpu", "memory", "volume_count",
    "storage", or None.
    sandboxcountlimitsandbox_countcpumemoryvolumevolume_countstorageN)lower)r   message_lowers     r%   extract_quota_typer8   k   sg     MMOMM!= G}$<	-		]	"	]	"= G}$<	m	#    c                \    t        | j                  dd      | j                  d            |)a,  Raise SandboxCreationError with the error_type from the API response.

    The error_type indicates the specific failure reason:
    - ImagePull: Image pull failed
    - CrashLoop: Container crashed during startup
    - SandboxConfig: Configuration error
    - Unschedulable: Cannot be scheduled
    r   zSandbox creation failedr   r   )r   r   )r"   r   s     r%   raise_creation_errorr<      s1     5688L) r9   c                   | j                   j                  }t        |       }|dk(  rt        |d   d      | |dk(  r[t	        |       }|rAt        d |D              r/|r|d   j                  dd	g      d
   nd	}t        |d   ||      | t        ||        y	|dk(  rt        |d         }t        |d   |      | |dk(  r$t        |d   |j                  d      xs d      | t        |        y	)a  Handle HTTP errors specific to sandbox creation.

    Maps API error responses to specific exception types:
    - 408: ResourceTimeoutError (sandbox didn't become ready in time)
    - 422: ValidationError (bad input) or SandboxCreationError (runtime)
    - 429: QuotaExceededError (org limits exceeded)
    - 503: SandboxCreationError (no resources available)
    - Other: Falls through to generic error handling
    i  r   r-   resource_type  c              3  D   K   | ]  }|j                  d       dk(    yw)typevalue_errorN)r   ).0r#   s     r%   	<genexpr>z0handle_sandbox_creation_error.<locals>.<genexpr>   s     Ka155=M9Ks    r   locNr   fielddetails  r   
quota_type  r   Unschedulabler;   )r   status_coder&   r	   r+   anyr   r   r<   r8   r   r   handle_client_http_error)r   statusr"   rJ   rI   rM   s         r%   handle_sandbox_creation_errorrT      s    ^^''F&D}"4	?)LRWW	3(/sK7KK9@GAJNN54&1"5dE!Y 	 !u-	3'Y8
 O!
 	 
3"Oxx-@
 	 	!'r9   c                    | j                   j                  }t        |       }|dk(  rt        |d   d      | |dk(  rt	        |d   d      | t        |        y)	a  Handle HTTP errors specific to volume creation.

    Maps API error responses to specific exception types:
    - 503: SandboxCreationError (provisioning failed)
    - 504: ResourceTimeoutError (volume didn't become ready in time)
    - Other: Falls through to generic error handling
    rN   r   VolumeProvisioningr;     r3   r>   N)r   rP   r&   r   r	   rR   )r   rS   r"   s      r%   handle_volume_creation_errorrX      se     ^^''F&D}"O(<
	 
3"4	?(KQVV 	!'r9   c                   | j                   j                  }t        |       }|j                  d      }|dk(  r8|dk(  rt	        |d   d      | |dk(  rt        |d   |      | t        |        y|d	k(  rt        |d   d
      | |dk(  rt        |d         }t        |d   |      | |dk(  rt        |d   d
      | t        |        y)a  Handle HTTP errors specific to pool creation/update.

    Maps API error responses to specific exception types:
    - 400: ResourceNotFoundError or ValidationError (template has volumes)
    - 409: ResourceAlreadyExistsError
    - 429: QuotaExceededError (org limits exceeded)
    - 504: ResourceTimeoutError (timeout waiting for ready replicas)
    - Other: Falls through to generic error handling
    r     TemplateNotFoundr   templater>   r   r;   i  poolrK   rL   rW   N)r   rP   r&   r   r   r   rR   r   r8   r   r	   )r   rS   r"   r   rM   s        r%   handle_pool_errorr^      s     ^^''F&D,'J}++'Yz ,,!$y/jIuT %U+	3(O6
	 
3'Y8
 O!
 	 
3"4	?&IuT 	!'r9   c                   t        |       }|d   }|j                  d      }| j                  j                  }|dv rt	        |      | |dk(  rt        |      | |dk(  r7t        |       }|r|d   j                  ddg      d	   nd}t        |||
      | |dk(  rt        |      }t        ||      | |dk(  r|dk(  rt        |      | |dk(  rt        |      | t        |      | )zLHandle HTTP errors and raise appropriate exceptions (for client operations).r   r   )i      r@   r   rF   NrG   rH   rK   rL     ConnectionErrori  )r&   r   r   rP   r   r   r+   r   r8   r   r   r
   r   )r   r"   r   r   rS   rJ   rI   rM   s           r%   rR   rR     s   &D9oG,'J^^''F(1u<}#G,%7 }(/5<
utf-b1$
 		 }'0
 !
 	
 }'88$W-58}g&E1
W
%50r9   c                   t        |       }|d   }|j                  d      }| j                  j                  }|dk(  rt	        |d|      | |dk(  rt	        |d|      | |dk(  rt	        |d	|      | |d
k(  rt	        |dd      | |dk(  r|dk(  rt        |      | |dk(  r|dk(  rt        |      | |dk(  s|dk(  rt        |d      | t        |      | )a  Handle HTTP errors for sandbox operations (run, read, write).

    Maps API error types to specific exceptions:
    - WriteError -> SandboxOperationError (operation="write")
    - ReadError -> SandboxOperationError (operation="read")
    - CommandError -> SandboxOperationError (operation="command")
    - ConnectionError (502) -> SandboxConnectionError
    - FileNotFound / 404 -> ResourceNotFoundError (resource_type="file")
    - NotReady (400) -> SandboxNotReadyError
    - 403 -> SandboxOperationError (permission denied)
    r   r   
WriteErrorwrite)	operationr   	ReadErrorreadCommandErrorcommandr`   NPermissionDeniedrb   rc   rZ   NotReadyra   FileNotFoundfiler>   )	r)   r   r   rP   r   r   r   r   r   )r   r"   r   r   rS   s        r%   handle_sandbox_http_errorrp   9  s    'u-D9oG,'J^^''F \!#w:
	 [ #v*
	 ^##yZ
	
 }#t0B
	
 }'88$W-58 }z1"7+6}
n4#G6BM
W
%50r9   )r   httpx.HTTPStatusErrorreturndict[str, Any])r   rq   rr   z
list[dict])r   r   rr   zOptional[str])r"   rs   r   rq   rr   None)r   rq   rr   rt   )__doc__
__future__r   typingr   r   httpxlangsmith.sandbox._exceptionsr   r   r   r	   r
   r   r   r   r   r   r   r   r&   r)   r+   r8   r<   rT   rX   r^   rR   rp    r9   r%   <module>r{      s_    #      (;D;,$>-(`(0+(\"1T/1r9   