
    Ѯh                        d Z ddlZddlZddlZddlZddlmZmZmZm	Z	m
Z
 ddlmZ ddlZddlZddlZddlmZmZmZ ddlZ ej(                  ej*                          ej,                  e      ZdZdZed	   Z G d
 de      Z G d de      Z G d d      Z G d d      Z G d d      Z  G d d      Z! G d d      Z"ddedeee#e#f      fdZ$	 	 d dedeee#e#f      dee#   fdZ% G d d      Z&y)!zxFirebase Remote Config Module.
This module has required APIs for the clients to use Firebase Remote Config with python.
    N)DictOptionalLiteralUnionAny)Enum)App_http_client_utils)level_remoteconfig
   )defaultremotestaticc                        e Zd ZdZdZdZdZdZy)PercentConditionOperatorzFEnum representing the available operators for percent conditions.
    LESS_OR_EQUALGREATER_THANBETWEENUNKNOWNN)__name__
__module____qualname____doc__r   r   r   r        n/home/www/academy-backend.kofcorporation.com/venv/lib/python3.12/site-packages/firebase_admin/remote_config.pyr   r   '   s    #M!LGGr   r   c                   T    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdZy)CustomSignalOperatorzLEnum representing the available operators for custom signal conditions.
    STRING_CONTAINSSTRING_DOES_NOT_CONTAINSTRING_EXACTLY_MATCHESSTRING_CONTAINS_REGEXNUMERIC_LESS_THANNUMERIC_LESS_EQUALNUMERIC_EQUALNUMERIC_NOT_EQUALNUMERIC_GREATER_THANNUMERIC_GREATER_EQUALSEMANTIC_VERSION_LESS_THANSEMANTIC_VERSION_LESS_EQUALSEMANTIC_VERSION_EQUALSEMANTIC_VERSION_NOT_EQUALSEMANTIC_VERSION_GREATER_THANSEMANTIC_VERSION_GREATER_EQUALr   N)r   r   r   r   r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r   r   r   r   r    r    /   sj    'O753+-#M+13!="?5!=$C!%E"Gr   r    c                   f    e Zd ZdZd Zed        Zed        Zed        Zed        Z	ed        Z
y)	_ServerTemplateDataz>Parses, validates and encapsulates template data and metadata.c                 J   d|v r|d   |d   | _         nt        d      i | _         d|v r|d   |d   | _        nt        d      g | _        d| _        d|v r
|d   | _        d| _        d|v rt        |d   t              r
|d   | _        t        j                  |      | _	        y)	zInitializes a new ServerTemplateData instance.

        Args:
            template_data: The data to be parsed for getting the parameters and conditions.

        Raises:
            ValueError: If the template data is not valid.
        
parametersNz2Remote Config parameters must be a non-null object
conditionsz2Remote Config conditions must be a non-null object versionetag)
_parameters
ValueError_conditions_version_etag
isinstancestrjsondumps_template_data_json)selftemplate_datas     r   __init__z_ServerTemplateData.__init__F   s     =(\*6#0#>  !UVV!D=(\*6#0#>  !UVV!D%))4DM
]"z-2G'M&v.DJ#'::m#< r   c                     | j                   S N)r9   rC   s    r   r4   z_ServerTemplateData.parametersi       r   c                     | j                   S rG   )r=   rH   s    r   r8   z_ServerTemplateData.etagm   s    zzr   c                     | j                   S rG   )r<   rH   s    r   r7   z_ServerTemplateData.versionq   s    }}r   c                     | j                   S rG   )r;   rH   s    r   r5   z_ServerTemplateData.conditionsu   rI   r   c                     | j                   S rG   )rB   rH   s    r   template_data_jsonz&_ServerTemplateData.template_data_jsony   s    '''r   N)r   r   r   r   rE   propertyr4   r8   r7   r5   rN   r   r   r   r2   r2   D   so    H!=F             ( (r   r2   c                   v    e Zd ZdZddedeeeef      fdZd Z	ddeeee
eef   f      dd	fd
ZdefdZd Zy)ServerTemplatezZRepresents a Server Template with implementations for loading and evaluating the template.Nappdefault_configc                     t        j                  |t        t              | _        d| _        i | _        t        j                         | _	        |#|D ]  }t        ||         | j                  |<    yy)a  Initializes a ServerTemplate instance.

        Args:
          app: App instance to be used. This is optional and the default app instance will
                be used if not present.
          default_config: The default config to be used in the evaluated config.
        N)r   get_app_service_REMOTE_CONFIG_ATTRIBUTE_RemoteConfigService_rc_service_cache_stringified_default_config	threadingRLock_lockr?   )rC   rR   rS   keys       r   rE   zServerTemplate.__init__   sw     "11#2JL`b ;=(__&

 %% Q8;N3<O8P005Q &r   c                    K   | j                   j                          d{   }| j                  5  || _        ddd       y7 !# 1 sw Y   yxY ww)z0Fetches the server template and caches the data.N)rX   get_server_templater]   rY   )rC   rc_server_templates     r   loadzServerTemplate.load   sL     #'#3#3#G#G#IIZZ 	-,DK	- 	- J	- 	-s%   AAAA
