
    5it                     :   d Z ddlmZmZmZmZ ddlZ ej                  e      Z	e	j                   ej                                ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddl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$m%Z%m&Z&m'Z'm(Z( ddl)m*Z* ddl+Z+ddlm,Z, ddl-m.Z.  ejX                         Z/da0d Z1d Z2 e2        ddl3m4Z5 e5Z6dZ7d\  a8a9d\  a:a;a<a=dZ>dZ?dZ@e>aAe?aBe@aCdZDdZEdZFdaGdZHdj                  ee5 ej                           ej                               ZK ej                         ZMeKdddd ZNe+j                  j                  j                  eEeE!      ZR ed"d#      ZSe!j                  e!j                  ee!j                  e!j                  fZX e,       ZYdaZd$ Z[dCd&Z\dDd'Z]d( Z^ej                  ej                  ej                  hZbe!j                  ee!j                  ede+jB                  j                  e!j                  fZfd) Zgd* Zhd+ Zid, ZjdEd-Zkd. Zld/ Zmd0ddeEddd%dddeDd%fd1Zn G d2 d3      Zo	 dFd4ZpdGd5Zqd6 Zrd7 Zsd8 Ztd9 ZudDd:ZvdHd;Zw	 daxd< Zyd= Zzd> Z{dd?l|m}Z~  e~       Zdd@l ddAlmZ ddBlmZmZ y)Ia  
When this package is imported, configuration values will be loaded from
the following sources in order of decreasing priority:

1. Environment variables
2. Values stored in ``~/.dnanexus_config/environment``
3. Hardcoded defaults

The bindings are configured by the following environment variables:

.. envvar:: DX_SECURITY_CONTEXT

   A JSON hash containing your auth token, typically of the form
   ``{"auth_token_type": "Bearer", "auth_token": "YOUR_TOKEN"}``.

.. envvar:: DX_APISERVER_PROTOCOL

   Either ``http`` or ``https`` (usually ``https``).

.. envvar:: DX_APISERVER_HOST

   Hostname of the DNAnexus API server.

.. envvar:: DX_APISERVER_PORT

   Port of the DNAnexus API server.

.. envvar:: DX_JOB_ID

   Should only be present if run in an Execution Environment; indicates
   the ID of the currently running job.

.. envvar:: DX_WORKSPACE_ID

   Should only be present if run in an Execution Environment; indicates
   the running job's temporary workspace ID.

.. envvar:: DX_PROJECT_CONTEXT_ID

   Indicates either the project context of a running job, or the default
   project to use for a user accessing the platform from the outside.

The following fields can be used to read the current configuration
values:

.. py:data:: APISERVER_PROTOCOL

   Protocol being used to access the DNAnexus API server. Either
   ``http`` or ``https`` (usually ``https``).

.. py:data:: APISERVER_HOST

   Hostname of the DNAnexus API server.

.. py:data:: APISERVER_PORT

   Port of the DNAnexus API server.

.. py:data:: JOB_ID

   Indicates the ID of the currently running job, or None if we are not
   in an Execution Environment.

.. py:data:: WORKSPACE_ID

   Indicates the temporary workspace ID of the currently running job, or
   the current project if we are not in an Execution Environment.

.. py:data:: PROJECT_CONTEXT_ID

   Indicates either the project context of a running job, if there is
   one, or the default project that is being used, for users accessing
   the platform from the outside.

.. py:data:: USER_AGENT

   The user agent string that dxpy will send to the server with each request.

The :func:`dxpy.DXHTTPRequest` function uses the ``DX_SECURITY_CONTEXT``
and ``DX_APISERVER_*`` variables to select an API server and provide
appropriate authentication headers to it. (Note: all methods in the
:mod:`dxpy.api` module, and by extension any of the bindings methods
that make API calls, use this function.)

All object handler methods that require a project or data container ID
use by default the ``DX_WORKSPACE_ID`` (if running inside an Execution
Environment) or ``DX_PROJECT_CONTEXT_ID`` (otherwise).

The following functions can be used to override any of the settings
obtained from the environment for the duration of the session:

* :func:`dxpy.set_security_context`: to specify an authentication token
* :func:`dxpy.set_api_server_info`: to specify the API server (host, port, or protocol)
* :func:`dxpy.set_workspace_id`: to specify the default data container

To pass API server requests through an HTTP(S) proxy, set the following
environment variables:

.. envvar:: HTTP_PROXY

   HTTP proxy, in the form 'protocol://hostname:port' (e.g. 'http://10.10.1.10:3128')

.. envvar:: HTTPS_PROXY

   HTTPS proxy, in the form 'protocol://hostname:port'

    )print_functionunicode_literalsdivisionabsolute_importN)
