
    Mh                    ~   d Z 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mZ ddlmZmZ ddlmZ ddlZddlmZ ddlmZmZmZmZmZmZ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* ddl+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2m3Z3m4Z4m5Z5 ej6        Z7ej8        Z8d@dZ9dZ:dZ;dAdZ<dBdZ=dCdZ>ej?        Z@e<ZAe=ZBdZC ejD                    ZEdDd ZFdEd!ZGd"d#d$d%ZHd& eG            d'd(id)fd&d*d'd(id+fd,ZIdFd/ZJdGd1ZK G d2 d3e&          ZL G d4 d5          ZMdHd<ZNdId>ZO G d? d&e%          ZPdS )Ja  Session object for building, serializing, sending, and receiving messages.

The Session object supports serialization, HMAC signatures,
and metadata on messages.

Also defined here are utilities for working with Sessions:
* A SessionFactory to be used as a base class for configurables that work with
Sessions.
* A Message object for convenience that allows attribute-access to the msg dict.
    )annotationsN)b2a_hex)datetimetimezone)compare_digest)IOLoop)AnyBoolCBytesCUnicodeDictDottedObjectNameInstanceIntegerSet
TraitErrorUnicodeobserve)ConfigurableLoggingConfigurable)
get_logger)import_item)	ZMQStream   )protocol_version)adapt)extract_dates
json_cleanjson_defaultsquash_datesobjt.Anyreturnc                   t          | t                    rwt          |                                           D ]T}t	          | |                   | |<   t          |t
                    r%|                     |          | t	          |          <   Ungt          | t                    r(t          |           D ]\  }}t	          |          | |<   n*t          | t
                    r|                     d          } | S )z#coerce unicode back to bytestrings.utf8)	
isinstancedictlistkeyssquash_unicodestrpop	enumerateencode)r!   keyivs       V/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/jupyter_client/session.pyr*   r*   @   s    #t 	!

## 	8 	8C%c#h//CH#s## 8+.773<<N3''(	8 
C		 !cNN 	' 	'DAq#A&&CFF	'	C		 !jj  J    @   i   bytesc                Z   	 t          j        | t          dd                              dd          S # t          t
          f$ re}t          j        t          |           t          dd                              dd          }t          j        d| dd	           |cY d
}~S d
}~ww xY w)z!Convert a json object to a bytes.F)defaultensure_ascii	allow_nanr%   surrogateescape)errorsz#Message serialization failed with:
zk
Supporting this message is deprecated in jupyter-client 7, please make sure your message is JSON-compliant   
stacklevelN)	jsondumpsr   r.   	TypeError
ValueErrorr   warningswarn)r!   epackeds      r2   json_packerrG   \   s    z 	
 
 

 & 1&
2
2	3 z"   sOO 	
 
 

 & 1&
2
2 	 	21 2 2 2 		
 	
 	
 	
 !s   14 B*AB%B*%B*sstr | bytesc                    t          | t                    r|                     dd          } t          j        |           S )z,Convert a json bytes or string to an object.r%   replace)r&   r5   decoder?   loads)rH   s    r2   json_unpackerrN   x   s5    !U (HHVY'':a==r3   oc                P    t          j        t          |           t                    S )z'Pack an object using the pickle module.)pickler@   r    PICKLE_PROTOCOL)rO   s    r2   pickle_packerrS      s    <Q999r3   s	   <IDS|MSG>r+   c                     t          j        d          } d                    d | dd         | dd         fD                       S )zGenerate a new random id.

    Avoids problematic runtime import in stdlib uuid on Python 2.

    Returns
    -------

    id string (16 random bytes as hex-encoded text, chunks separated by '-')
       -c              3  Z   K   | ]&}t          |                              d           V  'dS )asciiN)r   rL   ).0xs     r2   	<genexpr>znew_id.<locals>.<genexpr>   s6      KK1GAJJ%%g..KKKKKKr3   N   )osurandomjoin)bufs    r2   new_idra      sG     *R..C88KKRaR#abb'8JKKKKKKr3   c                 D    t                                          d          S )zReturn new_id as ascii bytesrX   )ra   r.    r3   r2   new_id_bytesrd      s    88??7###r3   zSession.sessionzSession.usernamezSession.keyfile)identuserkeyfileSession )r/   rg   zUse HMAC digests for authentication of messages.
        Setting this flag will generate a new UUID to use as the HMAC key.
        r3   zDon't authenticate messages.)securez	no-securecfgNonec                    t          j        dt          d           d| v rd| j        v s	d| j        v rdS t	                      | j        _        dS )zSet the default behavior for a config environment to be secure.

    If Session.key/keyfile have not been set, set Session.key to
    a new random UUID.
    zdefault_secure is deprecatedr<   r=   rh   r/   rg   N)rC   rD   DeprecationWarningrh   rd   r/   )rk   s    r2   default_securero      sW     M02DQRSSSSCUck11Y#+5M5M"nnCKOOOr3   r   c                 4    t          j        t                    S )z#Return timezone-aware UTC timestamp)r   nowutcrc   r3   r2   utcnowrs      s    <r3   c                       e Zd ZdZ ed          Z ed          dd            Z ed	          Z	dd
