
    !                     "   S r SSKrSSKrSSKrSSKJr  SSKJs  Js  J	r
  SSKJs  Js  Jr  SSKJs  Js  Jr  SSKJr  SSKJr  SSKJr  \R.                  (       a  SSKJr  OSSKJr  SS	/rS
rS rS rS rSS jr SS jr!SS jr"S r#S r$S r%g)z4Assorted utilities shared between parts of apitools.    N)http_client)messages)encoding_helper)
exceptions)Iterable	DetectGae	DetectGcez:/?#[]@!$&'()*+,;=c                      [         R                  R                  SS5      n U R                  S5      =(       d    U R                  S5      $ )zDetermine whether or not we're running on GAE.

This is based on:
  https://developers.google.com/appengine/docs/python/#The_Environment

Returns:
  True iff we're running on GAE.
SERVER_SOFTWARE zDevelopment/zGoogle App Engine/)osenvironget
startswith)server_softwares    (lib/third_party/apitools/base/py/util.pyr   r   -   s@     jjnn%6;O&&~6 =&&';<>    c                     SR                  [        R                  R                  SS5      5      n  [        R
                  " [        R                  " 0 5      5      R                  [        R                  " U SS0S95      nUR                  5       [        R                  :H  =(       a    UR                  R                  S5      S:H  $ ! [        R                   a     gf = f)	zDetermine whether or not we're running on GCE.

This is based on:
  https://cloud.google.com/compute/docs/metadata#runninggce

Returns:
  True iff we're running on a GCE instance.
z	http://{}GCE_METADATA_ROOTzmetadata.google.internalzMetadata-FlavorGoogle)headersFzmetadata-flavor)formatr   r   r   urllib_requestbuild_openerProxyHandleropenRequesturllib_errorURLErrorgetcoder   OKr   )metadata_urlos     r   r	   r	   ;   s     %%


*,FGIL''(C(CB(GHMM""'8(&CEF
 IIK;>>) 9IIMM+,8:    s   AC CCc                 |   [        U [        R                  5      (       a0  [        R                  " U 5      n [	        U R                  S5      5      $ [        U [        5      (       a1  U  Vs/ s H  n[        R                  " U5      PM     n n[	        U 5      $ [        R                  " S[        U 5      < 35      es  snf )z)Normalize scope_spec to a set of strings. z3NormalizeScopes expected string or iterable, found )

isinstancesixstring_types
ensure_strsetsplitr   r   TypecheckErrortype)
scope_specxs     r   NormalizeScopesr0   P   s    *c..//^^J/
:##C())	J	)	)1;<AcnnQ'
<:

#
#	    =s   ) B9c                     [        X5      (       dV  Uc=  [        U[        5      (       a  S[        U 5      < SU< 3nOS[        U 5      < SU< S3n[        R                  " U5      eU $ )NzType of arg is "z", not one of z", not "")r&   tupler-   r   r,   )argarg_typemsgs      r   	Typecheckr7   ]   sZ    c$$;(E**Ix) + :>cHM'',,Jr   c           
         U=(       d    U R                   =(       d    SnU R                   H  nSU-  nSnSU-  nXs;   a  [        nUR                  Xu5      nXS;  a  [        R
                  " SU-  5      e X   nUc  [        R
                  " SU-  5      e [        U[        R                  5      (       d  [        U5      nUR                  U[        R                  " UR                  S5      U5      5      nM     U$ ! [         a    [        R
                  " SU-  5      ef = f! [         a'  n	[        R
                  " SU< S	U< S
U	< 35      eSn	A	ff = f)z(Determine the relative path for request.r   z{%s}z{+%s}zMissing path parameter %sz%Request missing required parameter %sNutf_8z!Error setting required parameter z
 to value z: )relative_pathpath_params_RESERVED_URI_CHARSreplacer   InvalidUserInputErrorKeyErrorr&   r'   r(   strurllib_parsequoteencode	TypeError)
method_configparamsr:   pathparamparam_templatereserved_charsreserved_templatevaluees
             r   ExpandRelativePathrN   i   sf   =M77=2D**% #eO$0N<< 1BD%22+e35 5	A ME =227%?A A		&eS%5%566E
<< , 2 25<<3H3A!CDD3 +@ K!  	A227%?A A	A  	&225!%& &	&s%   5C<A D#<$D #
E-"EEc                 v    SU -  nUS-  nU[         R                  " U* U5      -  n[        S[        X!5      5      $ )an  Calculates amount of time to wait before a retry attempt.

Wait time grows exponentially with the number of attempts. A
random amount of jitter is added to spread out retry attempts from
different clients.

Args:
  retry_attempt: Retry attempt counter.
  max_wait: Upper bound for wait time [seconds].

Returns:
  Number of seconds to wait before retrying request.

   g      @   )randomuniformmaxmin)retry_attemptmax_wait	wait_time
max_jitters       r   CalculateWaitForRetryrZ      s@      ]"ISJZ88Iq#i*++r   c                   ^^ ST;  a  [         R                  " ST-  5      eU  Vs/ s H  nSU;   d  M  UPM     nnU(       a(  [         R                  " SSR                  U5      -  5      eS m[	        UU4S jU  5       5      $ s  snf )a  Return True iff mime_type is acceptable for one of accept_patterns.

Note that this function assumes that all patterns in accept_patterns
will be simple types of the form "type/subtype", where one or both
of these can be "*". We do not support parameters (i.e. "; q=") in
patterns.

Args:
  accept_patterns: list of acceptable MIME types.
  mime_type: the mime type we would like to match.

Returns:
  Whether or not mime_type matches (at least) one of these patterns.
/zInvalid MIME type: "%s";z.MIME patterns with parameter unsupported: "%s"z, c           	          U S:X  a  Sn [        S [        U R                  S5      UR                  S5      5       5       5      $ )z4Return True iff mime_type is acceptable for pattern.*z*/*c              3   4   #    U  H  u  pUS U4;   v   M     g7f)r_   N ).0acceptprovideds      r   	<genexpr>>AcceptableMimeType.<locals>.MimeTypeMatches.<locals>.<genexpr>   s$      EC 2B6c8_,Cs   r\   )allzipr+   )pattern	mime_types     r   MimeTypeMatches+AcceptableMimeType.<locals>.MimeTypeMatches   sG     c>G E'--,iooc.BCE E 	Er   c              3   6   >#    U  H  nT" UT5      v   M     g 7fNra   )rb   ri   rk   rj   s     r   re   %AcceptableMimeType.<locals>.<genexpr>   s"      /-7 w	22-s   )r   r>   GeneratedClientErrorjoinany)accept_patternsrj   punsupported_patternsrk   s    `  @r   AcceptableMimeTyperv      s     )..%	13 	3'6C!#(AC--<tyy$@& &' 	'E  /-/ / / Ds
   
BBc                 h    U  Vs/ s H   n[         R                  " XS9=(       d    UPM"     sn$ s  snf )z2Reverse parameter remappings for URL construction.)	json_name)encodingGetCustomJsonFieldMapping)rF   request_typert   s      r   MapParamNamesr|      s<      ..|INQN  s   '/c                 ^   [        U 5      nU R                  5        H  u  p4[        R                  " XS9nUb  UR	                  U5      X%'   Un[        U[        R                  5      (       d  MR  [        R                  " [        U5      [        U5      S9=(       d    [        U5      X#'   M     U$ )aw  Perform any renames/remappings needed for URL construction.

Currently, we have several ways to customize JSON encoding, in
particular of field names and enums. This works fine for JSON
bodies, but also needs to be applied for path and query parameters
in the URL.

This function takes a dictionary from param names to values, and
performs any registered mappings. We also need the request type (to
look up the mappings).

Args:
  params: (dict) Map from param names to values
  request_type: (protorpc.messages.Message) request type for this API call

Returns:
  A new dict of the same size, with all registered mappings applied.
)python_name)dictitemsry   rz   popr&   r   EnumGetCustomJsonEnumMappingr-   r@   )rF   r{   
new_params
param_namerL   field_remappings         r   MapRequestParamsr      s    & fJ#\\^
"<<2&*4..*DJ'(JeX]]++%-%F%FUU&5 &C8;E
 " , r   rn   )<   )&__doc__r   rR   r'   	six.movesr   six.moves.urllib.errormovesurlliberrorr   six.moves.urllib.parseparserA   six.moves.urllib.requestrequestr   apitools.base.protorpcliter   apitools.base.pyr   ry   r   PY3collections.abcr   collections__all__r<   r   r	   r0   r7   rN   rZ   rv   r|   r   ra   r   r   <module>r      s   " ; 	  
 ! - - - - 1 1 / 8 '77($ 
 , >:*
 	$N,,!/Hr   