namedtuple)BadStatusLine)StringIO)Repr   )
exceptions)BOLDBLUEYELLOWGREENREDWHITE)randint)Lock)urlsplitc                  \    t         5  t        } t        dz  a| cd d d        S # 1 sw Y   y xY w)Nr   )sequence_number_mutexcounter)retvals    o/home/marpiech/ifpan-abm-pgxpred/analysis/marpiech-gwas-test/venv/lib/python3.12/site-packages/dxpy/__init__.py_get_sequence_numberr      s+    	 1  s   "+c                      t        j                  t         j                  j                         t	        j
                  d      j                  t        j                         y )N)categoryzurllib3.connectionpool)urllib3disable_warningsr   InsecurePlatformWarninglogging	getLoggersetLevelERROR     r   configure_urllib3r'      s:    g&8&8&P&PQ./88Gr&   )versionz1.0.0)NN)NNNNhttpsapi.dnanexus.com443   i  T   z5{name}/{version} ({platform}) Python/{python_version})namer(   platformpython_versionzgzip, deflatez*/*z
keep-alive)
User-AgentzAccept-EncodingAccept
Connection)connectread_RequestForAuthzmethod url headersc                    i }t        |       }|j                  r|j                  |j                  j                  d      dz   d  } dj	                  |j
                  |       |d<   |j                  r'dj	                  |j                  |j                        }n|j                  }t        j                  |      |d<   |S | |d<   |S )N@r   z	{0}://{1}	proxy_urlz{0}:{1})proxy_basic_authproxy_headers)	r   usernamenetlocfindformatschemepasswordr   make_headers)url
proxy_infourl_info
proxy_auths       r   _get_proxy_inforG      s    J}H oohoo22379:;"-"4"4X__c"J
;"))(*;*;X=N=NOJ!**J&-&:&:J&W
?#
  #&
;r&   Fc                     d}d }|D ](  }|t         j                  v st         j                  |   }* | r"t        dd|dt        j                         |S )N)
http_proxy
HTTP_PROXYhttps_proxyHTTPS_PROXYzUsing env variable =z	 as proxyfile)osenvironprintsysstderr)print_proxyproxy_tupleproxy	env_proxys       r   _get_env_var_proxyrY      sU    J+
% $iBJJjj#e$ 	5
Azz	,r&   c           	         t        dt        j                  t        t              }dt
        j                  vr|j                  t               || dt
        j                  vrwt        5  t        [t               r<t        t        d            }|j                  |       t        j                  di |a
nt        j                  di |a
t        cd d d        S t        ||||| xs5 t
        j                  j!                  d      xs t#        j$                               }| d	u s"t
        j                  j!                  d      d
k(  r5|j                  t        j&                  d        t        j(                          t               r;t        t        d            }|j                  |       t        j                  di |S t        j                  di |S # 1 sw Y   y xY w)N    )maxsize	cert_reqsheaderstimeoutDX_USE_OS_CA_BUNDLE)ca_certs
DX_CA_CERTT)rU   )	cert_filekey_filessl_contextra   FNOVERIFY)r]   ra   r%   )dictsslCERT_REQUIRED_default_headers_default_timeoutrP   rQ   update_default_certs_pool_mutex_pool_managerrY   rG   r   ProxyManagerPoolManagergetcertifiwhere	CERT_NONEr   )verifyrc   rd   re   default_pool_argsproxy_params	pool_argss          r   _get_pool_managerrz      s   R'*'8'8%5%57 BJJ.  . 9V^BJJ0N 	!$%'#23ERV3W#XL%,,\:$+$8$8$M;L$MM$+$7$7$L:K$LM 	! 	! *#,"*%0"("[BJJNN<,H"[GMMO	]	
 U?bjjnn\:jHs}}tD$$&*+=$+OPL\*''4)44&&3333	! 	!s   *A'GG c                 b    t        |      r |       \  }}|j                  |       n||}}| ||fS N)callablerl   )methodrC   r^   _url_headerss        r   _process_method_url_headersr     s6    }h gh4!!r&   c                    t        | t        j                  j                        ryt        | t              ryt        | t
        j                  t
        j                  f      ryt        | t
        j                        r| j                  t        v ryt        | t        j                  j                        ryt        | t        j                  j                        ryt        | t        j                        ryy)al  Returns True if the exception is always safe to retry.

    This is True if the client was never able to establish a connection
    to the server (for example, name resolution failed or the connection
    could otherwise not be initialized).

    Conservatively, if we can't tell whether a network connection could
    have been established, we return False.

    TF)