Z
 edd          Z ed          ZddZd fdZ xZS )SessionFactoryz[The Base class for configurables that have a Session, Context, logger,
    and IOLoop.
    ri   lognamechanger"   r#   rl   c                D    t          j        |d                   | _        d S )Nnew)logging	getLoggerlogselfrw   s     r2   _logname_changedzSessionFactory._logname_changed   s    $VE]33r3   zmq.Contextc                (    t          j                    S N)zmqContextr~   s    r2   _context_defaultzSessionFactory._context_default   s    {}}r3   zjupyter_client.session.SessionT
allow_noneztornado.ioloop.IOLoopr   c                (    t          j                    S r   )r   currentr   s    r2   _loop_defaultzSessionFactory._loop_default   s    ~r3   kwargsc                n     t                      j        di | | j        t          di || _        dS dS )zInitialize a session factory.Nrc   )super__init__sessionrh   r~   r   	__class__s     r2   r   zSessionFactory.__init__   sI    ""6"""<",,V,,DLLL  r3   rw   r"   r#   rl   )r#   r   )r#   r   r   r"   r#   rl   )__name__
__module____qualname____doc__r   rv   r   r   r   contextr   r   loopr   r   __classcell__r   s   @r2   ru   ru      s          gbkkGWY4 4 4 4 h}%%G    h7DIIIG8+,,D       - - - - - - - - - -r3   ru   c                  B    e Zd ZdZddZddZdd
ZddZddZddZ	dS )MessagezA simple message object that maps dict keys to attributes.

    A Message can be created from a dict and a dict from a Message instance
    simply by calling dict(msg_obj).msg_dictdict[str, t.Any]r#   rl   c                    | j         }t          |                                          D ].\  }}t          |t                    rt	          |          }|||<   /dS )zInitialize a message.N)__dict__r'   itemsr&   r   )r~   r   dctkr1   s        r2   r   zMessage.__init__   s`    mNN((** 	 	DAq!T"" AJJCFF	 	r3   t.ItemsView[str, t.Any]c                N    t          | j                                                  S r   )iterr   r   r   s    r2   __iter__zMessage.__iter__   s    DM''))***r3   r+   c                *    t          | j                  S r   )reprr   r   s    r2   __repr__zMessage.__repr__  s    DM"""r3   c                4    t          j        | j                  S r   )pprintpformatr   r   s    r2   __str__zMessage.__str__  s    ~dm,,,r3   r   objectboolc                    || j         v S r   r   r~   r   s     r2   __contains__zMessage.__contains__	  s    DM!!r3   r"   c                    | j         |         S r   r   r   s     r2   __getitem__zMessage.__getitem__  s    }Qr3   N)r   r   r#   rl   )r#   r   r#   r+   )r   r   r#   r   )r   r+   r#   r"   )
