o
    i[I                  	   @  s  d dl m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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mZmZmZmZmZ d d
l m!Z!m"Z# d dl$m%Z% d dl&m'Z'm(Z( d dl)m*Z* d dl+m,Z, d dl-m.Z. d dl/mZ0 d dl1m2Z2m3Z3 d dl4m5Z5 d dl6m7Z7 ze8Z9W n e:y   esG dd de;Z8Y nw erd dlm<Z< d dl=m>Z> ee?e@e; e;edB f e?d f ZA	 e<dZBedZCeeDeEeFeGdeHd e?d df ZIeJeFeIf ZKzd dlLZLW n eMy   drd!d"ZNY nw drd#d"ZNeOd$ZPdsd(d)ZQdtd+d,ZRed-eFeSd.d/ZTd0d1dud6d7ZUdvd8d9ZVdwd=d>ZWG d?d@ d@eZXdxdCdDZYG dEdF dFe2ZZdydIdJZ[dzdMdNZ\dOgZ]ze]^e!j_ W n
 e`yx   Y nw d{dQdRZaedSdO ZbdTdU Zcd|dWdXZdG dYdZ dZZeee ZfefecjgZhehjid[ksJ eejjjgZkd}d]d^Zld~d`daZmddbdcZnedddddeG dfdg dge*Zod{dhdiZpdddndoZqddpdqZrdS )    )annotationsN)MappingSequence)contextmanager)	dataclass)Path)time)TracebackType)TYPE_CHECKINGAnyCallable	TypedDictTypeVarUnion)contexttrace)Resource)EventReadableSpan)IdGenerator)InstrumentationScope)Status)types)RequestExceptionResponse)is_user_code)ulidc                   @  s   e Zd ZdZdS )BaseExceptionGroupz.Stub for BaseExceptionGroup for Python < 3.11.N)__name__
__module____qualname____doc__ r"   r"   ]/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/logfire/_internal/utils.pyr   .   s    r   )	ParamSpecVersion)NNNPT	JsonValue)r)   .JsonDictobjreturnstrc                 C  s   t j| ddS )N),:)
separators)jsondumpsr+   r"   r"   r#   	dump_jsonG      r4   c                 C  s   t |  S N)pydantic_coreto_jsondecoder3   r"   r"   r#   r4   K   r5   logfireseqSequence[T]tuple[T, ...]c                   s$   t    jt fdd| D S )z3Remove duplicates from a sequence preserving order.c                 3  s$    | ]}| v s|s|V  qd S r6   r"   ).0xseenseen_addr"   r#   	<genexpr>V   s   " z$uniquify_sequence.<locals>.<genexpr>)setaddtuple)r;   r"   r@   r#   uniquify_sequenceR   s   rG   r   c                 C  sV   zt | }W n ty   d}Y nw |r|S z
dt| j dW S  ty*   Y dS w )zVReturn some kind of non-empty string representation of an object, catching exceptions. <z object>z<unknown (repr failed)>)repr	Exceptiontyper   )r+   resultr"   r"   r#   	safe_reprY   s   rN   Truncatablez	list[Any]ztuple[Any, ...]z...)middles
max_lengthintrP   c                C  s   t | ||dS )z]Return a string at most max_length characters long, with `middle` in the middle if truncated.)rR   rP   )truncate_sequence)rQ   rR   rP   r"   r"   r#   truncate_stringm   s   rU   c                C  sB   t | |kr| S |t | }|d }| d| | | | d  S )zaReturn a sequence at with `len()` at most `max_length`, with `middle` in the middle if truncated.   N)len)r;   rR   rP   remaining_lengthhalfr"   r"   r#   rT   r   s
   rT   pathr   dict[str, Any]c                 C  s\   t jdkrddlm} nddlm} | d}||}W d   |S 1 s'w   Y  |S )zRead a TOML file and return the parsed data.

    It wraps the `tomllib.load` function from Python 3.11 or the `tomli.load` function from older versions.
    )      r   )loadrbN)sysversion_infotomllibr^   tomliopen)rZ   	load_tomlfdatar"   r"   r#   read_toml_file{   s   