isinstancer   r   ProtocolErrorConnectionResetErrorsocketgaierrorherrorerrorerrno_RETRYABLE_SOCKET_ERRORSNewConnectionErrorSSLErrorrh   )es    r   _is_retryable_exceptionr   4  s     !W''556!)*!foov}}56!V\\"qww2J'J!W''::;!W''001!S\\"r&   c                      t        j                         \  } }}t        |t        j                        r|j                         S t        j                  | |      d   j                         S )z? Extract a useful error message from the last thrown exception )	rS   exc_infor   r   
DXAPIErrorerror_message	tracebackformat_exception_onlystrip)last_exc_type
last_errorlast_tracebacks      r    _extract_msg_from_last_exceptionr   O  sV    03-M:~*j334
 ''))..}jI"MSSUUr&   c                 2   | ]| j                   dv rOd| j                  v rA	 t        | j                  d         }|dk\  r|S |t        dt        |dz
  d      z  |z        z   S |dk  ryt        |d      }t        d|dz
  z  d|dz
  z        S # t        $ r Y 5w xY w)	z
    Returns the time in seconds that we should wait.

    :param num_attempts: number of attempts that have been made to the
        resource, including the most recent failed one
    :type num_attempts: int
    i    zretry-after<   g      ?r      r-      )statusr^   intmin
ValueErrorr   )responsenum_attemptssuggested_delays      r   _calculate_retry_delayr   \  s     : =-S[ScScBc	!("2"2="ABO '6&;? _$s4#lQ6F2K+Ko+]'^^_ q|Q'L1)*A,2B,CDD  	 		s   B
  B
 
	BBc                     d}t         r<t        dd      dk(  r-d| v r)t        |      |kD  rt        j	                  d|       |d| S |S )Ni @  r   	   uploadz#truncating upload data to length=%d)_INJECT_ERRORr   lenloggerinfo)rC   dataMIN_UPLOAD_LENs      r   _maybe_truncate_requestr     sJ    NAqMQHOD	N8RKK=~N.))Kr&   c                     t         r`|dk(  rZt        dd      dk(  rJt        dd      }|dk(  r| t        j                         |dk(  r| | dk  rt        j                         y y y y y y )NGETr   r   r      )r   r   r   DXIncompleteReadsErrorUrllibInternalError)	try_indexr~   error_throwns      r   _raise_error_for_testingr     sy    5WQ]a-?q!}1!23355 Q9#8Y]0022 >K#8 .@}r&   c           
         | dk\  r|s,t        |      dk(  rd}nRdt        t        |            z   dz   }n7	 t        dk\  rt        j                  |d      }nt        j                  |      }d	}	d
|v rdt        j                  d
|d
   i      z   }	t        dt        t        d|z              |t        |      ||	|fz  t        j                  d	       y | dkD  rZt        dt        t        d|z              |t        |      |t               j                  |      fz  t        j                  d	       y y # t
        t        f$ r d}Y w xY w)Nr   r   z""z<file data of length >r   indentz<binary data> Range z%s [%f] %s %s%s => %s
z>%d)rO   endz%s [%f] %s %s => %s
)r   str_DEBUGjsondumpsUnicodeDecodeError	TypeErrorrR   r   r   r   rS   rT   r
   repr)
debug_levelseq_numtime_startedr~   rC   r^   jsonify_datar   formatted_dataprintable_headerss
             r   _debug_print_requestr     sE   a4yA~!%!83s4y>!IC!O1Q;%)ZZQ%?N%)ZZ%5N g #djj'77;K1L&M M'6$uw2G+H+7+/<+.+<+9+; ; ::	 
q%UW_0E)F)5)-f),)-T):	)< <
 ::	 
 '	2 1!01s   6D2 2EEc	                 l   | dkD  r.|re| dk\  r+dt        j                  |d      j                  dd      z   }	nS| dk(  rt        j                  |      }	n8t               j	                  |      }	nt        |      dkD  rdt        |      z  nd}	t        t        j                         |z
  d	z        }
d
|cxk  rdk  r	n nt        nt        }t        dt        t        d|z              z   d|z  t        |      ||d |t        |            t        t        d|
z              |	t         j"                  
       y y )Nr   r   z
  r   r   
z
(%d bytes)r   i     i,  z  z<%dz[%f]z<=z(%dms)rN   )r   r   replacer
   r   r   r   timer   r   rR   r   r   r   r   r   rS   rT   )r   r   r   req_idresponse_statusresponse_was_jsonr~   rC   contentcontent_to_printtcode_formats               r   _debug_print_responser     s   Qa#)DJJwq,I,Q,QRVX^,_#_ !#'::g#6 #'6;;w#7 >A'lQ>N|c'l:TV|+t34 # < <e3dVD122|#6l#o./DA&'::		 r&   POSTc                    |}|i }t               }|