r   r   r   r   r   r   r   r   r   r   rc   r3   r2   r   r      s        ( (
   + + + +# # # #- - - -" " " "           r3   r   msg_idmsg_typeusernamer   Session | strr   c                H    t                      }t          }t                      S )zCreate a new message header)rs   r   locals)r   r   r   r   dateversions         r2   
msg_headerr     s     88DG88Or3   msg_or_headerc                    | si S 	 | d         }n+# t           $ r 	 | d         }| }n# t           $ r  w xY wY nw xY wt          |t                    st          |          }|S )z-Given a message or header, return the header.headerr   )KeyErrorr&   r'   )r   hs     r2   extract_headerr     s     	
(#   	h'A AA  	 	 		 A a GGHs    
7%7177c                      e Zd ZdZ eddd          Z eddd          Z eddd          Z e	d	          dld            Z
 eddd          Z e	d          dld            Z eddd          ZdmdZ e	d          dld            Z ed          Z eej                            dd          dd          Z ei dd          Z ed          Z edd          Zdnd!Z e	d"          dld#            Z ed$dd%          Z e	d&          dld'            Z  e!            Z"dod)Z# e$e%j&        d*          Z'dpd+Z( e)            Z* ed,dd-          Z+ eddd.          Z, e	d/          dld0            Z- e            Z. e!e/          Z0 e	d1          dld2            Z1 e!e2          Z3 e	d3          dld4            Z4 ed,dd5          Z5 ee6dd6          Z7 ee8dd7          Z9dq fd9Z:drd:Z;dZ<e=dmd;            Z>dpd<Z?dsd?Z@	 	 	 	 dtdudGZAdvdJZB	 dwdxdOZC	 	 	 	 	 	 	 dydzdYZD	 	 	 d{d|d^ZEeFjG        ddfd}dbZH	 d~ddeZIddgZJdpdhZK	 	 dddiZLddkZM xZNS )rh   a  Object for handling serialization and sending of messages.

    The Session object handles building messages and sending them
    with ZMQ sockets or ZMQStream objects.  Objects can communicate with each
    other over the network via Session objects, and only need to work with the
    dict-based IPython message spec. The Session will handle
    serialization/deserialization, security, and metadata.

    Sessions support configurable serialization via packer/unpacker traits,
    and signing with HMAC digests via the key/keyfile traits.

    Parameters
    ----------

    debug : bool
        whether to trigger extra debugging statements
    packer/unpacker : str : 'json', 'pickle' or import_string
        importstrings for methods to serialize message parts.  If just
        'json' or 'pickle', predefined JSON and pickle packers will be used.
        Otherwise, the entire importstring must be used.

        The functions must accept at least valid JSON input, and output *bytes*.

        For example, to use msgpack:
        packer = 'msgpack.packb', unpacker='msgpack.unpackb'
    pack/unpack : callables
        You can also set the pack/unpack callables for serialization directly.
    session : bytes
        the ID of this Session object.  The default is to generate a new UUID.
    username : unicode
        username added to message headers.  The default is to ask the OS.
    key : bytes
        The key used to initialize an HMAC signature.  If unset, messages
        will not be signed or checked.
    keyfile : filepath
        The file containing a key.  If this is set, `key` will be initialized
        to the contents of the file.

    FTzDebug output in the Session)confighelpzWhether to check PID to protect against calls after fork.

        This check can be disabled if fork-safety is handled elsewhere.
        r?   zThe name of the packer for serializing messages.
            Should be one of 'json', 'pickle', or an import name
            for a custom callable serializer.packerrw   r"   r#   rl   c                <   |d         }|                                 dk    r!t          | _        t          | _        || _        d S |                                 dk    r!t          | _        t          | _        || _        d S t          t          |                    | _        d S Nry   r?   rQ   )
lowerrG   packrN   unpackunpackerrS   pickle_unpackerr   r+   r~   rw   ry   s      r2   _packer_changedzSession._packer_changedi  s|    Um99;;&  #DI'DKDMMMYY[[H$$%DI)DKDMMM#CHH--DIIIr3   zjThe name of the unpacker for unserializing messages.
        Only used with custom functions for `packer`.r   c                <   |d         }|                                 dk    r!t          | _        t          | _        || _        d S |                                 dk    r!t          | _        t          | _        || _        d S t          t          |                    | _        d S r   )
r   rG   r   rN   r   r   rS   r   r   r+   r   s      r2   _unpacker_changedzSession._unpacker_changed~  s|    Um99;;&  #DI'DKDKKKYY[[H$$%DI)DKDKKK%c#hh//DKKKr3   ri   z"The UUID identifying this session.r+   c                V    t                      }|                    d          | _        |S NrX   )ra   r.   bsession)r~   us     r2   _session_defaultzSession._session_default  s#    HH))r3   r   c                D    | j                             d          | _        d S r   )r   r.   r   r}   s     r2   _session_changedzSession._session_changed  s    ++G44r3   r3   USERr   z:Username for the Session. Default is your system username.)r   r   zZMetadata dictionary, which serves as the default top-level metadata dict for each message.r   z$execution key, for signing messages.r5   c                    t                      S r   )rd   r   s    r2   _key_defaultzSession._key_default  s    ~~r3   r/   c                .    |                                   d S r   )	_new_authr}   s     r2   _key_changedzSession._key_changed  s    r3   zhmac-sha256zcThe digest scheme used to construct the message signatures.
        Must have the form 'hmac-HASH'.signature_schemec                F   |d         }|                     d          st          d|z            |                    dd          d         }	 t          t          |          | _        n%# t          $ r}t          d|z            |d }~ww xY w|                                  d S )Nry   zhmac-z0signature_scheme must start with 'hmac-', got %rrV   r   z!hashlib has no such attribute: %s)