rh   c                   @  sr   e Zd ZU dZded< ded< ded< ded< d	ed
< ded< ded< ded< ded< ded< ded< ded< dS )ReadableSpanDicta=  A dictionary representation of a ReadableSpan.

    ReadableSpan is immutable, so making modified versions of it is inconvenient and slow.
    Converting a ReadableSpan to a ReadableSpanDict using span_to_dict makes it easier to modify.
    See `SpanProcessorWrapper.on_end` for an example of how this is useful.
    r-   nameztrace_api.SpanContext | Noner   parentzResource | Noneresourcez'Mapping[str, otel_types.AttributeValue]
attributeszSequence[Event]eventszSequence[trace_api.Link]linksztrace_api.SpanKindkindr   status
int | None
start_timeend_timezInstrumentationScope | Noneinstrumentation_scopeN)r   r   r    r!   __annotations__r"   r"   r"   r#   ri      s   
 ri   spanr   c                 C  s<   t | j| j| j| j| jpi | j| j| j| j	| j
| j| jdS )zSee ReadableSpanDict.)rj   r   rk   rl   rm   rn   ro   rp   rq   rs   rt   ru   )ri   rj   r   rk   rl   rm   rn   ro   rp   rq   rs   rt   ru   )rw   r"   r"   r#   span_to_dict   s   rx   c                      sD   e Zd ZU dZded< d fddZdd	d
ZedddZ  Z	S )UnexpectedResponsez4An unexpected response was received from the server.r   responser,   Nonec                   s   t  jd|j |d d S )NzUnexpected response: )rz   )super__init__status_code)selfrz   	__class__r"   r#   r}      s   zUnexpectedResponse.__init__r-   c                 C  s   | j d usJ z| j  }W n ty)   z| j j}W n ty&   d}Y nw Y nw tj|dd}| j j}d| j j d|j d|j d| j j dt	|d	d
 dS )Nz[binary data]rV   )indentzUnexpected response z

 u    —> z
body: x   )rR   zq
If the error persists, please contact us. (See https://logfire.pydantic.dev/docs/help/ for contact information.))
rz   r1   
ValueErrortextr2   requestr~   methodurlrU   )r   	body_jsonbodyr   r"   r"   r#   __str__   s.   
zUnexpectedResponse.__str__c                 C  s   |j tddvr| |dS )zBLike the requests method, but raises a more informative exception.   i,  N)r~   range)clsrz   r"   r"   r#   raise_for_status   s   z#UnexpectedResponse.raise_for_status)rz   r   r,   r{   )r,   r-   )
r   r   r    r!   rv   r}   r   classmethodr   __classcell__r"   r"   r   r#   ry      s   
 
ry   data_dirr{   c                 C  sH   |   r|  std|  dd S | jddd | d }|d d S )NzData directory z exists but is not a directoryT)parentsexist_okz
.gitignore*)existsis_dirr   mkdir
write_text)r   	gitignorer"   r"   r#   ensure_data_dir_exists   s   r   versionr&   c                 C  sv   zddl m} W || S  ty:   ddlm} zddl m} W n ty/   ddlm} Y nw Y || S Y || S w )zReturn a packaging.version.Version object from a version string.

    We check if `packaging` is available, falling back to `setuptools._vendor.packaging` if it's not.
    r   r%   )packaging.versionr&   ImportError$setuptools._vendor.packaging.version)r   r&   r"   r"   r#   get_version   s   r   suppress_instrumentationboolc                   C  s   t dd tD S )zReturn True if the `suppress_instrumentation` context manager is currently active.

    This means that any logs/spans generated by logfire or OpenTelemetry will not be logged in any way.
    c                 s  s    | ]}t |V  qd S r6   )r   	get_value)r>   keyr"   r"   r#   rC     s    z0is_instrumentation_suppressed.<locals>.<genexpr>)any%SUPPRESS_INSTRUMENTATION_CONTEXT_KEYSr"   r"   r"   r#   is_instrumentation_suppressed  s   r   c               	   c  sP    t  } tD ]	}t |d| } qt | }zdV  W t | dS t | w )zQContext manager to suppress all logs/spans generated by logfire or OpenTelemetry.TN)r   get_currentr   	set_valueattachdetach)new_contextr   tokenr"   r"   r#   r     s   
