
    \d               
          d Z ddlmZmZ ddlmZmZmZmZm	Z	m
Z
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 ddlmZ ddlmZ  e            Zeeef         ZdedefdZ dedefdZ!d  ed          d d fd  ed          e e!fgZ"d e"D             Z#dede$fdZ%de$defdZ&dedefdZ'dedefd Z(	 d*d"ee         d#edefd$Z)	 	 d+d'ee         d#e
e         d(e*de	e         fd)Z+d%S ),zA
Tools for saving and loading log events in a structured format.
    )dumpsloads)IOAnyAnyStrDictIterableOptionalUnioncast)UUID)NamedConstant)Failure   FileLogObserver)flattenEvent)LogEvent)LogLevel)Loggerfailurereturnc                     t          |                                 t          | j        j        | j        j                            S )z
    Convert a failure to a JSON-serializable data structure.

    @param failure: A failure to serialize.

    @return: a mapping of strings to ... stuff, mostly reminiscent of
        L{Failure.__getstate__}
    )
__module____name__)type)dict__getstate__r   r   r   )r   s    4lib/python3.11/site-packages/twisted/logger/_json.pyfailureAsJSONr       sL     |.\*
 
 
       failureDictc                     t          j        t                     }| d         }t          |d         d|          | d<   | |_        |S )z
    Load a L{Failure} from a dictionary deserialized from JSON.

    @param failureDict: a JSON-deserialized object like one previously returned
        by L{failureAsJSON}.

    @return: L{Failure}
    r   r    )r   __new__r   __dict__)r"   ftypeInfos      r   failureFromJSONr)   .   sD     	  A6"Hx
3RBBKAJHr!   c                 f    t          | t                    ot          t          | j        d           | u S N)
isinstancer   getattrr   namelevels    r   <lambda>r1   @   s/    um,, =%*d33u< r!   z$02E59486-F24D-46AD-8224-3ACDF2A5732Ac                 ,    t          | j                  S )N)r.   )r   r.   r/   s    r   r1   r1   E   s    d
+++ r!   c                 :    t          t          | d         d           S )Nr.   )r-   r   r/   s    r   r1   r1   F   s    ghft<< r!   c                 ,    t          | t                    S r+   )r,   r   )os    r   r1   r1   I   s    *Q(( r!   z$E76887E2-20ED-49BF-A8F8-BA25CC586F2Dc                     i | ]
\  }}}}||S r$   r$   ).0	predicateuuidsaverloaders        r   
<dictcomp>r<   Q   s#    OOO!A)T5&fOOOr!   aDictc                 ^    d| v r(t          t          | d                            |           S | S )a#  
    Dictionary-to-object-translation hook for certain value types used within
    the logging system.

    @see: the C{object_hook} parameter to L{json.load}

    @param aDict: A dictionary loaded from a JSON object.

    @return: C{aDict} itself, or the object represented by C{aDict}
    __class_uuid__)uuidToLoaderr   )r=   s    r   objectLoadHookrA   T   s5     5  D'7!899:5AAALr!   pythonObjectc                     t           D ]3\  }}}} ||           r! ||           }t          |          |d<   |c S 4ddiS )a  
    Object-to-serializable hook for certain value types used within the logging
    system.

    @see: the C{default} parameter to L{json.dump}

    @param pythonObject: Any object.

    @return: If the object is one of the special types the logging system
        supports, a specially-formatted dictionary; otherwise, a marker
        dictionary indicating that it could not be serialized.
    r?   unpersistableT)	classInfostr)rB   r8   r9   r:   r;   results         r   objectSaveHookrH   d   si     -6  (D%9\"" 	U<((F'*4yyF#$MMM	 T""r!   eventc                     dt           dt          t          t          f         fd}t	          |            t          | |d          S )a  
    Encode an event as JSON, flattening it if necessary to preserve as much
    structure as possible.

    Not all structure from the log event will be preserved when it is
    serialized.

    @param event: A log event dictionary.

    @return: A string of the serialized JSON; note that this will contain no
        newline characters, and may thus safely be stored in a line-delimited
        file.
    unencodabler   c                 t    t          | t                    r|                     d          S t          |           S )z
        Serialize an object not otherwise serializable by L{dumps}.

        @param unencodable: An unencodable object.

        @return: C{unencodable}, serialized
        charmap)r,   bytesdecoderH   )rK   s    r   defaultzeventAsJSON.<locals>.default   s8     k5)) 	1%%i000k***r!   T)rP   skipkeys)objectr   JSONDictrF   r   r   )rI   rP   s     r   eventAsJSONrT   y   sR    