startswithr   splitgetattrhashlib
digest_modAttributeErrorr   )r~   rw   ry   	hash_namerE   s        r2   _signature_scheme_changedz!Session._signature_scheme_changed  s    Um~~g&& 	WORUUVVVIIc1%%a(		U%gy99DOO 	U 	U 	U@9LMMSTT	Us   A( (
B
2BB

t.Callablec                    t           j        S r   )r   sha256r   s    r2   _digest_mod_defaultzSession._digest_mod_default  s
    ~r3   r   c                p    | j         r't          j        | j         | j                  | _        d S d | _        d S )N)	digestmod)r/   hmacHMACr   authr   s    r2   r   zSession._new_auth  s5    8 		$(doFFFDIIIDIIIr3   i   zzThe maximum number of digests to remember.

        The digest history will be culled when it exceeds this value.
        z&path to file containing execution key.rg   c                    t          |d         d          5 }|                                                                | _        d d d            d S # 1 swxY w Y   d S )Nry   rb)openreadstripr/   )r~   rw   fs      r2   _keyfile_changedzSession._keyfile_changed  s    &-&& 	(!vvxx~~''DH	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(s   ,AAAr   c                r    |d         }t          |          st          dt          |          z            d S )Nry   zpacker must be callable, not %scallablerA   typer   s      r2   _pack_changedzSession._pack_changed  s@    Um}} 	K=S		IJJJ	K 	Kr3   r   c                r    |d         }t          |          st          dt          |          z            d S )Nry   z!unpacker must be callable, not %sr   r   s      r2   _unpack_changedzSession._unpack_changed  sB     Um}} 	M?$s))KLLL	M 	Mr3   zJThreshold (in bytes) beyond which a buffer should be sent without copying.z[Threshold (in bytes) beyond which an object's buffer should be extracted to avoid pickling.zThe maximum number of items for a container to be introspected for custom serialization.
        Containers larger than this are pickled outright.
        r   c                P    t                      j        di | |                                  |                     i           | _        | j         t          j                    | _        | 	                                 | j
        s#t                                          d           dS dS )ae  create a Session object

        Parameters
        ----------

        debug : bool
            whether to trigger extra debugging statements
        packer/unpacker : str : 'json', 'pickle' or import_string
            importstrings for methods to serialize message parts.  If just
            'json' or 'pickle', predefined JSON and pickle packers will be used.
            Otherwise, the entire importstring must be used.

            The functions must accept at least valid JSON input, and output
            *bytes*.

            For example, to use msgpack:
            packer = 'msgpack.packb', unpacker='msgpack.unpackb'
        pack/unpack : callables
            You can also set the pack/unpack callables for serialization
            directly.
        session : unicode (must be ascii)
            the ID of this Session object.  The default is to generate a new
            UUID.
        bsession : bytes
            The session as bytes
        username : unicode
            username added to message headers.  The default is to ask the OS.
        key : bytes
            The key used to initialize an HMAC signature.  If unset, messages
            will not be signed or checked.
        signature_scheme : str
            The message digest scheme. Currently must be of the form 'hmac-HASH',
            where 'HASH' is a hashing function available in Python's hashlib.
            The default is 'hmac-sha256'.
            This is ignored if 'key' is empty.
        keyfile : filepath
            The file containing a key.  If this is set, `key` will be
            initialized to the contents of the file.
        zCMessage signing is disabled.  This is insecure and not recommended!Nrc   )r   r   _check_packersr   noner   r]   getpidpidr   r/   r   warningr   s     r2   r   zSession.__init__  s    P 	""6"""IIbMM	9;;x 	LL  U    	 	r3   c           	         t          |                       }|                                 D ]!}t          ||t          | |                     "t	                      |_        |j                            | j                   |S )a  Create a copy of this Session

        Useful when connecting multiple times to a given kernel.
        This prevents a shared digest_history warning about duplicate digests
        due to multiple connections to IOPub in the same process.

        .. versionadded:: 5.1
        )r  traitssetattrr   setdigest_historyupdate)r~   new_sessionnames      r2   clonezSession.cloneD  sw     !d4jjllKKMM 	< 	<DKwtT':':;;;;%(UU""))$*=>>>r3   c                p    | j         }| xj         dz  c_         | j         dt          j                     d| S )Nr   _)message_countr   r]   r	  )r~   message_numbers     r2   r   zSession.msg_idX  sB    +a,????~???r3   c                   | j         | j        dddgi}	  |          }n/# t          $ r"}d| j         d| }t	          |          |d}~ww xY wt          |t                    st	          dt          |          z            	  |          }||k    sJ n7# t          $ r*}d| j         d	| j         d
| }t	          |          |d}~ww xY wdt                      i}	   |                    }t          |d         t                    rd}t	          |          dS # t          $ r fd| _         fd| _        Y dS w xY w)z#check packers for datetime support.ar   hizpacker 'z(' could not serialize a simple message: Nz,message packed to %r, but bytes are requiredz
unpacker 'z'' could not handle output from packer 'z': tz!Shouldn't deserialize to datetimec                4     t          |                     S r   )r    )rO   r   s    r2   <lambda>z(Session._check_packers.<locals>.<lambda>  s    $$|A"7"7 r3   c                     |           S r   rc   )rH   r   s    r2   r  z(Session._check_packers.<locals>.<lambda>  s    FF1II r3   )r   r   	Exceptionr   rB   r&   r5   r  r   rs   r   )	r~   msg_listrF   rE   msgunpackedmsg_datetimer   r   s	          @@r2   r  zSession._check_packers^  s   y !T#	)T(^^FF 	) 	) 	)UT[UURSUUCS//q(	)
 &%(( 	\KdSYllZ[[[	)vf~~Hx''''' 	) 	) 	))T] ) )[) )%&) )  S//q(	) VXX	.vdd<0011H(3-22 &9 oo%& &  	. 	. 	.7777DI----DKKKK	.s?   $ 
AAAB 
C&%CC$A D& &EEr   r   c                D    t          | j        || j        | j                  S )z#Create a header for a message type.)r   r   r   r   )r~   r   s     r2   r   zSession.msg_header  s    $+xMMMr3   Ncontentdict | Noneparentdict[str, t.Any] | Noner   metadatac                "   i }||                      |          n|}||d<   |d         |d<   |d         |d<   |i nt          |          |d<   |i n||d<   | j                                        |d<   ||d                             |           |S )zReturn the nested message dict.

        This format is different from what is sent over the wire. The
        serialize/deserialize methods converts this nested message dict to the wire
        format, which is a list of message parts.
        Nr   r   r   parent_headerr&  r*  )r   r   r*  copyr  )r~   r   r&  r(  r   r*  r"  s          r2   r"  zSession.msg  s     .4n***&Hx(H ,J%+^rr9O9OO&GI-,,..J
O""8,,,
r3   r!  r(   c                    | j         dS | j                                         }|D ]}|                    |           |                                                                S )zSign a message with HMAC digest. If no auth, return b''.

        Parameters
        ----------
        msg_list : list
            The [p_header,p_parent,p_content] part of the message list.
        Nr3   )r   r-  r  	hexdigestr.   )r~   r!  r   ms       r2   signzSession.sign  s\     93INN 	 	AHHQKKKK{{}}##%%%r3   r"  re   list[bytes] | bytes | Nonelist[bytes]c                8   |                     di           }|| j        }nt          |t                    r|                     |          }n`t          |t
                    rnJt          |t                    r|                    d          }nt          dt          |          z            |                     |d                   |                     |d                   |                     |d                   |g}g }t          |t                    r|                    |           n||                    |           |                    t                     |                     |          }|                    |           |                    |           |S )a2  Serialize the message components to bytes.

        This is roughly the inverse of deserialize. The serialize/deserialize
        methods work with full message lists, whereas pack/unpack work with
        the individual message parts in the message list.

        Parameters
        ----------
        msg : dict or Message
            The next message dict as returned by the self.msg method.

        Returns
        -------
        msg_list : list
            The list of bytes objects to be sent with the format::

                [ident1, ident2, ..., DELIM, HMAC, p_header, p_parent,
                 p_metadata, p_content, buffer1, buffer2, ...]

            In this list, the ``p_*`` entities are the packed or serialized
            versions, so if JSON is used, these are utf8 encoded JSON strings.
        r&  Nr%   zContent incorrect type: %sr   r,  r*  )getr  r&   r'   r   r5   r+   r.   rA   r  r(   extendappendDELIMr1  )r~   r"  re   r&  real_messageto_send	signatures          r2   	serializezSession.serialize  sy   6 '')R((?iGG&& 		Jii((GG'' 	J%% 	JnnV,,GG84==HIII IIc(m$$IIc/*++IIc*o&&	
 eT"" 	"NN5!!!!NN5!!!uIIl++	y!!!|$$$r3   stream*zmq.sugar.socket.Socket | ZMQStream | Nonemsg_or_typedict[str, t.Any] | strbytes | list[bytes] | Nonebufferslist[bytes] | Nonetrackr   c
                   t          |t          j                  sd}t          |t          j        j                  r(|J t          j                            |j                  }t          |t          t          f          r|}
|p|
                    dg           }n| 	                    |||||	          }
| j
        r@t          j                    | j        k    r$t                                          d|
           dS |g n|}t!          |          D ]}\  }}t          |t"                    r|}n5	 t#          |          }n$# t$          $ r}d}t%          |          |d}~ww xY wt'          |d          r|j        st+          d||fz            ~| j        rt/          |
| j                  }
|                     |
|          }|                    |           t5          d	 |D                       }|| j        k     }|r|r|r|s|                    |dd
          }n(|rt:          }|                    ||           nt:          }| j        r<t?          j        |
           t?          j        |           t?          j        |           ||
d<   |
S )aW  Build and send a message via stream or socket.

        The message format used by this function internally is as follows:

        [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content,
         buffer1,buffer2,...]

        The serialize/deserialize methods convert the nested message dict into this
        format.

        Parameters
        ----------

        stream : zmq.Socket or ZMQStream
            The socket-like object used to send the data.
        msg_or_type : str or Message/dict
            Normally, msg_or_type will be a msg_type unless a message is being
            sent more than once. If a header is supplied, this can be set to
            None and the msg_type will be pulled from the header.

        content : dict or None
            The content of the message (ignored if msg_or_type is a message).
        header : dict or None
            The header dict for the message (ignored if msg_to_type is a message).
        parent : Message or dict or None
            The parent or parent header describing the parent of this message
            (ignored if msg_or_type is a message).
        ident : bytes or list of bytes
            The zmq.IDENTITY routing path.
        metadata : dict or None
            The metadata describing the message
        buffers : list or None
            The already-serialized buffers to be appended to the message.
        track : bool
            Whether to track.  Only for use with Sockets, because ZMQStream
            objects cannot track messages.


        Returns
        -------
        msg : dict
            The constructed message.
        FNrB  )r&  r(  r   r*  z/WARNING: attempted to send message from fork
%sz0Buffer objects must support the buffer protocol.
contiguousz Buffer %i (%r) is not contiguousc                ,    g | ]}t          |          S rc   )len)rY   rH   s     r2   
<listcomp>z Session.send.<locals>.<listcomp>V  s    ///!s1vv///r3   T)r-  rD  r-  tracker) r&   r   Socketasyncioshadow
underlyingr   r'   r5  r"  	check_pidr]   r	  r
  r   r  r-   
memoryviewrA   hasattrrF  rB   adapt_versionr   r<  r6  maxcopy_thresholdsend_multipartDONEdebugr   )r~   r=  r?  r&  r(  re   rB  rD  r   r*  r"  idxr`   viewrE   emsgr:  longestr-  rK  s                       r2   sendzSession.send  s   n &#*-- 	Efck011 	:%%%Z&&v'899FkGT?33 	 C7B!7!7GG((!   C > 	bikkTX55LL  !SUXYYY4""W!'** 	R 	RHC#z** 11%c??DD  1 1 1MD#D//q01
 t\** R4? R !CsCj!PQQQ 	1T/00C..e,,w//w///00,, 	g 	% 	 	++G%t+LLGG 	G!!'!5555G: 	#M#M'"""M'""" I