r	t        | z   n| }|j                         }|du rt        }|r |t	        |||             dD ci c]  }||j                  |d       }}|j                  dd      }|r$t        j                  |      }d|vr|dk(  rd|d<   n|}d}t        |d	      rt        |d
      r|j                         }d}d}g }d}d}	 d\  }}d}d}	 t        j                         }t        |||      \  } }}!t        t        ||| ||!||       t        ||      }"	 t        dJi |}#t         |!d<   t"        |!d<   d }$|!j%                         D %&ci c]  \  }%}& |$|%       |$|&       }!}%}&|!j                  dd       |!j                  dd       |!j                  dd       	  |$|       |}' |#j4                  | |'f|!|"|dd|}t?        ||       |j@                  jC                  dd      }tD        r|j@                  jC                  dd      jG                  d      rjdtH        jJ                  vrXtL        jO                  |j@                  d          	 tQ        tD        d      5  tI        jR                  tD        d       ddd       da"|jT                  dz  dk(  rt|j@                  jC                  d      }|s t9        j<                  d |jT                        	 |r|dkD  r{tL        jO                  d!t        jV                         |||       nN|jT                  dz  dk7  r|j@                  jC                  d"d      jG                  d      rm	 |jX                  j[                  d#      }*	 t        j^                  |*      }*	 te        t8        |*d&   d'   t8        jf                        }+ |+|*|jT                  ||      	 |jX                  j[                  d#      }*t9        jl                  d)jo                  |jT                  |jp                  ||      |*js                               |r6||r2|dkD  r,tL        jO                  d!t        jV                         |||       S S S d*|j@                  v r}tu        |j@                  d*         tw        |jX                        k7  rOd+|v r	d,|d+   d-nd},t9        jx                  d.d/|j@                  d*   tw        |jX                        |,||fz  z         |jX                  }*d}-|	rT|*j[                  d#      }*|j@                  jC                  d"d      jG                  d      r	 t        j^                  |*      }*d}-|j@                  jC                  d      xs d0}t{        t        ||||jT                  |-| ||*	       |r|j}                  |*       tw        |      d1k(  r9	 |s|dkD  stL        jO                  d!t        jV                         |||       t        |d          |d1   |r2|dkD  r,tL        jO                  d!t        jV                         |||       S S S |*|r2|dkD  r,tL        jO                  d!t        jV                         |||       S S S |rt        ||"f||||||||	|
|||dH|S t        dI      c c}w c c}&}%w # t&        $ rh ddl}(t+        |(j,                  j/                  |            })|(j,                  j1                  |)d         |)d<   |(j,                  j3                  |)      }'Y Rw xY w# t6        j8                  j:                  $ r t9        j<                  d      w xY w# 1 sw Y   xY w#  Y xY w# t\        $ r! t9        j<                  d$|jT                        w xY w# t`        $ r! t9        jb                  d%|jT                        w xY w# th        t\        tj        f$ r$ t9        jl                  d(|jT                  z  |*      w xY w# t\        $ r! t9        j<                  d$|jT                        w xY w# t`        $ r! t9        jb                  d%|jT                        w xY w# t        $ r1}.t        dJi |j                          d}t               }/t        |.t              r<|d1z   }0d}1|xs |d2k(  xs t        |.      }2|d1z   |0k  r|t        |.t              r|2}1n+|jT                  d3k(  xs d4|jT                  cxk  xr d5k  nc }1||jT                  d6k(  r|2r|d7k(  rt        |.t6        j8                  j                        r`d8}3|3|/v s(t        |.t8        jl                        r&|3|.j                  v rtL        jO                  d9||       ntL        jO                  d:|/||       d}1||jT                  d;k(  rd}1|1r%||j                  |       t        ||d1z         }4d+|v r	d<|d+   d-nd},||jT                  d=v rd>|4fz  }5nd?|4|d1z   |fz  }5d@t        jV                         dA|dB|dC|/dD|5dB|,}6t        |.t8        jl                        r|6dE|.j                  z  z  }6tL        j                  |6       t        j                  |4       |d1z  }||jT                  d=vr|d1z  }Y d}.~.|s	|dkD  s	tL        jO                  d!t        jV                         |||       	t        |.t8        jf                        sbd@t        jV                         dA|dB|dC|/dF	}6t        |.t8        jl                        r|6dE|.j                  z  z  }6tL        j                  |6       t        |.t6        j8                  j                        rdG|/v rt9        j                  |/       d}.~.ww xY w# |r2|dkD  r,tL        jO                  d!t        jV                         |||       w w w xY w)Ka  
    :param resource: API server route, e.g. "/record/new". If *prepend_srv* is False, a fully qualified URL is expected. If this argument is a callable, it will be called just before each request attempt, and expected to return a tuple (URL, headers). Headers returned by the callback are updated with *headers* (including headers set by this method).
    :type resource: string
    :param data: Content of the request body
    :type data: list or dict, if *jsonify_data* is True; or string or file-like object, otherwise
    :param headers: Names and values of HTTP headers to submit with the request (in addition to those needed for authentication, compression, or other options specified with the call).
    :type headers: dict
    :param auth:
        Controls the ``Authentication`` header or other means of authentication supplied with the request. If ``True``
        (default), a token is obtained from the ``DX_SECURITY_CONTEXT``. If the value evaluates to false, no action is
        taken to prepare authentication for the request. Otherwise, the value is assumed to be callable, and called with
        three arguments (method, url, headers) and expected to prepare the authentication headers by reference.
    :type auth: tuple, object, True (default), or None
    :param timeout: HTTP request timeout, in seconds
    :type timeout: float
    :param use_compression: Deprecated
    :type use_compression: string or None
    :param jsonify_data: If True, *data* is converted from a Python list or dict to a JSON string
    :type jsonify_data: boolean
    :param want_full_response: If True, the full :class:`urllib3.response.HTTPResponse` object is returned (otherwise, only the content of the response body is returned)
    :type want_full_response: boolean
    :param decode_response_body: If True (and *want_full_response* is False), the response body is decoded and, if it is a JSON string, deserialized. Otherwise, the response body is uncompressed if transport compression is on, and returned raw.
    :type decode_response_body: boolean
    :param prepend_srv: If True, prepends the API server location to the URL
    :type prepend_srv: boolean
    :param session_handler: Deprecated.
    :param max_retries: Maximum number of retries to perform for a request. A "failed" request is retried if any of the following is true:

                        - A response is received from the server, and the content length received does not match the "Content-Length" header.
                        - A response is received from the server, and the response has an HTTP status code in 5xx range.
                        - A response is received from the server, the "Content-Length" header is not set, and the response JSON cannot be parsed.
                        - No response is received from the server, and either *always_retry* is True or the request *method* is "GET".

    :type max_retries: int
    :param always_retry: If True, indicates that it is safe to retry a request on failure

                        - Note: It is not guaranteed that the request will *always* be retried on failure; rather, this is an indication to the function that it would be safe to do so.

    :type always_retry: boolean
    :returns: Response from API server in the format indicated by *want_full_response* and *decode_response_body*.
    :raises: :exc:`exceptions.DXAPIError` or a subclass if the server returned a non-200 status code; :exc:`urllib3.exceptions.HTTPError` if an invalid response was received from the server; or :exc:`urllib3.exceptions.ConnectionError` if a connection cannot be established.

    Wrapper around :meth:`urllib3.request()` that makes an HTTP
    request, inserting authentication headers and (by default)
    converting *data* to JSON.

    .. note:: Bindings methods that make API calls make the underlying
       HTTP request(s) using :func:`DXHTTPRequest`, and most of them
       will pass any unrecognized keyword arguments you have supplied
       through to :func:`DXHTTPRequest`.

    NT)rv   rc   rd   re   _test_retry_http_requestFzContent-Typer   zapplication/jsonseektellr   )TNr1   zDNAnexus-APIc                 H    t        | t              s| j                  d      } | S )Nascii)r   bytesencode)is    r   ensure_asciiz#DXHTTPRequest.<locals>.ensure_asciiU  s    %a/HHW-Hr&   s   hosts   content-lengths   Content-Lengthr   )r^   bodyr_   retriesClosedPoolErrorzx-request-idunavailablezx-upgrade-infor   z!A recommended update is available_ARGCOMPLETEad   r   Locationz'Location not found in redirect responsez&[%s] %s %s: Recovered after %d retrieszcontent-typezutf-8zContent is nonez!Invalid JSON received from serverr   typez0Appropriate error class not found. [HTTPCode=%s]z{} {} [Time={} RequestID={}]zcontent-lengthr   z ()zSReceived response with content-length header set to %s but content length is %d%s. z[Time=%f RequestID=%s]z--r   r   r   i  iX  i  PUTz<Code>RequestTimeout</Code>zQRetrying 400 HTTP error, due to slow data transfer. Request Time=%f Request ID=%szT400 HTTP error, of unknown origin, exception_msg=[%s]. Request Time=%f Request ID=%si  z (range=r   z"Waiting %d seconds before retry...z+Waiting %d seconds before retry %d of %d...[z] r   z: z. z
