
    g/                       d dl m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mZmZmZmZ d dlZddlmZmZ erdd	lmZ 	 	 	 	 	 	 	 	 	 	 	 	 dd
Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZe G d de             Z ed      ZddZddZy)    )annotationsN)deque)	dataclass)partial)TYPE_CHECKINGAnyCallableContextManagerTypeVar   )BaseTransformerLogfireArgs)Logfirec           	         dt        j                         j                   g t        | ||||      } t	        | t
        j                        sJ t        | |dd      dfd}|S )a-  Compile a modified AST of the module's source code in the module's namespace.

    Returns a function which accepts module globals and executes the compiled code.

    The modified AST wraps the body of every function definition in `with context_factories[index]():`.
    `context_factories` is added to the module's namespace as `logfire_<uuid>`.
    `index` is a different constant number for each function definition.
    `context_factories[index]` is one of these:
        - `partial(logfire_instance._fast_span, name, attributes)` where the name and attributes
            are constructed from `filename`, `module_name`, attributes of `logfire_instance`,
            and the qualified name and line number of the current function.
        - `MeasureTime`, a class that measures the time elapsed. If it exceeds `min_duration`,
            then `context_factories[index]` is replaced with the `partial` above.
    If `min_duration` is greater than 0, then `context_factories[index]` is initially `MeasureTime`.
    Otherwise, it's initially the `partial` above.
    logfire_execT)dont_inheritc                *    | <   t        | |        y N)r   )globscodecontext_factorieslogfire_names    ]/var/www/openai/venv/lib/python3.12/site-packages/logfire/_internal/auto_trace/rewrite_ast.pyexecutezcompile_source.<locals>.execute,   s    /lT5%     )r   zdict[str, Any])uuiduuid4hexrewrite_ast