s   /D??
E 	EE zmq.sugar.socket.Socketflagsintr-  c                   g }t          |t                    r|g}||                    |           |                    t                     |                    |                     |dd                              |                    |           t          |t          j        j                  r$t          j        	                    |j
                  }|                    |||           dS )a0  Send a raw message via ident path.

        This method is used to send a already serialized message.

        Parameters
        ----------
        stream : ZMQStream or Socket
            The ZMQ stream or socket to use for sending the message.
        msg_list : list
            The serialized list of messages to send. This only includes the
            [p_header,p_parent,p_metadata,p_content,buffer1,buffer2,...] portion of
            the message.
        ident : ident or list
            A single ident or a list of idents to use in sending.
        Nr   r\   rJ  )r&   r5   r6  r7  r8  r1  r   rM  rL  rN  rO  rV  )r~   r=  r!  r_  r-  re   r:  s          r2   send_rawzSession.send_rawl  s    . eU## 	GENN5!!!utyy!A#//000x   fck011 	:Z&&v'899Fgu488888r3   socketmode2tuple[list[bytes] | None, dict[str, t.Any] | None]c                   t          |t                    r|j        }t          |t          j        j                  r$t          j                            |j                  }	 |                    ||          }n3# t          j	        $ r!}|j
        t          j        k    rY d}~dS  d}~ww xY w|                     ||          \  }}	 ||                     |||          fS # t          $ r}|d}~ww xY w)aY  Receive and unpack a message.

        Parameters
        ----------
        socket : ZMQStream or Socket
            The socket or stream to use in receiving.

        Returns
        -------
        [idents], msg
            [idents] is a list of idents and msg is a nested message dict of
            same format as self.msg returns.
        rJ  N)NN)r&  r-  )r&   r   rc  r   rM  rL  rN  rO  recv_multipartZMQErrorerrnoEAGAINfeed_identitiesdeserializer   )r~   rc  rd  r&  r-  r!  rE   identss           r2   recvzSession.recv  s   ( fi(( 	#]Ffck011 	:Z&&v'899F	,,T,==HH| 	 	 	w#*$$ "zzzzz	  //$??	4++HgD+QQQQ 	 	 	G	s6   !A9 9B)B$#B$$B)C   
C1*C,,C1list[bytes] | list[zmq.Message]3tuple[list[bytes], list[bytes] | list[zmq.Message]]c                   |r[t          j        t           j        t                   |          }|                    t
                    }|d|         ||dz   d         fS t          j        t           j        t          j                 |          }d}t          |          D ]\  }}|j        t
          k    rd} n|rd}t          |          |d|         ||dz   d         }}d |D             |fS )ae  Split the identities from the rest of the message.

        Feed until DELIM is reached, then return the prefix as idents and
        remainder as msg_list. This is easily broken by setting an IDENT to DELIM,
        but that would be silly.

        Parameters
        ----------
        msg_list : a list of Message or bytes objects
            The message to be split.
        copy : bool
            flag determining whether the arguments are bytes or Messages

        Returns
        -------
        (idents, msg_list) : two lists
            idents will always be a list of bytes, each of which is a ZMQ
            identity. msg_list will be a list of bytes or zmq.Messages of the
            form [HMAC,p_header,p_parent,p_content,buffer1,buffer2,...] and
            should be unpackable/unserializable via self.deserialize at this
            point.
        Nr   TFzDELIM not in msg_listc                6    g | ]}t          |j                   S rc   r5   )rY   r0  s     r2   rI  z+Session.feed_identities.<locals>.<listcomp>  s     333qE!'NN333r3   )