%s.z!Connection broken: IncompleteRead)r~   r^   authr_   use_compressionr   want_full_responsedecode_response_bodyprepend_srvsession_handlermax_retriesalways_retryz<Should never reach this line: should never break out of loopr%   )Rr   	APISERVERupperAUTH_HELPERr6   popr   r   hasattrr   r   r   r   r   r   rz   
USER_AGENTAPI_VERSIONitemsUnicodeEncodeErrorurllib.parselistparseurlparsequote
urlunparserequestr   r   r   r   r   r^   rr   _UPGRADE_NOTIFY
startswithrP   rQ   r   r   openutimer   ctimer   decodeAttributeErrorloadsr   BadJSONInReplygetattrr   KeyErrorr   HTTPErrorWithContentr?   reasonr   r   r   ContentLengthErrorr   append_set_retry_responseAssertionError	Exceptionclearr   r   _expected_exceptionsr   _RETRYABLE_WITH_RESPONSE	HTTPErrorr   r   r   warningsleepr   r   r   DXHTTPRequest)7resourcer   r~   r^   r   r_   r   r   r   r   r   r   r   r   kwargssafe_to_retryr   rC   argry   
test_retryserialized_datarewind_input_buffer_offsetr   try_index_including_throttledretried_responsesr   redirect_urlsuccessr   r   r   _methodr   r   pool_managerr   kvencoded_urlurllibpartsr   error_class	range_strr   r   exception_msgtotal_allowed_triesok_to_retryis_retryablerequest_timeout_strdelaywaiting_msglog_msgs7                                                          r   r'  r'    s   v !M #$G"-)h
8C\\^Ft|_VS'237ijfjjd++jIj6>J
 **T*(Vv-=&8GN# "&tVv!6%)YY[" I$%! DL
 *`	m99;L&A&#w&W#GT8 ,xYegkl*4AD'H0=9=)3&+6(
 JRIYZALO\!_<ZZ Wd+.5.5A &"&K 0<// Zh]a8?ZRXZ %Y7%%)).-HF##''(8"=HHIlm!3H,,-=>?os3 8$78 #( #%*'//33J?#$889bdldsdsttt 9q=DdjjlTZ\`bklo #%*##'';FFGYZa"*--"6"6w"?n"&**W"5M&-j'':J6:RT^TiTi&j &gxfUUa"*--"6"6w"? %99:X:_:_`h`o`oYaYhYhYeY_;a cjbobobqs s
 "t 9q=DdjjlTZ\`bkl )wq $x'7'778++,<=>#hmmBTTGNRYGY0@%B_a	(;;q4%--.>?X]]ASU^`lntuvv  #--$)!'%nnW5G''++NB?JJK]^5&*jj&9G
 15-!))--n=E%fg|VX__^o&-tW> %,,W5,-2 p 9q=DdjjlTZ\`bklo ,,=a,@A03j 9q=DdjjlTZ\`bkl )wg f 9q=DdjjlTZ\`bkl )w \4 \VZdk-<<0B2FT_-<)4=\
 U[\ 	\ W
XX_ kp [  * A' !6!6t!<=E%||11%(;E!H"(,,"9"9%"@K	A %%55 H !445FGGH8 8" * a(<<=NPXP_P_``a & n(778[]e]l]lmmn
 %ni@ M(==>ps{  tC  tC  ?C  EL  M  MM * a(<<=NPXP_P_``a8  * r",";";<_aiapap"qqr*  O	 *	*002G<>M!12 '2Ao##,_5_E\]^E_ q=#66 !($Q(@A&2&.oo&<&\x@\Y\@\ !,#??c1lvQV%a););)E)EF.K+/=@ *1j.M.M NSfjkjsjsSs"KK )HIUW]_ #KK )HIVXdfln&*  +30F&+1=		"<=28=Z]^=^_EIPT[I[''2B!DacI+:0M&JeX&U&S!9q=+W? '? :>vtUbdoqz{G!!Z%D%DE6AII#55NN7+JJu%1Q61'8??*+L!Q	" 9q=DdjjlTZ\`bkl a!6!67/3zz|VT=Ya!@!@A6AII#55W% !W//==>2mC 77FF_O	b 9q=DdjjlTZ\`bkl )wsA  Z&Aa .3\ !Z:9\ 4
Z  >\ Ba %] 5]
] Aa  =a ] :^ %^9 5a _4 &Aa (Ca  `! A#a 1a 8a \  A-\\ \\ 3]a 
]] ]a *^		a *^66a 98_11a 4*`a !*aa 
n	H6nn 
B:nn		n 6oc                       e Zd Zd Zd Zy)DXHTTPOAuth2c                     || _         y r|   security_context)selfrH  s     r   __init__zDXHTTPOAuth2.__init__5  s
     0r&   c                     | j                   d   j                         dk(  rA| j                   d   dz   | j                   d   z   }|j                         |j                  d<   |S t	        d      )Nauth_token_typebearerr   
auth_tokens   Authorizationz3Token types other than bearer are not yet supported)rH  lowerr   r^   NotImplementedError)rI  rauth_headers      r   __call__zDXHTTPOAuth2.__call__8  ss      !2399;xG//0ABSH4K`K`amKnnK*5*<*<*>AII&'  &&[\\r&   N)__name__
__module____qualname__rJ  rS  r%   r&   r   rE  rE  4  s    1r&   rE  c                 >   |r dt        |      z   dz   t        |      z   |d<   	 t        | dd|d ddd|d
      }t                |S # t        j                  $ r t               }t        t        j                  ||z
  d	z   t        z              }|}	|	|k  rct        |	|z   d	z
  |      }
dt        |	      z   dz   t        |
      z   |d<   |	|z  }	t        | dd|d ddd|d
      }|j                  |       |	|k  rc|j                         }|j                          |cY S w xY w)
Nzbytes=-r   r   r   FT)r~   r^   r   r   r   r   r_   r   r   )r   r'  r   r   r   r	   r   mathceilINCOMPLETE_READS_NUM_SUBCHUNKSr   writegetvalueclose)rC   r^   	start_posend_posr_   	sub_ranger   chunk_buffersubchunk_lensubchunk_start_possubchunk_end_posconcat_chunkss               r   _dxhttp_read_rangerg  L  sM   #c)n4s:S\IS"UG$]bpu*.V[] " ,, z499g	&9A&=?]%]^_& G+"#5#Dq#H'R'#.@*AACG#N^J__GG,. bdaf-2w6;=D
 t$ !G+ %--/%s    A B1D7"DDc                     | | a ||a||a||dk(  rt        dz   t         z   ayt        dz   t         z   dz   t	        t              z   ay)a  
    :param host: API server hostname
    :type host: string
    :param port: API server port. If not specified, *port* is guessed based on *protocol*.
    :type port: string
    :param protocol: Either "http" or "https"
    :type protocol: string

    Overrides the current settings for which API server to communicate
    with. Any parameters that are not explicitly specified are not
    overridden.
    Nr   ://:)APISERVER_HOSTAPISERVER_PORTAPISERVER_PROTOCOLr   r   )hostportprotocols      r   set_api_server_inforq  k  s^     %|trz&.?	&.?#ENH[[	r&   c                     | a t        |       ay)z
    :param security_context: Authentication hash, usually with keys ``auth_token_type`` set to ``Bearer`` and ``auth_token`` set to the authentication token.
    :type security_context: dict

    Sets the security context to use the provided token.
    N)SECURITY_CONTEXTrE  r  rG  s    r   set_security_contextrt    s     (/0Kr&   c                     | a y)aC  
    :param dxid: ID of a job
    :type dxid: string

    Sets the ID of the running job.

    .. warning:: This function is only really useful if you are
       developing code that will run in and interact with the Execution
       Environment, but wish to test it outside of an actual Execution
       Environment.

    N)JOB_IDdxids    r   
set_job_idry    s	     Fr&   c                     | a y)z
    :param dxid: ID of a project or workspace
    :type dxid: string

    Sets the default data container for object creation and modification
    to the specified project or workspace.

    N)WORKSPACE_IDrw  s    r   set_workspace_idr|    s	     Lr&   c                     | a y)a  
    :param dxid: Project ID
    :type dxid: string

    Sets the project context for a running job.

    .. warning:: This function is only really useful if you are
       developing code that will run in and interact with the Execution
       Environment but wish to test it outside of an actual Execution
       Environment.

       It does not change the default data container in which new
       objects are created or name resolution is performed. If you want
       to do that, use :func:`set_workspace_id` instead.

    N)PROJECT_CONTEXT_IDrw  s    r   set_project_contextr    s
    & r&   c                     | a y)aS  
    :param port: port to use for streaming job logs
    :type port: string

    Sets the port to use for streaming job logs via `dx watch` inside the
    Execution Environment

    .. warning:: This function is only really useful if you are
       developing code that will run in and interact with the Execution
       Environment.

    N)
WATCH_PORT)ro  s    r   set_watch_portr    s	     Jr&   c                 8   | |0| |t        j                  d      |dz   | z   dz   t        |      z   S t        dk(  ryt        dk(  ryt        dk(  ry	t        d
k(  ryt        dk(  st        dk(  s	t        dk(  rydt        j
                  vsdt        j
                  vr+d}t        j                  |j                  t                    t        j
                  d   dz   t        j
                  d   z   S d}t        j                  |j                  t                    )z
    Chooses the auth server name from the currently configured API server name.

    Raises DXError if the auth server name cannot be guessed and the overrides
    are not provided (or improperly provided).
    z;Both host and port must be specified if either is specifiedri  rj  zstagingapi.dnanexus.comz https://stagingauth.dnanexus.comr*   zhttps://auth.dnanexus.comzstagingapi.cn.dnanexus.comz(https://stagingauth.cn.dnanexus.com:7001zapi.cn.dnanexus.comz!https://auth.cn.dnanexus.com:8001	localhostz	127.0.0.1	apiserverDX_AUTHSERVER_HOSTDX_AUTHSERVER_PORTzbMust set authserver env vars (DX_AUTHSERVER_HOST, DX_AUTHSERVER_PORT) if apiserver is {apiserver}.)r  zECould not determine which auth server is associated with {apiserver}.)r   DXErrorr   rk  rP   rQ   r?   )host_overrideport_overriderp  err_msgs       r   get_auth_server_namer    s     M$= M$9$$%bcc%-/#5M8JJJ	4	41	-	-*	7	79	0	02	;	&.K*G>]hKhrzz15IQSQ[Q[5[zG$$W^^n^%MNN::23c9BJJG[<\\\Y  .!IJJr&   c                     | a y r|   _retry_response)r   s    r   r  r    s    Or&   c                      t         S r|   r  r%   r&   r   _get_retry_responser    s    r&   c                     | r| d   dk7  sd| vr| S | d   j                         D ];  \  }}|d   }t        j                  j                  |d|d   i      }|| d   |   d<   = | S )	z
    Adds the "workflowDescribe" field to the config for each region of
    the global workflow. The value is the description of an underlying
    workflow in that region.
    classglobalworkflowregionalOptionsworkflowproject	resources)input_paramsworkflowDescribe)r  dxpyapiworkflow_describe)globalworkflow_descregionconfigworkflow_idworkflow_descs        r   #append_underlying_workflow_describer     s     (,<<!%88""-.?@FFH [Z(22;iY_`kYlMm2nMZ-.v67IJ[ r&   )DXConfig)*)DXLogHandler)runentry_point)Fr|   )Nr   )T)NNN)NNr)   )__doc__
