U 췀g7 @sxddlZddlZddlZddlmZmZmZddlZddlmZm Z m Z ddl m Z ddl mZmZmZmZddlmZerddlmZmZmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlm Z ddlm!Z!ddl"m#Z#m$Z$edZ%e!dZ&ddl'Zddl(m)Z)m*Z*m+Z+m,Z,Gddde#ddZ-Gddde-ddZ.e#dde/iZ0dZ1dZ2d Z3d!Z4d"Z5d#Z6d$Z7d%Z8e4gZ9e7e7e7e5e4e7e5e5e5d& Z:d'd(Z;Gd)d*d*ZGd/d0d0e=Z?er"ed8d1d2Z@ed3d2Z@d9d4d2Z@dd5lAmBZBmCZCmDZDmEZEmFZFeGeHd6eIdd7lJmKZKW5QRXdS):N)datetime timedeltatimezone) INSTRUMENTER SPANSTATUSSPANDATA)get_profiler_id)get_current_thread_metais_valid_sample_rateloggernanosecond_time) TYPE_CHECKING)CallableMappingMutableMapping)Any)Dict)Iterator)List)Optional)overload) ParamSpec)Tuple)Union)TypeVar) TypedDictUnpackPR)EventMeasurementUnitSamplingContextMeasurementValuec@seZdZUeed<eed<eed<eed<eed<eed<eed<eded <eed <ed ed <eeee fed <ded<eed<eed<dS) SpanKwargstrace_idspan_idparent_span_idsame_process_as_parentsampledop descriptionzsentry_sdk.Hubhubstatus Transactioncontaining_transactionstart_timestampzsentry_sdk.ScopescopeoriginnameN) __name__ __module__ __qualname__str__annotations__boolrrrfloatr:r:@/opt/hc_python/lib/python3.8/site-packages/sentry_sdk/tracing.pyr#,s   r#F)totalc@s&eZdZUeed<eed<ded<dS)TransactionKwargssourceparent_sampledBaggagebaggageN)r3r4r5r6r7r8r:r:r:r;r=gs r=ProfileContext profiler_idrAz sentry-traceZcustomurlZrouteview componenttask) ZendpointZ function_name handler_nameZmethod_and_path_patternpathZ route_nameZ route_patternZ uri_templaterDcCs|dkrtjSd|kr"dkrnn\|dkr4tjS|dkrBtjS|dkrPtjS|dkr^tjS|dkrltjS|dkrztjStjSnHd|krd krnn0|d krtj S|d krtj S|d krtj Stj Stj S) z Returns the Sentry status corresponding to the given HTTP status code. See: https://develop.sentry.dev/sdk/event-payloads/contexts/#trace-context iiiiiiiiiXiii)rOKZPERMISSION_DENIED NOT_FOUNDZRESOURCE_EXHAUSTEDZFAILED_PRECONDITIONZUNAUTHENTICATEDZALREADY_EXISTSZINVALID_ARGUMENTZDEADLINE_EXCEEDEDZ UNIMPLEMENTED UNAVAILABLEINTERNAL_ERROR UNKNOWN_ERROR)Zhttp_status_coder:r:r;get_span_status_from_http_codes2rOc@s$eZdZdZdZddZddZdS) _SpanRecorderz5Limits the number of spans recorded in a transaction.maxlenspanscCs|d|_g|_dS)NrQselfrRr:r:r;__init__s z_SpanRecorder.__init__cCs(t|j|jkrd|_n |j|dSN)lenrSrR_span_recorderappend)rVspanr:r:r;addsz_SpanRecorder.addN)r3r4r5__doc__ __slots__rWr]r:r:r:r;rPs rPc@seZdZdZdZd=ddZdd Zd d Zd d ZddZ ddZ e ddZ e jfddZeddZeddZddZeddZddZd d!Zd"d#Zd$d%Zd&d'Zd>d)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd?d3d4Zd5d6Z d7d8Z!d9d:Z"d;d<Z#dS)@SpanakA span holds timing information of a block of code. Spans can have multiple child spans thus forming a span tree. :param trace_id: The trace ID of the root span. If this new span is to be the root span, omit this parameter, and a new trace ID will be generated. :param span_id: The span ID of this span. If omitted, a new span ID will be generated. :param parent_span_id: The span ID of the parent span, if applicable. :param same_process_as_parent: Whether this span is in the same process as the parent span. :param sampled: Whether the span should be sampled. Overrides the default sampling decision for this span when provided. :param op: The span's operation. A list of recommended values is available here: https://develop.sentry.dev/sdk/performance/span-operations/ :param description: A description of what operation is being performed within the span. .. deprecated:: 2.15.0 Please use the `name` parameter, instead. :param name: A string describing what operation is being performed within the span. :param hub: The hub to use for this span. .. deprecated:: 2.0.0 Please use the `scope` parameter, instead. :param status: The span's status. Possible values are listed at https://develop.sentry.dev/sdk/event-payloads/span/ :param containing_transaction: The transaction that this span belongs to. :param start_timestamp: The timestamp when the span started. If omitted, the current time will be used. :param scope: The scope to use for this span. If not provided, we use the current scope. )r$r%r&r'r(r)r* _measurementsr/_start_timestamp_monotonic_nsr, timestamp_tags_datarZr+_context_manager_state_containing_transaction_local_aggregatorr0r1r2NTmanualcCs |p tj|_|p$tjdd|_||_||_||_||_|pF||_ | |_ ||_ | |_ | |_ i|_i|_i|_| |_|dk rtjdtdd|j p|j |_ | dkrttj} nt| trt| tj} | |_z t|_Wntk rYnXd|_ d|_!d|_"|#|$t%dS)Nz>The `hub` parameter is deprecated. Please use `scope` instead. stacklevel)&uuiduuid4hexr$r%r&r'r(r)r*r,r+r0r1rardrergwarningswarnDeprecationWarningrnowrutc isinstancer9 fromtimestampr/r rbAttributeErrorrcrZrhupdate_active_threadset_profiler_idr)rVr$r%r&r'r(r)r*r+r,r.r/r0r1r2r:r:r;rWsH   z Span.__init__cCs|jdkrt||_dSrX)rZrPrUr:r:r;init_span_recorderQs zSpan.init_span_recordercCs|j}|dkrt}|_|SrX)rhLocalAggregatorrVrvr:r:r;_get_local_aggregatorVs zSpan._get_local_aggregatorc Cs*d|jj|j|j|j|j|j|j|jfS)Nz^<%s(op=%r, description:%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r, origin=%r)>) __class__r3r)r*r$r%r&r(r1rVr:r:r;__repr__]sz Span.__repr__cCs(|jp t}|j}||_||f|_|SrX)r0 sentry_sdkget_current_scoper\rf)rVr0old_spanr:r:r; __enter__ms  zSpan.__enter__cCs6|dk r|tj|j\}}|`||||_dSrX) set_statusrrMrffinishr\)rVtyvaluetbr0rr:r:r;__exit__us    z Span.__exit__cCs|jS)zThe ``Transaction`` that this span belongs to. The ``Transaction`` is the root of the span tree, so one could also think of this ``Transaction`` as the "root span".)rgrr:r:r;r.s zSpan.containing_transactioncKs|ddk rtjdtddtjd}||kr:tS|d|j t f|j |j |j d|}|j op|j j}|r|||S) a Start a sub-span from the current span or transaction. Takes the same arguments as the initializer of :py:class:`Span`. The trace id, sampling decision, transaction pointer, and span recorder are inherited from the current span/transaction. The instrumenter parameter is deprecated for user code, and it will be removed in the next major version. Going forward, it should only be used by the SDK itself. r*NzEThe `description` parameter is deprecated. Please use `name` instead.rkrl instrumenterr()r$r&r.)getrqrrrsr get_clientoptionsNoOpSpan setdefaultr(r`r$r%r.rZr])rVrkwargsZconfiguration_instrumenterchildZ span_recorderr:r:r; start_childs,   zSpan.start_childcKs$|tkrtdtjt|f|S)a( Create a Transaction with the given params, then add in data pulled from the ``sentry-trace`` and ``baggage`` headers from the environ (if any) before returning the Transaction. This is different from :py:meth:`~sentry_sdk.tracing.Span.continue_from_headers` in that it assumes header names in the form ``HTTP_HEADER_NAME`` - such as you would get from a WSGI/ASGI environ - rather than the form ``header-name``. :param environ: The ASGI/WSGI environ to pull information from. zXDeprecated: use Transaction.continue_from_environ instead of Span.continue_from_environ.)r`r warningr-continue_from_headersEnvironHeaders)clsenvironrr:r:r;continue_from_environs zSpan.continue_from_environcKsl|tkrtdt|t}|t|it|t }|dk rX||| t f|}d|_ |S)z Create a transaction with the given params (including any data pulled from the ``sentry-trace`` and ``baggage`` headers). :param headers: The dictionary with the HTTP headers to pull information from. zXDeprecated: use Transaction.continue_from_headers instead of Span.continue_from_headers.NF) r`r rr@Zfrom_incoming_headerrBAGGAGE_HEADER_NAMEupdateextract_sentrytrace_dataSENTRY_TRACE_HEADER_NAMEfreezer-r')rheadersrrAZsentrytrace_kwargs transactionr:r:r;rs  zSpan.continue_from_headersccs8|js dSt|fV|j}|r4t|fVdS)z Creates a generator which returns the span's ``sentry-trace`` and ``baggage`` headers. If the span's containing transaction doesn't yet have a ``baggage`` value, this will cause one to be generated and stored. N)r.rto_traceparent get_baggage serializer)rVrAr:r:r; iter_headerss zSpan.iter_headerscKs$td|sdS|jt|if|S)a DEPRECATED: Use :py:meth:`sentry_sdk.tracing.Span.continue_from_headers`. Create a ``Transaction`` with the given params, then add in data pulled from the given ``sentry-trace`` header value before returning the ``Transaction``. zwDeprecated: Use Transaction.continue_from_headers(headers, **kwargs) instead of from_traceparent(traceparent, **kwargs)N)r rrr)r traceparentrr:r:r;from_traceparent s zSpan.from_traceparentcCsN|jdkrd}n|jdkr d}nd}d|j|jf}|dk rJ|d|f7}|S)NT1F0z%s-%sz-%s)r(r$r%)rVr(rr:r:r;r&s  zSpan.to_traceparentcCs|jr|jSdS)zReturns the :py:class:`~sentry_sdk.tracing_utils.Baggage` associated with this ``Span``, if any. (Taken from the root of the span tree.) N)r.rrr:r:r; to_baggage5s zSpan.to_baggagecCs||j|<dSrX)rdrVkeyrr:r:r;set_tag>sz Span.set_tagcCs||j|<dSrX)rerr:r:r;set_dataBsz Span.set_datacCs ||_dSrXr,rVrr:r:r;rFszSpan.set_statuscCs||d|j|<dSN)runitrarVr2rrr:r:r;set_measurementJszSpan.set_measurementcCs4|dk r0|tjt||dk r0|tj|dSrX)rr THREAD_IDr6 THREAD_NAMErV thread_id thread_namer:r:r; set_threadNszSpan.set_threadcCs|dk r|tj|dSrX)rr PROFILER_IDrVrCr:r:r;rzWszSpan.set_profiler_idcCs0|dt||tj||t|dS)Nzhttp.status_code)rr6rrZHTTP_STATUS_CODErrOrVZ http_statusr:r:r;set_http_status\s zSpan.set_http_statuscCs |jdkS)Nokrrr:r:r; is_successdszSpan.is_successcCs|jdk rdSzJ|r4t|tr,t|tj}||_n"t|j}|j t |dd|_Wn"t k rzt tj|_YnX|pt }t||dS)aD Sets the end timestamp of the span. Additionally it also creates a breadcrumb from the span, if the span represents a database or HTTP request. :param scope: The scope to use for this transaction. If not provided, the current scope will be used. :param end_timestamp: Optional timestamp that should be used as timestamp instead of the current time. :return: Always ``None``. The type is ``Optional[str]`` to match the return value of :py:meth:`sentry_sdk.tracing.Transaction.finish`. Ni) microseconds)rcrvr9rrwrrur rbr/rrxrtrr"maybe_create_breadcrumbs_from_span)rVr0 end_timestampelapsedr:r:r;rhs      z Span.finishc Cs|j|j|j|j|j|j|j|j|jd }|j r<|j |j d<|j dk r\|j }|r\||d<t |jdkrt|j|d<|j }|r||d<|j}|r||d<|S) z5Returns a JSON-compatible representation of the span.) r$r%r&r'r)r*r/rcr1r,N_metrics_summaryr measurementstagsdata)r$r%r&r'r)r*r/rcr1r,rdrhto_jsonrYrare)rVr~metrics_summaryrrr:r:r;rs2     z Span.to_jsoncCs|j|j|j|j|j|jd}|jr.|j|d<|jrF|j |d<i}|j t j }|dk rh||d<|j t j}|dk r||d<|r||d<|S)N)r$r%r&r)r*r1r,dynamic_sampling_contextz thread.idz thread.namer)r$r%r&r)r*r1r,r.rrrerrrr)rVr~rrrr:r:r;get_trace_contexts,  zSpan.get_trace_contextcCs"|jtj}|dkrdSd|iS)NrC)rerrrrr:r:r;get_profile_contexts zSpan.get_profile_contextcCst\}}|||dSrX)r rrr:r:r;rys zSpan.update_active_thread)NNNTNNNNNNNNriN)r)NN)$r3r4r5r^r_rWr{rrrrpropertyr.rSENTRYr classmethodrrrrrrrrrrrrzrrrrrrryr:r:r:r;r`s^ B  *  )     &%! r`cseZdZdZdZdddeffdd ZddZd d Zfd d Z fd dZ e ddZ ddZ d$ddfdd Zd%ddZddZfddZfddZfddZd d!Zd"d#ZZS)&r-aiThe Transaction is the root element that holds all the spans for Sentry performance instrumentation. :param name: Identifier of the transaction. Will show up in the Sentry UI. :param parent_sampled: Whether the parent transaction was sampled. If True this transaction will be kept, if False it will be discarded. :param baggage: The W3C baggage header value. (see https://www.w3.org/TR/baggage/) :param source: A string describing the source of the transaction name. This will be used to determine the transaction's type. See https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations for more information. Default "custom". :param kwargs: Additional arguments to be passed to the Span constructor. See :py:class:`sentry_sdk.tracing.Span` for available arguments. )r2r>r? sample_ratera _contexts_profile_baggagerNc sBtjf|||_||_d|_||_i|_i|_d|_||_ dSrX) superrWr2r>rr?rarrr)rVr2r?rAr>rrr:r;rWs zTransaction.__init__c Cs.d|jj|j|j|j|j|j|j|j|j f S)Nzb<%s(name=%r, op=%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r, source=%r, origin=%r)>) rr3r2r)r$r%r&r(r>r1rr:r:r;rszTransaction.__repr__cCs|jdk p|jdkS)zReturns whether the transaction might have been started. If this returns False, we know that the transaction was not started with sentry_sdk.start_transaction, and therefore the transaction will be discarded. NF)rZr(rr:r:r;_possibly_started*s zTransaction._possibly_startedcs4|stdt|jdk r0|j|S)NzTransaction was entered without being started with sentry_sdk.start_transaction.The transaction will not be sent to Sentry. To fix, start the transaction bypassing it to sentry_sdk.start_transaction.)rr debugrrrrrr:r;r6s   zTransaction.__enter__cs.|jdk r|j|||t|||dSrX)rrr)rVrrrrr:r;rFs zTransaction.__exit__cCs|S)znThe root element of the span tree. In the case of a transaction it is the transaction itself. r:rr:r:r;r.Ms z"Transaction.containing_transactioncCsF|}|dk r tjdtdd|}t|tjrBtjdtdd|jS|S)z Logic to get the scope from the arguments passed to finish. This function exists for backwards compatibility with the old finish. TODO: Remove this function in the next major version. NzMThe `hub` parameter is deprecated. Please use the `scope` parameter, instead.rlzDPassing a Hub to finish is deprecated. Please pass a Scope, instead.)rqrrrsrvrZHubr0)rVZ scope_argZhub_argZ scope_or_hubr:r:r;_get_scope_from_finish_argsYs  z'Transaction._get_scope_from_finish_argsr+c s|jdk rdS|||}|p*|jp*t}t}|s@dS|jdkr|jdkr`t dn t d|j rt |j r|jr|jjdkrd}nd}|j j|dd |j j|d d dS|jst d d |_t|||js|jdkrt d dSdd|jjD}d|_i}||j|d|i|}|dk rV|d|id|jd|ji||j|j|j|d} |jdk r|jr|j| d<d|_|j| d<|j dk r|j !} | r| | d<|"| S)auFinishes the transaction and sends it to Sentry. All finished spans in the transaction will also be sent to Sentry. :param scope: The Scope to use for this transaction. If not provided, the current Scope will be used. :param end_timestamp: Optional timestamp that should be used as timestamp instead of the current time. :param hub: The hub to use for this transaction. This argument is DEPRECATED. Please use the `scope` parameter, instead. :return: The event ID if the transaction was sent to Sentry, otherwise None. NFz.Discarding transaction because sampled = FalsezSDiscarding transaction because it was not started with sentry_sdk.start_transactionrZ backpressurerr)Z data_categoryr\zCTransaction has no name, falling back to ``.zz1Discarding transaction without sampling decision.cSsg|]}|jdk r|qSrX)rcr).0r\r:r:r; s z&Transaction.finish..traceZprofiler>)typerZtransaction_infocontextsrrcr/rSrr)#rcrr0rrrZ is_activerZr(r r transporthas_tracing_enabledrmonitordownsample_factorZrecord_lost_eventr2rrrrSrrrrr>rdr/rZvalidrarhrZ capture_event) rVr0rr+clientreasonZfinished_spansrZprofile_contexteventrrr:r;rzsz              zTransaction.finishcCs||d|j|<dSrrrr:r:r;rszTransaction.set_measurementcCs||j|<dS)aSets a context. Transactions can have multiple contexts and they should follow the format described in the "Contexts Interface" documentation. :param key: The name of the context. :param value: The information about the context. N)rrr:r:r; set_contexts zTransaction.set_contextcs t||dd|idS)zySets the status of the Transaction according to the given HTTP status. :param http_status: The HTTP status code.response status_codeN)rrrrrr:r;rs zTransaction.set_http_statuscs,t}|j|d<|j|d<|j|d<|S)zr()rrr2r>r(r}rr:r;r s     zTransaction.to_jsoncst}|jr|j|d<|S)Nr)rrre)rVZ trace_contextrr:r;rs  zTransaction.get_trace_contextcCs |jr|jjrt||_|jS)zReturns the :py:class:`~sentry_sdk.tracing_utils.Baggage` associated with the Transaction. The first time a new baggage with Sentry items is made, it will be frozen.)rZmutabler@Zpopulate_from_transactionrr:r:r;r!s zTransaction.get_baggagecCsft}dj|jr d|jdnd|jd}t|js@d|_dS|jdk rZt|j|_ dSt |j drx|jd|n|d dk r|d n|jd }t |d d st d j|dd|_dSt||_ |jr|j d|jj_ |j s t dj|t |j dr dnddd|_dSt|j k|_|jrLt dj|dnt dj||j ddS)aO Sets the transaction's sampling decision, according to the following precedence rules: 1. If a sampling decision is passed to `start_transaction` (`start_transaction(name: "my transaction", sampled: True)`), that decision will be used, regardless of anything else 2. If `traces_sampler` is defined, its decision will be used. It can choose to keep or ignore any parent sampling decision, or use the sampling context data to make its own decision or to choose a sample rate for the transaction. 3. If `traces_sampler` is not defined, but there's a parent sampling decision, the parent sampling decision will be used. 4. If `traces_sampler` is not defined and there's no parent sampling decision, `traces_sample_rate` will be used. z{op}transaction <{name}> r)r)r2FNZtraces_samplerr?Ztraces_sample_rateZTracing)r>zN[Tracing] Discarding {transaction_description} because of invalid sample rate.)transaction_descriptionrkz?[Tracing] Discarding {transaction_description} because {reason}z"traces_sampler returned 0 or Falseztraces_sample_rate is set to 0)rrz,[Tracing] Starting {transaction_description}z}[Tracing] Discarding {transaction_description} because it's not included in the random sample (sampling rate = {sample_rate}))rr)rrformatr)r2rrr(r9rcallablerr r rrrrrandom)rVsampling_contextrrrr:r:r;_set_initial_sampling_decision.sh       z*Transaction._set_initial_sampling_decision)NN)r)r3r4r5r^r_TRANSACTION_SOURCE_CUSTOMrWrrrrrr.rrrrrrrrr __classcell__r:r:rr;r-s4   #|    r-c@seZdZddZeddZejfddZddZ d d Z d d Z d dZ ddZ ddZddZddZddZddZddZddZd,dd d!d"Zd-d$d%Zd&d'Zd(d)Zd*d+ZdS).rcCs d|jjS)Nz<%s>)rr3rr:r:r;rszNoOpSpan.__repr__cCsdSrXr:rr:r:r;r.szNoOpSpan.containing_transactioncKstSrX)r)rVrrr:r:r;rszNoOpSpan.start_childcCsdS)Nrr:rr:r:r;rszNoOpSpan.to_traceparentcCsdSrXr:rr:r:r;rszNoOpSpan.to_baggagecCsdSrXr:rr:r:r;rszNoOpSpan.get_baggagecCstdS)Nr:)iterrr:r:r;rszNoOpSpan.iter_headerscCsdSrXr:rr:r:r;rszNoOpSpan.set_tagcCsdSrXr:rr:r:r;rszNoOpSpan.set_datacCsdSrXr:rr:r:r;rszNoOpSpan.set_statuscCsdSrXr:rr:r:r;rszNoOpSpan.set_http_statuscCsdS)NTr:rr:r:r;rszNoOpSpan.is_successcCsiSrXr:rr:r:r;rszNoOpSpan.to_jsoncCsiSrXr:rr:r:r;rszNoOpSpan.get_trace_contextcCsiSrXr:rr:r:r;rszNoOpSpan.get_profile_contextNrcCsdS)z_ The `hub` parameter is deprecated. Please use the `scope` parameter, instead. Nr:)rVr0rr+r:r:r;rs zNoOpSpan.finishrcCsdSrXr:rr:r:r;rszNoOpSpan.set_measurementcCsdSrXr:rr:r:r;rszNoOpSpan.set_contextcCsdSrXr:rUr:r:r;r{szNoOpSpan.init_span_recordercCsdSrXr:)rVrr:r:r;rsz'NoOpSpan._set_initial_sampling_decision)NN)r)r3r4r5rrr.rrrrrrrrrrrrrrrrrrr{rr:r:r:r;rs2  rcCsdSrXr:funcr:r:r;rsrcCsdSrXr:rr:r:r;rscCs ddlm}|r||S|SdS)av Decorator to start a child span under the existing current transaction. If there is no current transaction, then nothing will be traced. .. code-block:: :caption: Usage import sentry_sdk @sentry_sdk.trace def my_function(): ... @sentry_sdk.trace async def my_async_function(): ... r)start_child_span_decoratorN)sentry_sdk.tracing_utilsr)rrr:r:r;rs )r@rrrrignore)r|)N)N)LrnrrqrrrrZsentry_sdk.constsrrrZ'sentry_sdk.profiler.continuous_profilerrZsentry_sdk.utilsr r r r typingr collections.abcrrrrrrrrrrrrrtyping_extensionsrrrrZsentry_sdk.profilerZsentry_sdk._typesrr r!r"r#r=r6rBrrrZTRANSACTION_SOURCE_URLZTRANSACTION_SOURCE_ROUTEZTRANSACTION_SOURCE_VIEWZTRANSACTION_SOURCE_COMPONENTZTRANSACTION_SOURCE_TASKZLOW_QUALITY_TRANSACTION_SOURCESZSOURCE_FOR_STYLErOrPr`r-rrrr@rrrrcatch_warnings simplefilterrsZsentry_sdk.metricsr|r:r:r:r;s            ; '6\