r  castListr5   indexr8  r   r   r-   rB   )r~   r!  r-  rY  failedr0  r"  rm  s           r2   rk  zSession.feed_identities  s    2  	>vafUmX66H..''CDSD>8C!GII#666vafS[18<<HF#H--  Q7e##"FE $  &- oo%'~xa		/BHF33F333X==r3   r;  c                    | j         dk    rdS | j                            |           t          | j                  | j         k    r|                                  dS dS )z9add a digest to history to protect against replay attacksr   N)digest_history_sizer  addrH  _cull_digest_history)r~   r;  s     r2   _add_digestzSession._add_digest  se    #q((F	***t"##d&>>>%%''''' ?>r3   c                P   t          | j                  }t          t          |dz            || j        z
            }||k    rt                      | _        dS t          j        t          t          | j                            |          }| j        
                    |           dS )z_cull the digest history

        Removes a randomly selected 10% of the digest history
        
   N)rH  r  rT  r`  ry  r  randomsampletuplesorteddifference_update)r~   r   	n_to_cullto_culls       r2   r{  zSession._cull_digest_history  s    
 d)**GrM**Gd6N,NOO	"%%%DF-fT-@&A&A B BINN--g66666r3   c                h   d}i }|szt          j        t           j        t          j                 |          }d |d|         D             }t          j        t           j        t
                   |          }|||d         z   }t          j        t           j        t
                   |          }| j        |d         }|sd}t          |          || j        v rt          d|z            |r| 	                    |           | 
                    |dd                   }	t          ||	          sd|z  }t          |          t          |          |k    sd	|z  }t          |          |                     |d                   }
t          |
          |d
<   |
d         |d<   |
d         |d<   t          |                     |d                             |d<   |                     |d                   |d<   |r|                     |d                   |d<   n|d         |d<   d |dd         D             }|rP|d         j        Ct          j        t           j        t          j                 |          }d |dd         D             }||d<   | j        rt%          j        |           t'          |          S )a  Unserialize a msg_list to a nested message dict.

        This is roughly the inverse of serialize. The serialize/deserialize
        methods work with full message lists, whereas pack/unpack work with
        the individual message parts in the message list.

        Parameters
        ----------
        msg_list : list of bytes or Message objects
            The list of message parts of the form [HMAC,p_header,p_parent,
            p_metadata,p_content,buffer1,buffer2,...].
        content : bool (True)
            Whether to unpack the content dict (True), or leave it packed
            (False).
        copy : bool (True)
            Whether msg_list contains bytes (True) or the non-copying Message
            objects in each place (False).

        Returns
        -------
        msg : dict
            The nested message dict with top-level keys [header, parent_header,
            content, buffers].  The buffers are returned as memoryviews.
           c                6    g | ]}t          |j                   S rc   rs  )rY   r"  s     r2   rI  z'Session.deserialize.<locals>.<listcomp>!  s"    !P!P!Ps%	"2"2!P!P!Pr3   Nr   zUnsigned MessagezDuplicate Signature: %rr   zInvalid Signature: %rz1malformed message, must have at least %i elementsr   r   r   r<   r,     r*  r\   r&  c                ,    g | ]}t          |          S rc   )rQ  rY   bs     r2   rI  z'Session.deserialize.<locals>.<listcomp>@  s    777Q:a==777r3   c                P    g | ]#}t          t          |j                            $S rc   )rQ  r5   r  s     r2   rI  z'Session.deserialize.<locals>.<listcomp>D  s(    HHHaz%..11HHHr3   rB  )r  rt  ru  r   r   r5   r   rB   r  r|  r1  r   rH  rA   r   r   shaperX  r   r   )r~   r!  r&  r-  minlenmessagemsg_list_beginningr;  r"  checkr   rB  s               r2   rl  zSession.deserialize  s   <  	>vafS[18<<H!P!Phww>O!P!P!PvafUmX66H)HVWW,==H6!&-229  I &( oo%D/// !:Y!FGGG ,  +++IIhqsm,,E!)U33 &-	9 oo%8}}&&ENCC.. Xa[)))&11"8,$Z0
#0Xa[1I1I#J#J "kk(1+66
 	-!%Xa[!9!9GI!)!GI77(122,777 	Iwqz'/vafS[18<<HHH8ABB<HHHG$	: 	#M'"""W~~r3   argsc                T    t          j        dt          d            | j        |i |S )z'**DEPRECATED** Use deserialize instead.z;Session.unserialize is deprecated. Use Session.deserialize.r<   r=   )rC   rD   rn   rl  )r~   r  r   s      r2   unserializezSession.unserializeK  s@     	I	
 	
 	
 	

  t0000r3   r   r   r#   r5   )r#   r   )r#   rl   r   )r#   rh   )r   r+   r#   r   )NNNN)r   r+   r&  r'  r(  r)  r   r)  r*  r)  r#   r   )r!  r(   r#   r5   r   )r"  r   re   r2  r#   r3  )NNNNFNN)r=  r>  r?  r@  r&  r)  r(  r)  re   rA  rB  rC  rD  r   r   r)  r*  r)  r#   r)  )r   TN)r=  r^  r!  r(   r_  r`  r-  r   re   rA  r#   rl   )
rc  r^  rd  r`  r&  r   r-  r   r#   re  )T)r!  ro  r-  r   r#   rp  )r;  r5   r#   rl   )TT)r!  ro  r&  r   r-  r   r#   r   )r  r"   r   r"   r#   r   )Or   r   r   r   r
   rX  rP  r   r   r   r   r   r   r   r   r   r   r   r   r   r]   environr5  r   r   r*  r   rS  r/   r   r   r   r   r	   r   r   r   r   r   r   r   r   r  ry  rg   r   r
  default_packerr   r  default_unpackerr   r  rU  	MAX_BYTESbuffer_threshold	MAX_ITEMSitem_thresholdr   r  r  propertyr   r  r   r"  r1  r<  r]  rb  r   NOBLOCKrn  rk  r|  r{  rl  r  r   r   s   @r2   rh   rh   -  s       & &P Dt*KLLLE  I 1  F WX. . . .  9  H WZ0 0 0 0 hr$-UVVVG   
 WY5 5 5 5 vc{{Hw

vz**M  H t
  H GAJJM &#M
N
N
NC    WU^^   ^ w+   W  	 	 	 ! 	 J    8DI$///D    SUUN!'   gb,XYYYGWY( ( ( (
 '))C 3~DWV__K K K _K
 S!""FWXM M M M WY  N
 w   W  N2 2 2 2 2 2h   $ M@ @ @ X@
%. %. %. %.NN N N N  $*.*.,0    4& & & &$ -1> > > > >H ,0*.,0&**.,0x x x x x| ,0#9 #9 #9 #9 #9P K) ) ) ) )X GK(> (> (> (> (>T	( 	( 	( 	(7 7 7 7  	K K K K KZ1 1 1 1 1 1 1 1r3   )r!   r"   r#   r"   )r!   r"   r#   r5   )rH   rI   r#   r"   )rO   r"   r#   r5   r   r  )rk   r"   r#   rl   )r#   r   )
r   r+   r   r+   r   r+   r   r   r#   r   )r   r   r#   r   )Qr   
__future__r   r   r   r?   rz   r]   rQ   r   r  typingr  rC   binasciir   r   r   r   zmq.asyncior   tornado.ioloopr   	traitletsr	   r
   r   r   r   r   r   r   r   r   r   r   traitlets.config.configurabler   r   traitlets.logr   traitlets.utils.importstringr   zmq.eventloop.zmqstreamr   _versionr   adapterr   jsonutilr   r   r   r    DEFAULT_PROTOCOLrR   rr   r*   r  r  rG   rN   rS   rM   r   r  r  r8  MessageTrackerrW  ra   rd   session_aliasessession_flagsro   rs   ru   r   r   r   rh   rc   r3   r2   <module>r     s  	 	 # " " " " "     				               ' ' ' ' ' ' ' '           ! ! ! ! ! !                            L K K K K K K K $ $ $ $ $ $ 4 4 4 4 4 4 - - - - - - & & & & & &       K K K K K K K K K K K K)l   ( 		   8   : : : :
 ,  sL L L L$ $ $ $    
LLNNr::;	 
CB//0* 
% 
% 
% 
%   - - - - -( - - -B               >      (f1 f1 f1 f1 f1l f1 f1 f1 f1 f1r3   