
    uYf-                        d 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
 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 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 erddl!m"Z"  ee#      Z$eZ%dZ& G d de'      Z( G d dejR                        Z* G d de*      Z+ G d de*      Z, G d  d!e*      Z- G d" d#e-      Z. G d$ d%e+      Z/ G d& d'e/      Z0y# e$ r e ZY w xY w)(zSamplers manage the client-side trace sampling

Any `sampled = False` trace won't be written, and can be ignored by the instrumentation.
    N)TYPE_CHECKING)Dict)List)Optional)Tuple   )ENV_KEY)_PRIORITY_CATEGORY)DEFAULT_SAMPLING_RATE_LIMIT)MAX_UINT_64BITS)
get_logger)RateLimiter)_apply_rate_limit)%_get_highest_precedence_rule_matching)_set_sampling_tags)SamplingRule)_config)JSONDecodeError)Spanl   qWV[{c                       e Zd Zy)SamplingErrorN__name__
__module____qualname__     O/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/ddtrace/sampler.pyr   r   /       r   r   c                   4    e Zd ZdZej
                  d        Zy)BaseSamplerr   c                      y Nr   selfspans     r   samplezBaseSampler.sample6   s     	r   N)r   r   r   	__slots__abcabstractmethodr'   r   r   r   r!   r!   3   s    I r   r!   )	metaclassc                   4    e Zd ZdZej
                  d        Zy)BasePrioritySamplerr   c                      y r#   r   )r%   sample_ratess     r   #update_rate_by_service_sample_ratesz7BasePrioritySampler.update_rate_by_service_sample_rates?   s    r   N)r   r   r   r(   r)   r*   r0   r   r   r   r-   r-   <   s    I r   r-   c                       e Zd ZdZd Zy)
AllSamplerzSampler sampling all the tracesc                      y)NTr   r$   s     r   r'   zAllSampler.sampleG   s    r   N)r   r   r   __doc__r'   r   r   r   r2   r2   D   s
    )r   r2   c                   $    e Zd ZdZddZd Zd Zy)RateSamplerzSampler based on a rate

    Keep (100 * `sample_rate`)% of the traces.
    It samples randomly, its main purpose is to reduce the instrumentation footprint.
    c                     |dk  rt        dj                  |            |dkD  rd}| j                  |       t        j	                  dd|z         y )Ng        zsample_rate of {} is negative      ?z.initialized RateSampler, sample %s%% of tracesd   )
ValueErrorformatset_sample_ratelogdebugr%   sample_rates     r   __init__zRateSampler.__init__R   sP    <CCKPQQ3K[)		BC+DUVr   c                 T    t        |      | _        | j                  t        z  | _        y r#   )floatr@   _MAX_UINT_64BITSsampling_id_thresholdr?   s     r   r<   zRateSampler.set_sample_rate]   s#     -%)%5%58H%H"r   c                 T    |j                   t        z  t        z  | j                  k  }|S r#   )_trace_id_64bitsKNUTH_FACTORrD   rE   )r%   r&   sampleds      r   r'   zRateSampler.sampleb   s)    ))L8<LLQUQkQkkr   Nr8   )r   r   r   r4   rA   r<   r'   r   r   r   r6   r6   K   s    	WI
r   r6   c                       e Zd Zy)_AgentRateSamplerNr   r   r   r   rL   rL   g   r   r   rL   c                   Z    e Zd ZdZdZdZe	 	 dd       ZddZ	 	 ddZ	d Z
d	 Zd
 Zd Zy)RateByServiceSamplerzSampler based on a rate, by service

    Keep (100 * `sample_rate`)% of the traces.
    The sample rate is kept independently for each service/env tuple.
    )r@   _by_service_samplers_default_samplerzservice:,env:Nc                 0    | xs d} |xs d}d| z   dz   |z   S )zACompute a key with the same format used by the Datadog agent API. zservice:z,env:r   )serviceenvs     r   _keyzRateByServiceSampler._keyv   s+     -RiRG#g-33r   c                 T    || _         t        | j                         | _        i | _        y r#   )r@   r6   rP   rO   r?   s     r   rA   zRateByServiceSampler.__init__   s%    & +D,<,< =$&!r   c                 T    t        |      | j                  | j                  ||      <   y r#   )rL   rO   rU   )r%   r@   rS   rT   s       r   r<   z$RateByServiceSampler.set_sample_rate   s%     >O{=[!!$))GS"9:r   c                 |    | j                  |      \  }}t        |||j                  | j                  |             |S r#   )_make_sampling_decisionr   r@   _choose_priority_category)r%   r&   rI   samplers       r   r'   zRateByServiceSampler.sample   sC    77=**73		
 r   c                     || j                   u rt        j                  S t        |t              rt        j
                  S t        j                  S r#   )rP   r
   DEFAULT
