
    iB                     ~   S r SSKrSSKrSSKrSSKrSSKrSSKJrJrJ	r	J
r
Jr  SSKJr  SSKrSSKJrJrJr  SSKJr  SSKJr  SSKJr  SS	KJr  S
SKJr  SSKJr  SSKJ r!  Sr"Sr#Sr$Sr%\RL                  " \'5      r(\RR                  " S\RT                  5      r+S\,4S jr-\-" 5       r. " S S\5      r/ " S S\5      r0g)z*Session customized for IBM Quantum access.    N)DictOptionalAnyTupleUnion)PurePath)SessionRequestExceptionResponse)HTTPAdapter)AuthBase)Retry)filter_data   )RequestsApiError   )IBMNotAuthorizedError)__version__)i  i    i  i  i	  i
  i  +QISKIT_IBM_RUNTIME_CUSTOM_CLIENT_APP_HEADERQE_CUSTOM_CLIENT_APP_HEADERUSAGE_DATA_OPT_OUTz^(.*/backends/)([^/}]{2,})(.*)$returnc                  \   [         R                  " [        S5      S:X  a  g/ SQn SS[         30nU  HE  n U S[        R
                  R                  U5       3nU[        R                  ;   a  US-  nX1U'   MG     S	S
R                  UR                  5       5       3$ ! [         a     Mx  f = f)zReturn the client version.FalseTrue )	qiskitqiskit_terra
qiskit_aerqiskit_experimentsqiskit_natureqiskit_machine_learningqiskit_optimizationqiskit_financecircuit_knitting_toolboxqiskit_ibm_runtimezqiskit_ibm_runtime--*zqiskit-version-2/,)osgetenvUSAGE_DATA_OPT_OUT_ENV_VARibm_runtime_version	importlibmetadataversionsysmodules	Exceptionjoinvalues)qiskit_pkgspkg_versionspkg_nameversion_infos       X/home/james-whalen/.local/lib/python3.13/site-packages/qiskit_ibm_runtime/api/session.py_get_client_headerr<   9   s     
yy+W5?
K ),?@S?T*UVL	&Zq););)C)CH)M(NOL3;;&#%1"   sxx(;(;(=>?@@  		s   AB
B+*B+c            	       `   ^  \ rS rSrSr      S
U 4S jjrSS\S\S\S\4U 4S jjjr	S	r
U =r$ )PostForcelistRetry\   am  Custom ``urllib3.Retry`` class that performs retry on ``POST`` errors in the force list.

Retrying of ``POST`` requests are allowed *only* when the status code
returned is on the ``STATUS_FORCELIST``. While ``POST``
requests are recommended not to be retried due to not being idempotent,
the IBM Quantum API guarantees that retrying on specific 5xx errors is safe.
c           	        > [         R                  5       [        R                  L aK  S=n=pU(       a$  UR                  nUR
                  nUR                  n	[         R                  SUUUUUU	5        [        T
U ]%  UUUUUUS9$ )z5Overwrites parent class increment method for logging.NzDRetrying method=%s, url=%s, status=%s, error=%s, data=%s, headers=%s)methodurlresponseerror_pool_stacktrace)
loggergetEffectiveLevelloggingDEBUGstatusdataheadersdebugsuper	increment)selfrA   rB   rC   rD   rE   rF   rK   rL   rM   	__class__s             r;   rP   PostForcelistRetry.incremente   s     ##%6&**F*T!}}"**LLV w # ! 
 	
    rA   status_codehas_retry_afterr   c                 l   > UR                  5       S:X  a  X R                  ;   a  g[        TU ]  XU5      $ )zIndicate whether the request should be retried.

Args:
    method: Request method.
    status_code: Status code.
    has_retry_after: Whether retry has been done before.

Returns:
    ``True`` if the request should be retried, ``False`` otherwise.
POSTT)upperstatus_forcelistrO   is_retry)rQ   rA   rU   rV   rR   s       r;   r[   PostForcelistRetry.is_retry   s3     <<>V#7L7L(Lw_EErT    )NNNNNNF)__name__
__module____qualname____firstlineno____doc__rP   strintboolr[   __static_attributes____classcell__rR   s   @r;   r>   r>   \   sO      
DFs F Ft FX\ F FrT   r>   c                   b  ^  \ rS rSrSr       SS\S\S\S\S\S	\	\
\\4      S
\	\   S\\\\S4   4   SS4U 4S jjjrSS jrS\S\S\SS4S jr SS\S	\
\\4   S
\	\   SS4S jjr S S\S\S\S\S\4
U 4S jjjrS\S\S\
\\4   SS4S jrS\S\4S jrSS jrS\
4U 4S jjrSrU =r$ )!RetrySession   zCustom session with retry and handling of specific parameters.

This is a child class of ``requests.Session``. It has its own retry
policy and handles IBM Quantum specific parameters.
Nbase_urlretries_totalretries_connectbackoff_factorverifyproxiesauthtimeoutr   c	                    > [         T	U ]  5         Xl        SU l        U R	                  X#U5        U R                  XV=(       d    0 U5        Xl        g)a  RetrySession constructor.

Args:
    base_url: Base URL for the session's requests.
    retries_total: Number of total retries for the requests.
    retries_connect: Number of connect retries for the requests.
    backoff_factor: Backoff factor between retry attempts.
    verify: Whether to enable SSL verification.
    proxies: Proxy URLs mapped by protocol.
    auth: Authentication handler.
    timeout: Timeout for the requests, in the form of (connection_timeout,
        total_timeout).
N)rO   __init__rm   custom_header_initialize_retry_initialize_session_parameters_timeout)
rQ   rm   rn   ro   rp   rq   rr   rs   rt   rR   s
            r;   rv   RetrySession.__init__   sF    0 	 ,0}~N++FMr4HrT   c                 F     U R                  5         g! [         a     gf = f)z,RetrySession destructor. Closes the session.N)closer4   )rQ   s    r;   __del__RetrySession.__del__   s"    	JJL 		s    
  c                 ~    [        UUU[        S9n[        US9nU R                  SU5        U R                  SU5        g)zSet the session retry policy.

Args:
    retries_total: Number of total retries for the requests.
    retries_connect: Number of connect retries for the requests.
    backoff_factor: Backoff factor between retry attempts.
)totalconnectrp   rZ   )max_retrieszhttp://zhttps://N)r>   STATUS_FORCELISTr   mount)rQ   rn   ro   rp   retryretry_adapters         r;   rx   RetrySession._initialize_retry   sB     ##)-	
 $6

9m,

:}-rT   c                     [         R                  " [        5      =(       d    [         R                  " [        5      U l        X0l        U=(       d    0 U l        Xl        g)zSet the session parameters and attributes.

Args:
    verify: Whether to enable SSL verification.
    proxies: Proxy URLs mapped by protocol.
    auth: Authentication handler.
N)r+   r,   CUSTOM_HEADER_ENV_VARQE_PROVIDER_HEADER_ENV_VARrw   rs   rr   rq   )rQ   rq   rr   rs   s       r;   ry   +RetrySession._initialize_session_parameters   sA      YY'<= 
&B
 	}"rT   rA   rB   barekwargsc           
      N  > U(       a;  UnUR                  S0 5      nUR                  SS05        UR                  SU05        OU R                  U-   nU R                  (       d#  SU;  a  UR                  SU R                  05        U R
                  R                  5       nUR                  UR                  S0 5      5        UR                  S[         S305        [        R                  " [        S5      S	:X  GdU  [        S
5      [        S5      [        S5      SSSSSS1	n[        R                  " 5       n	U	R                  5         Sn
U	 GH  n[!        [        UR"                  5      5      nU H  n[!        U5      U;   d  M  [!        U5      UR%                  [!        U5      S5      S   -   n[        R&                  S:X  a  UR)                  SS5      nOUR)                  SS5      nU R*                  (       a*  UR                  S[         SU SU R*                   305        OUR                  S[         SU 305        Sn
  O   U
(       d  GM    O   Xpl        U R-                  5          U R/                  XQU5        [0        TU ]d  " X4SU0UD6nUR5                  5         U$ ! [6         a  n[!        U5      nSnUR8                  b  UR8                  R:                  n UR8                  R=                  5       S   nUSR?                  US   US   5      -  n[@        RC                  SUR8                  R
                  S    5        O,! [D         a    US!UR8                  RF                   3-  n Of = fUS":X  a  [I        U5      UeUS#:X  a  [K        S$U 35      e[K        UU5      UeSnAff = f)%aS  Construct, prepare, and send a ``Request``.

If `bare` is not specified, prepend the base URL to the input `url`.
Timeout value is passed if proxies are not used.

Args:
    method: Method for the new request (e.g. ``POST``).
    url: URL for the new request.
    bare: If ``True``, do not send IBM Quantum specific information
        (such as access token) in the request or modify the input `url`.
    **kwargs: Additional arguments for the request.

Returns:
    Response object.

Raises:
    RequestsApiError: If the request failed.
    IBMNotAuthorizedError: If the auth token is invalid.
paramsaccess_tokenNrt   rM   X-Qx-Client-Applicationz/qiskitr   r   zqiskit/algorithmszqiskit_ibm_runtime/sampler.pyzqiskit_ibm_runtime/estimator.pyr#   r"   r$   r!   r%   r&   Fr   nt\~/TrD   z. {}, Error code: {}.messagecodezResponse uber-trace-id: %szuber-trace-idz. i  r   zUnexpected response received from server. Please check if the service is in maintenance mode https://docs.quantum.ibm.com/announcements/service-alerts )&getupdaterm   rr   rz   rM   copypopCLIENT_APPLICATIONr+   r,   r-   r   inspectstackreverserd   filenamesplitnamereplacerw   _set_custom_header_log_request_inforO   requestraise_for_statusr
   rC   rU   jsonformatrG   rN   r4   textr   r   )rQ   rA   rB   r   r   	final_urlr   rM   callersr   found_callerframe
frame_pathcaller
caller_strsanitized_caller_strrC   exr   rU   
error_jsonrR   s                        r;   r   RetrySession.request   s   . IZZ"-FMM>401MM8V,-+I ||	 7MM9dmm45,,##%vzz)R01 	16H5I3QRSyy3W=G ,-89:;)%$ *
G MMOEMMO L %..!9:
%F6{j0%([:3C3CCKQR3STV3W%W
77d?3=3E3EdC3P03=3E3Ec33O0--#NN$=BTAUUV';&<Ad>P>P=Q@S!" $NN$=BTAU&'(<'=@?!" (,- &.  <5 6 !	A""9f=wvT'TVTH%%'< ;   	A "gGK{{& kk557!#!1!1!3G!<J6=="9-z&/A  G LL4++O< ! 7BKK$4$4#566G7 c!+G4"<c!&QQXPY[ 
 #7K8b@7	As=   (5J 
N$)0NA%M ?N &M)&N(M))6NN$request_datac                    [         R                  " [        SU5      nU R                  U5      (       ap   [        R                  5       [        R                  L aI  SnUS;   a  SR                  [        U5      5      n[        R                  SUUR                  5       U5        ggg! [         a)  n[        R                  S[        U5      5         SnAgSnAff = f)a  Log the request data, filtering out specific information.

Note:
    The string ``...`` is used to denote information that has been filtered out
    from the request, within the url and request data. Currently, the backend name
    is filtered out from endpoint URLs, using a regex to capture the name, and from
    the data sent to the server when submitting a job.

    The request data is only logged for the following URLs, since they contain useful
    information: ``/Jobs`` (POST), ``/Jobs/status`` (GET),
    and ``/backends/<device_name>/properties`` (GET).

Args:
    url: URL for the new request.
    method: Method for the new request (e.g. ``POST``)
    request_data:Additional arguments for the request.

Raises:
    Exception: If there was an error logging the request information.
z\1...\3r   )z/devices/.../propertiesz/JobszRequest Data: {}.zEndpoint: %s. Method: %s. %sz5Filtering failed when logging request information: %sN)resubRE_BACKENDS_ENDPOINT_is_worth_loggingrG   rH   rI   rJ   r   r   rN   rY   r4   inford   )rQ   rB   rA   r   filtered_urlrequest_data_to_logr   s          r;   r   RetrySession._log_request_infoi  s    , vv2KE!!,//^++->*,'#'KK.A.H.HUaIb.c+LL6$+	 ? 0  ^SUXY[U\]]^s   A-B$ $
C.CCendpoint_urlc                     UR                  S5      (       a  gUR                  S5      (       a  gUS:X  a  gSU;   a  gSU;   a  gg)a  Returns whether the endpoint URL should be logged.

The checks in place help filter out endpoint URL logs that would add noise
and no helpful information.

Args:
    endpoint_url: The endpoint URL that will be logged.

Returns:
    Whether the endpoint URL should be logged.
)z/queue/statusz/devices/v/1z/Jobs/statusz/.../propertiesz/.../defaultsF)z/usersz/versionz/NetworkobjectstoragebookingsT)endswith
startswith)rQ   r   s     r;   r   RetrySession._is_worth_logging  sZ       
 
 ""#9:::%l*%rT   c                     U R                   R                  5       nU R                  (       a?  US   nU R                  U;  a)  UR                  SU SU R                   305        Xl         ggg)zSet custom header.r   r   N)rM   r   rw   r   )rQ   rM   currents      r;   r   RetrySession._set_custom_header  si    ,,##%78G!!0 9gYaHZHZG[;\]^& 1 rT   c                 Z   > [         TU ]  5       nUR                  U R                  5        U$ )z7Overwrite Session's getstate to include all attributes.)rO   __getstate__r   __dict__)rQ   staterR   s     r;   r   RetrySession.__getstate__  s%    $&T]]#rT   )rz   rs   rm   rw   rM   rr   rq   )      g      ?TNN)g      @N)r   N)Nr^   )r_   r`   ra   rb   rc   rd   re   floatrf   r   r   r   r   r   rv   r~   rx   ry   r   r   r   r   r   r   r   rg   rh   ri   s   @r;   rk   rk      s      #,0#'4?     	 
     $sCx.)  x   ueE4K001  
   @. .36.HM.	., QU%)#s(^;CH;M	$ 38zz #z+/zCFz	z zx'^S '^# '^T#s(^ '^X\ '^Rc d B'd  rT   rk   )1rc   r   r+   r   rI   r2   typingr   r   r   r   r   pathlibr   importlib.metadatar/   requestsr	   r
   r   requests.adaptersr   requests.authr   urllib3.util.retryr   qiskit_ibm_runtime.utils.utilsr   
exceptionsr   r   r1   r   r.   r   r   r   r-   	getLoggerr_   rG   compile
IGNORECASEr   rd   r<   r   r>   rk   r]   rT   r;   <module>r      s    1  	 	  
 4 4   8 8 ) " $ 6 ( . 8	  F : 1 			8	$
 zz"DbmmT AC A@ () 9F 9Fxh7 hrT   