isinstanceastModulecompile)	treefilenamemodule_namelogfire_instancemin_durationr   r   r   r   s	         @@@r   compile_sourcer*      sm    & djjl../0LACtX|[BRTegstDdCJJ'''46=D! Nr   c           	         t        |j                  |j                        }t        |||||||      }|j	                  |       S r   )r   _tags_sample_rateAutoTraceTransformervisit)	r%   r&   r   r'   r(   r   r)   logfire_argstransformers	            r   r    r    3   sM     /557G7T7TUL&lHk;KM^`lK T""r   c                  l     e Zd ZU dZded<   ded<   ded<   ddZd fd	Zd fd
Zd fdZddZ	 xZ
S )r.   zUTrace all encountered functions except those explicitly marked with `@no_auto_trace`.r   r(   'list[Callable[[], ContextManager[Any]]]r   intr)   c                :    t        d |j                  D              S )zUReturn true if the node has a `@no_auto_trace` or `@logfire.no_auto_trace` decorator.c              3    K   | ]  }t        |t        j                        xr |j                  t        j
                  k(  xs t        |t        j                        xrl |j                  t        j
                  k(  xrM t        |j                  t        j                        xr' |j                  j                  t        j
                  k(    y wr   )
r!   r"   Nameidno_auto_trace__name__	Attributeattrvaluelogfire).0nodes     r   	<genexpr>z;AutoTraceTransformer.check_no_auto_trace.<locals>.<genexpr>M   s      
 , 4* 6GG}555 tS]]3 :		]%;%;;:"4::sxx8: 

)9)99 ,s   CC)anydecorator_list)selfr@   s     r   check_no_auto_tracez(AutoTraceTransformer.check_no_auto_traceK   s$     
 ++
 
 	
r   c                H    | j                  |      r|S t        | 	  |      S r   )rE   supervisit_ClassDefrD   r@   	__class__s     r   rH   z#AutoTraceTransformer.visit_ClassDef[   s&    ##D)Kw%d++r   c                H    | j                  |      r|S t        | 	  |      S r   )rE   rG   visit_FunctionDefrI   s     r   rL   z&AutoTraceTransformer.visit_FunctionDefa   s&    ##D)Kw(..r   c                >    t        |      r|S t        | 	  ||      S r   )	has_yieldrG   rewrite_function)rD   r@   qualnamerJ   s      r   rO   z%AutoTraceTransformer.rewrite_functiong   s!    T?Kw'h77r   c           
         t         j                        t         j                  j                  g j                  ||j                          j                  dkD  rd j                  j                  }|j                  j                   j                   G  fdd      } j                  j                  |       n j                  j                         t        j                  t        j                  t        j                   j                   t        j"                               t        j$                  t        j&                              t        j"                               g g       S )Nr   c                  .    e Zd ZdZfdZ fdZy)BAutoTraceTransformer.logfire_method_call_node.<locals>.MeasureTimestartc                            | _         y r   )rT   )_selftimers    r   	__enter__zLAutoTraceTransformer.logfire_method_call_node.<locals>.MeasureTime.__enter__   s    "''EKr   c                T            | j                   z
  k\  rj                  <   y y r   )rT   r   )rV   _indexr)   rD   span_factoryrW   s     r   __exit__zKAutoTraceTransformer.logfire_method_call_node.<locals>.MeasureTime.__exit__   s+    w,<8D..u5 =r   N)r:   
__module____qualname__	__slots__rX   r]   )r[   r)   rD   r\   rW   s   r   MeasureTimerS   }   s    #	*E Er   ra   )r8   ctx)r=   )r=   slicerb   )funcargskeywords)lenr   r   r(   
_fast_spanlogfire_method_arg_valueslinenor)   _configadvancedns_timestamp_generatorappendr"   Call	Subscriptr7   logfire_method_nameLoadIndexConstant)	rD   r@   rP   configra   r[   r)   r\   rW   s	   `    @@@@r   logfire_method_call_nodez-AutoTraceTransformer.logfire_method_call_nodem   s   D**+!!,,
++HdkkB
 q **22F OO::E,,LE E ""))+6"")),7 xxhh$":":
Kiicll&?@HHJ
 
 	
r   )r@   z5ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDefreturnbool)r@   zast.ClassDef)r@   &ast.FunctionDef | ast.AsyncFunctionDef)r@   ry   rP   strrw   ast.AST)r@   ry   rP   rz   rw   zast.Call)r:   r^   r_   __doc____annotations__rE   rH   rL   rO   rv   __classcell__)rJ   s   @r   r.   r.   C   s1    _>>
 ,/8*
r   r.   Tc                    | S )a  Decorator to prevent a function/class from being traced by `logfire.install_auto_tracing`.

    This is useful for small functions that are called very frequently and would generate too much noise.

    The decorator is detected at import time.
    Only `@no_auto_trace` or `@logfire.no_auto_trace` are supported.
    Renaming/aliasing either the function or module won't work.
    Neither will calling this indirectly via another function.

    Any decorated function, or any function defined anywhere inside a decorated function/class,
    will be completely ignored by `logfire.install_auto_tracing`.

    This decorator simply returns the argument unchanged, so there is zero runtime overhead.
     )xs    r   r9   r9      s	     Hr   c                j   t        | g      }|r|j                         } t        j                  |       D ]y  }t	        |t        j
                  t        j                  f      r yt	        |t        j                  t        j                  t        j                  f      ri|j                  |       { |ry y )NT)r   popleftr"   iter_child_nodesr!   Yield	YieldFromFunctionDefAsyncFunctionDefLambdarn   )r@   queuechilds      r   rN   rN      sz    4&ME
}}))$/E%#))S]]!;<ecoos7K7KSZZ%XYU#	 0 r   )r%   r{   r&   rz   r'   rz   r(   r   r)   r4   rw   z Callable[[dict[str, Any]], None])r%   r{   r&   rz   r   rz   r'   rz   r(   r   r   r3   r)   r4   rw   r{   )r   r   rw   r   )r@   r{   )
__future__r   r"   r   collectionsr   dataclassesr   	functoolsr   typingr   r   r	   r
   r   r>   	ast_utilsr   r   mainr   r*   r    r.   r   r9   rN   r   r   r   <module>r      s    " 
   !  H H  4
 /2FM]`%B#
## # 	#
 # ?# # #  S
? S
 S
l CL$$r   