AA	AcontextreturnServerConfigc                    | j                   st        d      |xs i }i }| j                  5  | j                   j                  }| j                   j                  }ddd       | j
                  1| j
                  j                         D ]  \  }}t        d|      ||<    t        ||      | _	        t        | j                  j                               S # 1 sw Y   }xY w)a"  Evaluates the cached server template to produce a ServerConfig.

        Args:
          context: A dictionary of values to use for evaluating conditions.

        Returns:
          A ServerConfig object.
        Raises:
            ValueError: If the input arguments are invalid.
        zmNo Remote Config Server template in cache.
                            Call load() before calling evaluate().Nr   )config_values)rY   r:   r]   r5   r4   rZ   items_Value_ConditionEvaluator
_evaluatorre   evaluate)rC   rc   rg   template_conditionstemplate_parametersr^   values          r   rl   zServerTemplate.evaluate   s     {{ F G G-RZZ 	9"&++"8"8"&++"8"8	9
 ++7">>DDF >
U%+Iu%=c">-.A.A7.;= $//*B*B*DEE	9 	9s   -CCrN   c                     t        j                  |      }t        |      }| j                  5  || _        ddd       y# 1 sw Y   yxY w)zUpdates the cache to store the given template is of type ServerTemplateData.

        Args:
          template_data_json: A json string representing ServerTemplateData to be cached.
        N)r@   loadsr2   r]   rY   )rC   rN   template_data_maprD   s       r   setzServerTemplate.set   sB     !JJ'9:+,=>ZZ 	('DK	( 	( 	(s	   >Ac                     | j                   st        d      | j                  5  | j                   j                  }ddd       |S # 1 sw Y   S xY w)zRProvides the server template in a JSON format to be used for initialization later.zkNo Remote Config Server template in cache.
                            Call load() before calling toJSON().N)rY   r:   r]   rN   )rC   template_jsons     r   to_jsonzServerTemplate.to_json   sP    {{ D E EZZ 	; KK::M	;	;s   AANNrG   )r   r   r   r   r	   r   r   r?   rE   rb   r   intrl   rs   rv   r   r   r   rQ   rQ   ~   sl    dQC Qc3h8P Q.-Fc5c?.B)C D FP^ F>
(c 
(r   rQ   c                   :    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
y	)
re   z.Represents a Remote Config Server Side Config.c                     || _         y rG   )_config_values)rC   rg   s     r   rE   zServerConfig.__init__   s
    +r   c                 @    | j                  |      j                         S )Returns the value as a boolean.)
_get_value
as_booleanrC   r^   s     r   get_booleanzServerConfig.get_boolean       s#..00r   c                 @    | j                  |      j                         S )Returns the value as a string.)r~   	as_stringr   s     r   
get_stringzServerConfig.get_string   s    s#--//r   c                 @    | j                  |      j                         S )z Returns the value as an integer.)r~   as_intr   s     r   get_intzServerConfig.get_int   s    s#**,,r   c                 @    | j                  |      j                         S )zReturns the value as a float.)r~   as_floatr   s     r   	get_floatzServerConfig.get_float   s    s#,,..r   c                 @    | j                  |      j                         S z Returns the source of the value.)r~   
get_sourcer   s     r   get_value_sourcezServerConfig.get_value_source   r   r   c                 L    | j                   j                  |t        d            S )Nr   )r{   getri   r   s     r   r~   zServerConfig._get_value   s     ""&&sF8,<==r   N)r   r   r   r   rE   r   r   r   r   r   r~   r   r   r   re   re      s(    8,10-/1>r   re   c                   8    e Zd ZdZd Zd Zd Zedefd       Z	y)rW   zhInternal class that facilitates sending requests to the Firebase Remote
        Config backend API.
    c                    d}|j                   | _        |j                  j                         }ddt        j
                   i}|j                  j                  dt        j                        }t        j                  ||||      | _        y)zInitialize a JsonHttpClient with necessary inputs.

        Args:
            app: App instance to be used for fetching app specific details required
                for initializing the http client.
        z+https://firebaseremoteconfig.googleapis.comzX-FIREBASE-CLIENTzfire-admin-python/httpTimeout)