isinstancerL   AUTORULE)r%   r[   s     r   rZ   z.RateByServiceSampler._choose_priority_category   s?    d+++%---!23%***%***r   c                     |j                  t              }| j                  |j                  |      }| j                  j                  |      xs | j                  }|j                  |      }||fS r#   )get_tagr	   rU   rS   rO   getrP   r'   )r%   r&   rT   keyr[   rI   s         r   rY   z,RateByServiceSampler._make_sampling_decision   s^    ll7#iic*++//4M8M8M..&r   c                 b    i }|j                         D ]  \  }}t        |      ||<    || _        y r#   )itemsrL   rO   )r%   rate_by_servicesamplersrd   r@   s        r   r0   z8RateByServiceSampler.update_rate_by_service_sample_rates   s<     / 5 5 7 	;C-k:HSM	; %-!r   )NNrJ   )rR   rR   )r   r   r   r4   r(   _default_keystaticmethodrU   rA   r<   r'   rZ   rY   r0   r   r   r   rN   rN   k   sS     LI"L4 4' 	\+ -r   rN   c                   Z     e Zd ZdZdZdZeZ	 	 	 d	 fd	Zd Z	e	Z
d Z fdZ fdZ xZS )
DatadogSamplera  
    By default, this sampler relies on dynamic sample rates provided by the trace agent
    to determine which traces are kept or dropped.

    You can also configure a static sample rate via ``default_sample_rate`` to use for sampling.
    When a ``default_sample_rate`` is configured, that is the only sample rate used, and the agent
    provided rates are ignored.

    You may also supply a list of ``SamplingRule`` instances to set sample rates for specific
    services.

    Example rules::

        DatadogSampler(rules=[
            SamplingRule(sample_rate=1.0, service="my-svc"),
            SamplingRule(sample_rate=0.0, service="less-important"),
        ])

    Rules are evaluated in the order they are provided, and the first rule that matches is used.
    If no rule matches, then the agent sample rates are used.

    This sampler can be configured with a rate limit. This will ensure the max number of
    sampled traces per second does not exceed the supplied limit. The default is 100 traces kept
    per second.
    )limiterrulesc                 f   t         t        |           |1t        j                  d      dk7  rt        t        j                        }|t        t        j                        }|.t        j                  }|r| j                  |      }ng }|| _        nSg | _        |D ]G  }t        |t              st        dj                  |            | j                  j!                  |       I |%| j                  j!                  t        |             t#        |      | _        t&        j)                  d|        y)a  
        Constructor for DatadogSampler sampler

        :param rules: List of :class:`SamplingRule` rules to apply to the root span of every trace, default no rules
        :param default_sample_rate: The default sample rate to apply if no rules matched (default: ``None`` /
            Use :class:`RateByServiceSampler` only)
        :param rate_limit: Global rate limit (traces per second) to apply to all traces regardless of the rules
            applied to them, (default: ``100``)
        N_trace_sample_ratedefaultzCRule {!r} must be a sub-class of type ddtrace.sampler.SamplingRules)r@   zinitialized %r)superrl   rA   ddconfig_get_sourcerC   rq   int_trace_rate_limit_trace_sampling_rules_parse_rules_from_env_variablern   r^   r   	TypeErrorr;   appendr   rm   r=   r>   )r%   rn   default_sample_rate