c                  C  s|   zt jdd} t| od| v}W n ty   d}Y nw |r  t  tjdt d W d    d S 1 s7w   Y  d S )NPYTEST_CURRENT_TESTrH   test_internal_exceptionFzCaught an internal error in Logfire. Your code should still be running fine, just with less telemetry. This is just logging the internal error.)exc_info)	osenvirongetr   rK   r   logger	exception_internal_error_exc_info)current_testreraiser"   r"   r#   log_internal_error  s   "r   
SysExcInfoc                  C  s(  t  } | \}}}z|}|r|jr|jjtu r|j}t }|s"J |j}|rC|jt	j
u rC|j}|s4J |jtu r@|j}|s@J |j}|r^t|js^t|||j|jd}|j}|r^t|jrJtdD ]}|sh nt|||j|jd}|j}qb|szJ |s~J ||}|||fW S  ty   |  Y S w )z:Returns an exc_info tuple with a nicely tweaked traceback.)tb_nexttb_frametb_lasti	tb_linenor\   )r`   r   r   f_code$_HANDLE_INTERNAL_ERRORS_WRAPPER_CODEr   inspectcurrentframef_backr   __code__!_HANDLE_INTERNAL_ERRORS_EXIT_CODEr   r	   f_lastif_linenor   with_tracebackrK   )original_exc_infoexc_typeexc_valoriginal_tbtbframe_r"   r"   r#   r   1  s@   


r   c                   @  s(   e Zd Zdd ZdddZdddZdS )HandleInternalErrorsc                 C  s   d S r6   r"   r   r"   r"   r#   	__enter__f  s   zHandleInternalErrors.__enter__r   type[BaseException]r   BaseExceptionexc_tbr	   r,   bool | Nonec                 C  s   t |tr
t  dS d S )NT)
isinstancerK   r   )r   r   r   r   r"   r"   r#   __exit__i  s   
zHandleInternalErrors.__exit__funcCallable[P, T]c                   s   t  d	 fdd}|S )
NargsP.argskwargsP.kwargsr,   r(   c                    s6     | i |W  d    S 1 sw   Y  d S r6   r"   )r   r   r   r   r"   r#   wrappero  s   $z.HandleInternalErrors.__call__.<locals>.wrapper)r   r   r   r   r,   r(   )	functoolswraps)r   r   r   r"   r   r#   __call__n  s   zHandleInternalErrors.__call__N)r   r   r   r   r   r	   r,   r   )r   r   r,   r   )r   r   r    r   r   r   r"   r"   r"   r#   r   e  s    
r   r   capturec                 C  s    | rdt jd< dt jd< d S d S )Nz.*8OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST9OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE)r   r   )r   r"   r"   r#   maybe_capture_server_headers~  s   
r   rj   c                 C  s
   |  dS )N)z
 http sendz http receivez websocket sendz websocket receive)endswith)rj   r"   r"   r#   is_asgi_send_receive_span_name  s   
r   c                   C  s   t t d S )Ni  )rS   r   r"   r"   r"   r#   _default_ms_timestamp_generator  r5   r   T)rJ   eqc                   @  sJ   e Zd ZU dZdZded< eZded< 	 dd	d
ZdddZ	dddZ
dS )SeededRandomIdGeneratoray  Generate random span/trace IDs from a seed for deterministic tests.

    Similar to RandomIdGenerator from OpenTelemetry, but with a seed.
    Set the seed to None for non-deterministic randomness.
    In that case the difference from RandomIdGenerator is that it's not affected by `random.seed(...)`.

    Trace IDs are 128-bit integers.
    Span IDs are 64-bit integers.
    r   rr   seedzCallable[[], int]_ms_timestamp_generatorr,   r{   c                 C  s>   t | j| _ | jd u rttdrtj| j jd d S d S d S )Nregister_at_fork)after_in_child)randomRandomr   hasattrr   r   r   r"   r"   r#   __post_init__  s   z%SeededRandomIdGenerator.__post_init__rS   c                 C  s0   | j d}|tjkr| j d}|tjks|S )N@   )r   getrandbits	trace_apiINVALID_SPAN_ID)r   span_idr"   r"   r#   generate_span_id  s
   

z(SeededRandomIdGenerator.generate_span_idc                 C  s4   t | j| j}|tjkrt | j| j}|tjks|S r6   )r   r   r   r   INVALID_TRACE_ID)r   trace_idr"   r"   r#   generate_trace_id  s
   

z)SeededRandomIdGenerator.generate_trace_idN)r,   r{   r,   rS   )r   r   r    r!   r   rv   r   r   r   r   r   r"   r"   r"   r#   r     s   
 


r   c                   C  s   t   dkS )zReturn True if the platform is Emscripten, e.g. Pyodide.

    Threads cannot be created on Emscripten, so we need to avoid any code that creates threads.
    
emscripten)platformsystemlowerr"   r"   r"   r#   platform_is_emscripten  s   r  excr   rA   set[int] | Nonec                   s  zt | }d|j d|j dg}d}| jrht }t| jD ]H\}}|jj}t	
|||j }	|jd|}
|
 d|jj d|	 }||v r]|d7 }|dkr\t| tr\|d	  nq|| || q plt  t|  v ry|d
 nB t|  t| tr| j}|dgt fdd|D d7 }| jdur|dt| j g7 }| jdur| js|dt| j g7 }d|W S  ty   t  Y dS w )aZ  Return a canonical string representation of an exception traceback.

    Exceptions with the same representation are considered the same for fingerprinting purposes.
    The source line is used, but not the line number, so that changes elsewhere in a file are irrelevant.
    The module is used instead of the filename.
    The same line appearing multiple times in a stack is ignored.
    Exception group sub-exceptions are sorted and deduplicated.
    If the exception has a cause or (not suppressed) context, it is included in the representation.
    Cause and context are treated as different.
    
.z
----r   r   z
      d   z
<recursion detected>z
<repeated exception>z
<ExceptionGroup>c                   s   h | ]}t | qS r"   ) canonicalize_exception_traceback)r>   
nested_excrA   r"   r#   	<setcomp>  s    z3canonicalize_exception_traceback.<locals>.<setcomp>z
</ExceptionGroup>
Nz
__cause__:z
__context__:z<error while canonicalizing>)rL   r   r    __traceback__rD   	tracebackwalk_tbr   co_filename	linecachegetline	f_globalsstripr   co_namer   RecursionErrorappendrE   idr   
exceptionssorted	__cause__r  __context____suppress_context__joinrK   r   )r  rA   r   partsnum_repeatsvisitedr   linenofilenamesource_linemoduleframe_summarysub_exceptionsr"   r  r#   r    s^   






r  c                 C  s    t  }|| d | S )Nzutf-8)hashlibsha256updateencode	hexdigest)rQ   hasherr"   r"   r#   sha256_string  s   r0  )r+   r)   r,   r-   )r;   r<   r,   r=   )r+   r   r,   r-   )rQ   r-   rR   rS   rP   r-   r,   r-   )r;   rO   rR   rS   rP   rO   r,   rO   )rZ   r   r,   r[   )rw   r   r,   ri   )r   r   r,   r{   )r   r-   r,   r&   )r,   r   )r,   r   )r   r   )rj   r-   r,   r   r   r6   )r  r   rA   r  r,   r-   )rQ   r-   r,   r-   )s
__future__r   r   r*  r   r1   r  loggingr   r  r   r`   r  collections.abcr   r   
contextlibr   dataclassesr   pathlibr   r   r   r	   typingr
   r   r   r   r   r   opentelemetryr   r   r   opentelemetry.sdk.resourcesr   opentelemetry.sdk.tracer   r   $opentelemetry.sdk.trace.id_generatorr   &opentelemetry.sdk.util.instrumentationr   opentelemetry.trace.statusr   opentelemetry.util
otel_typesrequestsr   r   logfire._internal.stack_infor   logfire._internal.ulidr   r   r   	NameErrorr   r$   r   r&   rF   rL   r   r'   r(   rS   floatr-   r   listr)   dictr*   r7   rK   r4   	getLoggerr   rG   rN   bytesrO   rU   rT   rh   ri   rx   ry   r   r   r   r  _SUPPRESS_INSTRUMENTATION_KEYAttributeErrorr   r   r   r   r   handle_internal_errorsr   r   r  r   r   r   r   r   r   r  r  r0  r"   r"   r"   r#   <module>   s     	" 





	

#




4





!?