credentialbase_urlheaderstimeoutN)
project_id_project_idr   get_credentialfirebase_admin__version__optionsr   r
   DEFAULT_TIMEOUT_SECONDSJsonHttpClient_client)rC   rR   remote_config_base_urlapp_credential
rc_headersr   s         r   rE   z_RemoteConfigService.__init__   s|     "O>>668#5n6P6P5Q!RV
++//-1U1UV#22n<R;EwXr   c                 d  K   	 t        j                         }|j                  d| j                  j                  d| j                                d{   \  }}|j                  d      |d<   t        |      S 7 &# t        j                  j                  $ r}| j                  |      d}~ww xY ww)zRequests for a server template and converts the response to an instance of
        ServerTemplateData for storing the template parameters and conditions.Nr   r8   )asyncioget_event_looprun_in_executorr   headers_and_body_get_urlrequests
exceptionsRequestException_handle_remote_config_errorr   r2   )rC   loopr   rD   errors        r   r`   z(_RemoteConfigService.get_server_template  s     	:))+D+/+?+?@D@]@]@Et}},X &X"G]
 !(F 3f"=11&X ""33 	:22599	:s;   B0AA: A8A: B08A: :B-B((B--B0c                 "    d| j                    dS )zJReturns project prefix for url, in the format of /v1/projects/${projectId}z/v1/projects/z./namespaces/firebase-server/serverRemoteConfig)r   rH   s    r   r   z_RemoteConfigService._get_url  s    t//00^__r   r   c                 ,    t        j                  |      S )z5Handles errors received from the Cloud Functions API.)r   #handle_platform_error_from_requests)clsr   s     r   r   z0_RemoteConfigService._handle_remote_config_error  s     99%@@r   N)
r   r   r   r   rE   r`   r   classmethodr   r   r   r   r   rW   rW      s6    X$2` A A Ar   rW   c                       e Zd ZdZd Zd Zdeeef   fdZ		 dde
defdZ	 dde
defdZ	 dde
defd	Zdefd
Zdede
fdZdefdZdefdZdefdZdefdZdefdZy)rj   z_Internal class that facilitates sending requests to the Firebase Remote
    Config backend API.c                 <    || _         || _        || _        || _        y rG   )_contextr;   r9   r{   )rC   r5   r4   rc   rg   s        r   rE   z_ConditionEvaluator.__init__  s!    %%+r   c                    | j                  | j                  | j                        }| j                  r2| j                  j	                         D ]  \  }}|j                  di       }|j                  di       }d}|r&|j	                         D ]  \  }}||v s|s||   } n |r(|j                  d      rt        j                  d|       |r+|j                  d      }	t        d|	      | j                  |<   |st        j                  d|       |j                  d      rt        j                  d|       t        d|j                  d            | j                  |<    | j                  S )	z]Internal function that evaluates the cached server template to produce
        a ServerConfigconditionalValuesdefaultValueNuseInAppDefaultz'Using in-app default value for key '%s'ro   r   z#No default value found for key '%s')evaluate_conditionsr;   r   r9   rh   r   loggerinfori   r{   warning)
rC   evaluated_conditionsr^   	parameterconditional_valuesdefault_valueparameter_value_wrappercondition_namecondition_evaluationparameter_values
             r   rl   z_ConditionEvaluator.evaluate%  sn     $778H8H$--X "&"2"2"8"8": XY%.]]3F%K" )nb A*.' (@T@Z@Z@\ "<(<)-??DX6H6X3!"
 +/F/J/JK\/]KK I3O*&=&A&A'&JO/5h/PD'',$NN#H#N $$%67KK I3O+1(M<M<Mg<V+W##C(9X: """r   rd   c                 ~    i }|D ]5  }| j                  |j                  d      |      ||j                  d      <   7 |S )a%  Evaluates a list of conditions and returns a dictionary of results.

        Args:
          conditions: A list of NamedCondition objects.
          context: An EvaluationContext object.

        Returns:
          A dictionary that maps condition names to boolean evaluation results.
        	conditionname)evaluate_conditionr   )rC   r5   rc   r   r   s        r   r   z'_ConditionEvaluator.evaluate_conditionsK  sN      "# 	I:>:Q:Qk*G; v!67	 $#r   nesting_levelc                 T   |t         k\  rt        j                  d       y|j                  d      %| j	                  |j                  d      ||dz         S |j                  d      %| j                  |j                  d      ||dz         S |j                  d      y|j                  d      y|j                  d	      !| j                  |j                  d	      |      S |j                  d
      !| j                  |j                  d
      |      S t        j                  d       y)a  Recursively evaluates a condition.

        Args:
          condition: The condition to evaluate.
          context: An EvaluationContext object.
          nesting_level: The current recursion depth.

        Returns:
          The boolean result of the condition evaluation.
        z+Maximum condition recursion depth exceeded.ForCondition   andConditiontrueTfalsepercentcustomSignalz#Unknown condition type encountered.)MAX_CONDITION_RECURSION_DEPTHr   r   r   evaluate_or_conditionevaluate_and_conditionevaluate_percent_condition evaluate_custom_signal_condition)rC   r   rc   r   s       r   r   z&_ConditionEvaluator.evaluate_condition\  s    99NNHI=='3--immM.J.5}q7HJ J==(4..y}}^/L/68IK K== ,==!-==#/229==3KWUU==(488~9VX_``<=r   c                 p    |j                  d      xs g }|D ]  }| j                  |||dz         }|s y y)a&  Evaluates an OR condition.

        Args:
          or_condition: The OR condition to evaluate.
          context: An EvaluationContext object.
          nesting_level: The current recursion depth.

        Returns:
          True if any of the subconditions are true, False otherwise.
        r5   r   TFr   r   )rC   or_conditionrc   r   sub_conditionssub_conditionresults          r   r   z)_ConditionEvaluator.evaluate_or_condition|  sM     &)),7=2+ 	M,,]G]UVEVWF	 r   c                 p    |j                  d      xs g }|D ]  }| j                  |||dz         }|r y y)a(  Evaluates an AND condition.

        Args:
          and_condition: The AND condition to evaluate.
          context: An EvaluationContext object.
          nesting_level: The current recursion depth.

        Returns:
          True if all of the subconditions are met; False otherwise.
        r5   r   FTr   )rC   and_conditionrc   r   r   r   r   s          r   r   z*_ConditionEvaluator.evaluate_and_condition  sM     '**<8>B+ 	M,,]G]UVEVWF	 r   c                    |j                  d      st        j                  d       y|j                  d      }|j                  d      }|j                  d      }|j                  d      }|st        j                  d       y|r+|j                  d	      xs d
}|j                  d      xs d
}nd
}d
}|r|}	nd
}	|r| dnd}
|
 |j                  d       }| j                  |      }|dz  }|t        j
                  j                  k(  r||	k  S |t        j                  j                  k(  r||	kD  S |t        j                  j                  k(  r||cxk  xr |k  S c S t        j                  d|       y)zEvaluates a percent condition.

        Args:
          percent_condition: The percent condition to evaluate.
          context: An EvaluationContext object.

        Returns:
          True if the condition is met, False otherwise.
        randomization_idzEMissing randomization_id in context for evaluating percent condition.FseedpercentOperatormicroPercentmicroPercentRangez/Missing percent operator for percent condition.microPercentUpperBoundr   microPercentLowerBound.r6   i zUnknown percent operator: %s)	r   r   r   hash_seeded_randomization_idr   r   ro   r   r   )rC   percent_conditionrc   r   percent_operatormicro_percentmicro_percent_rangenorm_percent_upper_boundnorm_percent_lower_boundnorm_micro_percentseed_prefixstring_to_hashhash64instance_micro_percentiles                 r   r   z._ConditionEvaluator.evaluate_percent_condition  s    {{-.NNbc $$V,,001BC)--n=/334GHNNLM':'>'>?W'X']\]$':'>'>?W'X']\]$'($'($!.!"$(ajb'=5G)H(IJ22>B$*m$<!7EEKKK,0BBB7DDJJJ,/AAA7??EEE+.GcKccccc57GHr   seeded_randomization_idc                     t        j                         }|j                  |j                  d             |j	                         }t        t        |d            S )zHashes a seeded randomization ID.

        Args:
          seeded_randomization_id: The seeded randomization ID to hash.

        Returns:
          The hashed value.
        zutf-8   )hashlibsha256updateencode	hexdigestabsrx   )rC   r   hash_objectr   s       r   r   z0_ConditionEvaluator.hash_seeded_randomization_id  sI     nn&299'BC&&(3vr?##r   c                    |j                  d      xs i }|j                  d      xs i }|j                  d      xs i }t        |||g      st        j                  d       y|sy|j                  |      xs i }|st        j	                  d|       y|t
        j                  j                  k(  r| j                  ||d       S |t
        j                  j                  k(  r| j                  ||d        S |t
        j                  j                  k(  r| j                  ||d	       S |t
        j                  j                  k(  r!| j                  ||t        j                        S |t
        j                  j                  k(  r| j                  ||d
   |d       S |t
        j                   j                  k(  r| j                  ||d
   |d       S |t
        j"                  j                  k(  r| j                  ||d
   |d       S |t
        j$                  j                  k(  r| j                  ||d
   |d       S |t
        j&                  j                  k(  r| j                  ||d
   |d       S |t
        j(                  j                  k(  r| j                  ||d
   |d       S |t
        j*                  j                  k(  r| j-                  ||d
   |d       S |t
        j.                  j                  k(  r| j-                  ||d
   |d       S |t
        j0                  j                  k(  r| j-                  ||d
   |d       S |t
        j2                  j                  k(  r| j-                  ||d
   |d       S |t
        j4                  j                  k(  r| j-                  ||d
   |d       S |t
        j6                  j                  k(  r| j-                  ||d
   |d       S t        j                  d|       y)a  Evaluates a custom signal condition.

        Args:
          custom_signal_condition: The custom signal condition to evaluate.
          context: An EvaluationContext object.

        Returns:
          True if the condition is met, False otherwise.
        customSignalOperatorcustomSignalKeytargetCustomSignalValueszDMissing operator, key, or target values for custom signal condition.Fz,Custom signal value not found in context: %sc                 
    | |v S rG   r   targetactuals     r   <lambda>zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>  s    &@P r   c                 
    | |v S rG   r   r  s     r   r  zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>  s    FfDT r   c                 D    | j                         |j                         k(  S rG   )stripr  s     r   r  zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>  s    RXR^R^R`@` r   r   c                     | dk  S Nr   r   rs    r   r  zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>  
    1q5 r   c                     | dk  S r  r   r  s    r   r  zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>  
    16 r   c                     | dk(  S r  r   r  s    r   r  zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>  r  r   c                     | dk7  S r  r   r  s    r   r  zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>   r  r   c                     | dkD  S r  r   r  s    r   r  zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>%  r  r   c                     | dk\  S r  r   r  s    r   r  zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>*  r  r   c                     | dk  S r  r   r  s    r   r  zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>1  
    QU r   c                     | dk  S r  r   r  s    r   r  zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>6  
    Q!V r   c                     | dk(  S r  r   r  s    r   r  zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>;  r  r   c                     | dk7  S r  r   r  s    r   r  zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>@  r  r   c                     | dkD  S r  r   r  s    r   r  zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>E  r  r   c                     | dk\  S r  r   r  s    r   r  zF_ConditionEvaluator.evaluate_custom_signal_condition.<locals>.<lambda>J  r  r   z"Unknown custom signal operator: %s)r   allr   r   debugr    r!   ro   _compare_stringsr"   r#   r$   researchr%   _compare_numbersr&   r'   r(   r)   r*   r+   _compare_semantic_versionsr,   r-   r.   r/   r0   )rC   custom_signal_conditionrc   custom_signal_operatorcustom_signal_keytarget_custom_signal_valuesactual_custom_signal_values          r   r   z4_ConditionEvaluator.evaluate_custom_signal_condition  s`    "9!<!<=S!T!ZXZ3778IJPb#''(BCIr 	$ *,=?Z[\NNab*%,[[1B%C%Ir")LLGIZ[!%9%I%I%O%OO(()D)C)PR R "%9%Q%Q%W%WW,,-H-G-TV V V "%9%P%P%V%VV(()D)C)`b b "%9%O%O%U%UU(()D)C)+4 4
 "%9%K%K%Q%QQ(():)DQ)G)C)8: : "%9%L%L%R%RR(():)DQ)G)C)9; ; "%9%G%G%M%MM(():)DQ)G)C)9; ; "%9%K%K%Q%QQ(():)DQ)G)C)9; ; "%9%N%N%T%TT(():)DQ)G)C)8: : "%9%O%O%U%UU(():)DQ)G)C)9; ; "%9%T%T%Z%ZZ223D3Nq3Q3M3BD D "%9%U%U%[%[[223D3Nq3Q3M3CE E "%9%P%P%V%VV223D3Nq3Q3M3CE E "%9%T%T%Z%ZZ223D3Nq3Q3M3CE E "%9%W%W%]%]]223D3Nq3Q3M3BD D "%9%X%X%^%^^223D3Nq3Q3M3CE E 	;=STr   c                 :    |D ]  } ||t        |            s y y)aj  Compares the actual string value of a signal against a list of target values.

        Args:
            target_values: A list of target string values.
            actual_value: The actual value to compare, which can be a string or number.
            predicate_fn: A function that takes two string arguments (target and actual)
                            and returns a boolean indicating whether
                            the target matches the actual value.

        Returns:
            bool: True if the predicate function returns True for any target value in the list,
                False otherwise.
        TF)r?   )rC   target_valuesactual_valuepredicate_fnr	  s        r   r$  z$_ConditionEvaluator._compare_stringsN  s*     $ 	FFC$56	 r   c                     	 t        |      }t        |      }||k  rdn||kD  rdnd} ||      S # t        $ r t        j                  d|       Y yw xY w)Nr   r   z>Invalid numeric value for comparison for custom signal key %s.F)floatr:   r   r   )rC   r+  target_valuer0  r1  r	  r
  r   s           r   r'  z$_ConditionEvaluator._compare_numbersb  s_    	<(F<(F!F?RVf_!F'' 	NN[,.	s   -0 AAc                 N    | j                  |t        |      t        |      |      S )a  Compares the actual semantic version value of a signal against a target value.
        Calls the predicate function with -1, 0, 1 if actual is less than, equal to,
        or greater than target.

        Args:
        custom_signal_key: The custom signal for which the evaluation is being performed.
        target_values: A list of target string values.
        actual_value: The actual value to compare, which can be a string or number.
        predicate_fn: A function that takes an integer (-1, 0, or 1) and returns a boolean.

        Returns:
            bool: True if the predicate function returns True for the result of the comparison,
        False otherwise.
        )_compare_versionsr?   )rC   r+  r5  r0  r1  s        r   r(  z._ConditionEvaluator._compare_semantic_versionsm  s-      %%&7\9J&),&7G 	Gr   c                 d   	 |j                  d      D cg c]  }t        |       }}|j                  d      D cg c]  }t        |       }}t        t        |      t        |            }|j	                  dg|t        |      z
  z         |j	                  dg|t        |      z
  z         t        ||      D ]<  \  }	}
t        |	dk  |
dk  f      rt        |	|
k  r
 |d      c S |	|
kD  s4 |d      c S   |d      S c c}w c c}w # t        $ r t        j                  d|       Y yw xY w)a  Compares two semantic version strings.

        Args:
            custom_signal_key: The custom singal for which the evaluation is being performed.
            sem_version_1: The first semantic version string.
            sem_version_2: The second semantic version string.
            predicate_fn: A function that takes an integer and returns a boolean.

        Returns:
            bool: The result of the predicate function.
        r   r   r3  r   zHInvalid semantic version format for comparison for custom signal key %s.F)
splitrx   maxlenextendzipanyr:   r   r   )rC   r+  sem_version_1sem_version_2r1  partv1_partsv2_parts
max_lengthpart1part2s              r   r7  z%_ConditionEvaluator._compare_versions  s,   	.;.A.A#.FGdD	GHG.;.A.A#.FGdD	GHGS]CM:JOOQC:H#=>?OOQC:H#=>? #Hh 7 +u	519-.$$5='++5='?*+  ?" HG  	NNZ!# 		s?   D DD DBD *D 0	D :D 
D D/.D/N)r   )r   r   r   r   rE   rl   r   r?   boolr   rx   r   r   r   r   r   r   r$  r'  r(  r7  r   r   r   rj   rj     s    ,$#L$c4i $$ 12*-6:D 45-09=, 56.1:>(,/3,Z$C $C $m59m^T (	_c 	GPTG& IM r   rj   rR   rS   c                 \   K   t        | |      }|j                          d{    |S 7 w)a  Initializes a new ServerTemplate instance and fetches the server template.

    Args:
        app: App instance to be used. This is optional and the default app instance will
            be used if not present.
        default_config: The default config to be used in the evaluated config.

    Returns:
        ServerTemplate: An object having the cached server template to be used for evaluation.
    rR   rS   N)init_server_templaterb   )rR   rS   templates      r   r`   r`     s-      $NKH
--/O s   !,*,rN   c                 F    t        | |      }||j                  |       |S )a  Initializes a new ServerTemplate instance.

    Args:
        app: App instance to be used. This is optional and the default app instance will
            be used if not present.
        default_config: The default config to be used in the evaluated config.
        template_data_json: An optional template data JSON to be set on initialization.

    Returns:
        ServerTemplate: A new ServerTemplate instance initialized with an optional
        template and config.
    rI  )rQ   rs   )rR   rS   rN   rK  s       r   rJ  rJ    s(     #nEH%'(Or   c                   x    e Zd ZdZdZdZdZdZg dZefde	de
fd	Zd
e
fdZd
efdZd
efdZd
efdZd
e	fdZy)ri   z3Represents a value fetched from Remote Config.
    Fr6   r   g        )1r   tyesyonsourcero   c                      || _         || _        y)a  Initializes a Value instance.

        Args:
          source: The source of the value (e.g., 'default', 'remote', 'static').
          "static" indicates the value was defined by a static constant.
          "default" indicates the value was defined by default config.
          "remote" indicates the value was defined by config produced by evaluating a template.
          value: The string value.
        N)rS  ro   )rC   rS  ro   s      r   rE   z_Value.__init__  s     
r   rd   c                 b    | j                   dk(  r| j                  S t        | j                        S )r   r   )rS  DEFAULT_VALUE_FOR_STRINGr?   ro   rH   s    r   r   z_Value.as_string  s(    ;;("0004::r   c                     | j                   dk(  r| j                  S t        | j                        j	                         | j
                  v S )r}   r   )rS  DEFAULT_VALUE_FOR_BOOLEANr?   ro   lowerBOOLEAN_TRUTHY_VALUESrH   s    r   r   z_Value.as_boolean  s<    ;;("1114::$$&$*D*DDDr   c                     | j                   dk(  r| j                  S 	 t        | j                        S # t        $ r | j                  cY S w xY wzReturns the value as a number.r   )rS  DEFAULT_VALUE_FOR_INTEGERrx   ro   r:   rH   s    r   r   z_Value.as_int  sH    ;;("111	2tzz?" 	2111	2   2 A
	A
c                     | j                   dk(  r| j                  S 	 t        | j                        S # t        $ r | j                  cY S w xY wr\  )rS  DEFAULT_VALUE_FOR_FLOAT_NUMBERr4  ro   r:   rH   s    r   r   z_Value.as_float  sI    ;;("666	7$$ 	7666	7r^  c                     | j                   S r   )rS  rH   s    r   r   z_Value.get_source  s    {{r   N)r   r   r   r   rX  rV  r]  r`  rZ  ValueSourcer?   rE   r   rG  r   r4  r   r   r   r   r   r   ri   ri     sy     %! !%("@9Q { 3 3 ED E2 27% 7K r   ri   rw   )NNN)'r   r   r@   loggingr[   typingr   r   r   r   r   enumr   r%  r   r   r   r	   r
   r   basicConfigINFO	getLoggerr   r   rV   r   rb  r   r    r2   rQ   re   rW   rj   r?   r`   rJ  ri   r   r   r   <module>ri     s'       6 6  	   4 4    ',, '			8	$*  " 34t 4 *7( 7(tQ Qh> >:*A *AZD DL3 xSRUX?W  VZ=Ac (4S>:R -5c]&6 6r   