+V 
+hm(< 
+ 
+ 
+ 
+ $7777r!   	eventTextc                 T    t          t          t          | t                              S )z
    Decode a log event from JSON.

    @param eventText: The output of a previous call to L{eventAsJSON}

    @return: A reconstructed version of the log event.
    )object_hook)r   rS   r   rA   )rU   s    r   eventFromJSONrX      s!     %	~FFFGGGr!   outFilerecordSeparatorc                 *    t          | fd          S )a  
    Create a L{FileLogObserver} that emits JSON-serialized events to a
    specified (writable) file-like object.

    Events are written in the following form::

        RS + JSON + NL

    C{JSON} is the serialized event, which is JSON text.  C{NL} is a newline
    (C{"\n"}).  C{RS} is a record separator.  By default, this is a single
    RS character (C{"\x1e"}), which makes the default output conform to the
    IETF draft document "draft-ietf-json-text-sequence-13".

    @param outFile: A file-like object.  Ideally one should be passed which
        accepts L{str} data.  Otherwise, UTF-8 L{bytes} will be used.
    @param recordSeparator: The record separator to use.

    @return: A file log observer.
    c                 ,     t          |            dS )N
)rT   )rI   r[   s    r   r1   z%jsonFileLogObserver.<locals>.<lambda>   s    /I;u3E3EIII r!   r   )rZ   r[   s    `r   jsonFileLogObserverr_      s&    , IIII  r!   N   inFile
bufferSizec              #     K   dt           dt          fd}dt          dt          t                   fd|* ||                     d                    }|dk    r|}nd	}n ||          }d	}|d	k    rd
}}ndt          dt          t                   ffd}t          |          }	 |                     |          }|s&t          |          dk    r ||          }	|	|	V  dS | ||          z  }|                    |          }
|
dd         D ]&}t          |          dk    r ||          }	|	|	V  '|
d         })aM  
    Load events from a file previously saved with L{jsonFileLogObserver}.
    Event records that are truncated or otherwise unreadable are ignored.

    @param inFile: A (readable) file-like object.  Data read from C{inFile}
        should be L{str} or UTF-8 L{bytes}.
    @param recordSeparator: The expected record separator.
        If L{None}, attempt to automatically detect the record separator from
        one of C{"\x1e"} or C{""}.
    @param bufferSize: The size of the read buffer used while reading from
        C{inFile}.

    @return: Log events as read from C{inFile}.
    sr   c                 Z    t          | t                    r| S |                     d          S )Nutf-8)r,   rN   encode)rd   s    r   asBytesz&eventsFromJSONLogFile.<locals>.asBytes   s+    a 	%H88G$$$r!   recordc                 R   	 t          |                               d          }n:# t          $ r- t                              dt          |                      Y d S w xY w	 t          |          S # t          $ r- t                              dt          |                      Y d S w xY w)Nrf   z2Unable to decode UTF-8 for JSON record: {record!r}ri   z&Unable to read JSON record: {record!r})rN   rO   UnicodeDecodeErrorlogerrorrX   
ValueError)ri   texts     r   eventFromBytearrayz1eventsFromJSONLogFile.<locals>.eventFromBytearray   s    	==''00DD! 	 	 	IIDV}}     44		 &&& 	 	 	II>uV}}IUUU44	s!   "% 3AA A/ /3B&%B&Nr      r!      
c                     | d         t          d          k    r |           S t                              dt          |                      d S )Nr^   z0Unable to read truncated JSON record: {record!r}rk   )ordrm   rn   rN   )ri   rq   s    r   eventFromRecordz.eventsFromJSONLogFile.<locals>.eventFromRecord   sW    bzSYY&&))&111		F ==     4r!   Tr   ru   )r   rN   	bytearrayr
   r   readlensplit)ra   r[   rb   rh   firstrecordSeparatorBytesrw   buffernewDatarI   recordsri   rq   s               @r   eventsFromJSONLogFiler      s     (%6 %e % % % %9 (1C      A''G#(   $'    'w77s""$,	I 	(82D 	 	 	 	 	 	 uF++j)) 	6{{Q'//$KKKE'''""",,344crcl 	  	 F6{{Q'//$KKK'r!   )rY   )Nr`   ),__doc__jsonr   r   typingr   r   r   r   r	   r
   r   r   r9   r   
constantlyr   twisted.python.failurer   _filer   _flattenr   _interfacesr   _levelsr   _loggerr   rm   rF   rS   r    r)   rE   r@   rR   rA   rH   rT   rX   r_   intr   r$   r!   r   <module>r      s  
          I I I I I I I I I I I I I I I I I I I I       $ $ $ $ $ $ * * * * * * " " " " " " " " " " " " ! ! ! ! ! !            fhh S>7 x    $ g    $	
 	
 	344++<< 	)(344		& POYOOO( v     # #H # # # #*8x 8C 8 8 8 8>HS HX H H H H .4 W'*   : &*_ _sG_c]_ _ h	_ _ _ _ _ _r!   