rate_limitenv_sampling_rulesrule	__class__s         r   rA   zDatadogSampler.__init__   s   " 	nd,.&##$89YF&+H,G,G&H#X778J=!)!?!?!;;<NODJDJ (!$5#$i$p$pqu$vww

!!$'( *JJl7JKL #:.		"D)r   c                     | j                   j                         D ci c]  \  }}||j                   }}}dj                  | j                  j
                  || j                  | j                        S c c}}w )Nz.{}(agent_rates={!r}, limiter={!r}, rules={!r}))rO   rf   r@   r;   r   r   rm   rn   )r%   rd   r[   ratess       r   __str__zDatadogSampler.__str__  sg    >B>W>W>]>]>_`lc7g)))``?FFNN##UDLL$**
 	
 as   A4c           	         g }	 t        j                  |      }|D ]  }d|vr-t        dj	                  t        j                  |                  t        |d         }|j                  dt        j                        }|j                  dt        j                        }|j                  dt        j                        }|j                  dt        j                        }		 t        |||||	      }
|j                  |
        |S # t        $ r t        dj	                  |            w xY w# t        $ r3}t        d	j	                  t        j                  |      |            d }~ww xY w)
Nz*Unable to parse DD_TRACE_SAMPLING_RULES={}r@   z-No sample_rate provided for sampling rule: {}rS   nameresourcetags)r@   rS   r   r   r   z#Error creating sampling rule {}: {})jsonloadsr   r:   r;   KeyErrordumpsrC   rc   r   NO_RULEr{   )r%   rn   sampling_rules
json_rulesr   r@   rS   r   r   r   sampling_rulees               r   ry   z-DatadogSampler._parse_rules_from_env_variable  sV   	YE*J  	1DD(NUUVZV`V`aeVfghh] 34Khhy,*>*>?G88FL$8$89Dxx
L,@,@AH88FL$8$89Dd , +W4RZae!
 !!-0	1 #  	YIPPQVWXX	Y  d !F!M!MdjjY]N^`a!bccds#   D D*$D'*	E&3.E!!E&c           	         |j                   j                  |       t        || j                        }| j                  }| j
                  }|r|j                  |      }|j
                  }n2t        t        | '  |      \  }}t        |t              r|j
                  }t        |||| j                  ||             t        ||| j                        }|xr |S r#   )context_update_tagsr   rn   rP   r@   r'   rs   rl   rY   r^   r6   r   #_choose_priority_category_with_ruler   rm   )r%   r&   matched_ruler[   r@   rI   cleared_rate_limitr   s          r   r'   zDatadogSampler.sample'  s    !!$'<T4::N''&&"))$/G&22K$^TRSWXGW';/%1144\7K		
 /tWdllK!-g-r   c                     |rt         j                  S | j                  j                  rt         j                  S t
        t        |   |      S r#   )r
   r`   rm   _has_been_configuredUSERrs   rl   rZ   )r%   r   r[   r   s      r   r   z2DatadogSampler._choose_priority_category_with_rule@  s=    %***<<,,%***^TDWMMr   )NNN)r   r   r   r4   r(   NO_RATE_LIMITr   DEFAULT_RATE_LIMITrA   r   __repr__ry   r'   r   __classcell__)r   s   @r   rl   rl      sM    4 %IM4  	0*d
 H0.2N Nr   rl   )1r4   r)   r   typingr   r   r   r   r   	constantsr	   internal.constantsr
   r   r   rD   internal.loggerr   internal.rate_limiterr   internal.samplingr   r   r   r   r   settingsr   rt   json.decoderr   ImportErrorr:   ddtrace._trace.spanr   r   r=   MAX_TRACE_IDrH   	Exceptionr   ABCMetar!   r-   r2   r6   rL   rN   rl   r   r   r   <module>r      s             2 ; C ' . 0 D 1 ' )!,
 (   "	I 	CKK +  + 8	 	F-. F-RRN) RNq  ! O!s   ,C* *C43C4