__future__r   r   r   r   r!   r"   rT  r   
addHandlerNullHandlerrP   rS   r   r   r/   rh   r   r   rY  r   	threadingrs   collectionsr   http.clientr   ior	   reprlibr
   r   r   utils.printingr   r   r   r   r   r   randomr   r   r   r  r   r   r   r   r'   toolkit_versionr(   TOOLKIT_VERSION__version__r  r  rs  rv  r  r{  r~  DEFAULT_APISERVER_PROTOCOLDEFAULT_APISERVER_HOSTDEFAULT_APISERVER_PORTrm  rk  rl  DEFAULT_RETRIESDEFAULT_TIMEOUTr   r  r[  r?   r0   r  rt   rm   rj   utilr_   Timeoutrk   r6   network_exceptionsr   r  r   r"  rn   ro   rG   rY   rz   r   ENETDOWNENETUNREACHECONNREFUSEDr   r  r   r   r#  r   r   r   r   r   r   r   r'  rE  rg  rq  rt  ry  r|  r  r  r  r  r  r  r  utils.configr  	_DXConfigr  bindingsdxlogr  utils.exec_utilsr  r  r%   r&   r   <module>r     s  "jX S R 			8	$   %'%%' ( 4 4 4 4      " %    A A    !&	( 
H
   7 * 7M 4
L"4$ +  / ''	
!" DKKQY<K=NX=N=N=PCZ8CZCZC\ L ^
 $.&	
  <<''//o/^ .0DE"55z7L7Lm]g]v]v"668 
 f,	&4R" 
NN		  '99=*JcJc0'2D2D2R2RT^TrTrt 6
VEL3"J4 *0D)"&Te'+t-E	\Y~

 
>\2	1 * K< 
$ 0	   . .r&   