
    g\&                        U d dl mZ d dl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mZmZ d d	lmZ erd d
lmZ d dlmZ  ee      Zded<   ddZddZ G d de      Zy)    )annotationsN)TYPE_CHECKINGFinal)WeakKeyDictionary)configutil)
get_logger)
ForwardMsg)	CacheStatCacheStatsProvidergroup_stats)HASHLIB_KWARGS)MutableMapping)
AppSessionr   _LOGGERc                B   | j                   dk(  r| j                  }| j                  d       t        j                  di t
        }|j                  | j                                |j                         | _         | j                  j                  |       | j                   S )ao  Computes and assigns the unique hash for a ForwardMsg.

    If the ForwardMsg already has a hash, this is a no-op.

    Parameters
    ----------
    msg : ForwardMsg

    Returns
    -------
    string
        The message's hash, returned here for convenience. (The hash
        will also be assigned to the ForwardMsg; callers do not need
        to do this.)

     metadata )
hashr   
ClearFieldhashlibmd5r   updateSerializeToString	hexdigestCopyFrom)msgr   hashers      X/var/www/openai/venv/lib/python3.12/site-packages/streamlit/runtime/forward_msg_cache.pypopulate_hash_if_neededr!   #   s{    " xx2~ <<z" .~.c++-.##% 	h'88O    c                    t               }t        |       |_        |j                  j	                  | j                         |S )a  Create a ForwardMsg that refers to the given message via its hash.

    The reference message will also get a copy of the source message's
    metadata.

    Parameters
    ----------
    msg : ForwardMsg
        The ForwardMsg to create the reference to.

    Returns
    -------
    ForwardMsg
        A new ForwardMsg that "points" to the original message via the
        ref_hash field.

    )r
   r!   ref_hashr   r   )r   ref_msgs     r    create_reference_msgr&   E   s5    $ lG.s3Gcll+Nr"   c                      e Zd ZdZ G d d      Zd ZddZ	 	 	 	 	 	 	 	 ddZddZ	 	 	 	 	 	 	 	 ddZ	dd	Z
	 	 	 	 	 	 dd
ZddZddZy)ForwardMsgCachea  A cache of ForwardMsgs.

    Large ForwardMsgs (e.g. those containing big DataFrame payloads) are
    stored in this cache. The server can choose to send a ForwardMsg's hash,
    rather than the message itself, to a client. Clients can then
    request messages from this cache via another endpoint.

    This cache is *not* thread safe. It's intended to only be accessed by
    the server thread.

    c                  T    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dZ
y	)ForwardMsgCache.EntryzCache entry.

        Stores the cached message, and the set of AppSessions
        that we've sent the cached message to.

        c                0    || _         t               | _        y N)r   r   _session_script_run_counts)selfr   s     r    __init__zForwardMsgCache.Entry.__init__r   s    DH!# +r"   c                ,    t        j                  |       S r,   r   repr_r.   s    r    __repr__zForwardMsgCache.Entry.__repr__x   s    ::d##r"   c                    | j                   j                  |d      }||k  rt        j                  d||       |}|| j                   |<   y)a  Adds a reference to a AppSession that has referenced
            this Entry's message.

            Parameters
            ----------
            session : AppSession
            script_run_count : int
                The session's run count at the time of the call

            r   zMNew script_run_count (%s) is < prev_run_count (%s). This should never happen!N)r-   getr   error)r.   sessionscript_run_countprev_run_counts       r    add_session_refz%ForwardMsgCache.Entry.add_session_ref{   sS     "<<@@!LN.00$"	 $2 7GD++G4r"   c                    || j                   v S r,   r-   r.   r8   s     r    has_session_refz%ForwardMsgCache.Entry.has_session_ref   s    d====r"   c                &    || j                   |   z
  S )znThe age of the given session's reference to the Entry,
            given a new script_run_count.

            r=   )r.   r8   r9   s      r    get_session_ref_agez)ForwardMsgCache.Entry.get_session_ref_age   s     $d&E&Eg&NNNr"   c                    | j                   |= y r,   r=   r>   s     r    remove_session_refz(ForwardMsgCache.Entry.remove_session_ref   s    //8r"   c                2    t        | j                        dkD  S )zzTrue if this Entry has references from any AppSession.

            If not, it can be removed from the cache.
            r   )lenr-   r3   s    r    has_refszForwardMsgCache.Entry.has_refs   s    
 t667!;;r"   N)r   ForwardMsg | Nonereturnstrr8   r   r9   intrI   None)r8   r   rI   bool)r8   r   r9   rL   rI   rL   r8   r   rI   rM   )rI   rN   )__name__
__module____qualname____doc__r/   r4   r;   r?   rA   rC   rF   r   r"   r    Entryr*   j   sG    			$	H,	>	O%	O9<	O	O	9	<r"   rT   c                    i | _         y r,   )_entriesr3   s    r    r/   zForwardMsgCache.__init__   s	    :<r"   c                ,    t        j                  |       S r,   r1   r3   s    r    r4   zForwardMsgCache.__repr__   s    zz$r"   c                @   t        |       | j                  j                  |j                  d      }|Yt	        j
                  d      rt        j                  |      }nt        j                  d      }|| j                  |j                  <   |j                  ||       y)a  Add a ForwardMsg to the cache.

        The cache will also record a reference to the given AppSession,
        so that it can track which sessions have already received
        each given ForwardMsg.

        Parameters
        ----------
        msg : ForwardMsg
        session : AppSession
        script_run_count : int
            The number of times the session's script has run

        Nz)global.storeCachedForwardMessagesInMemory)	r!   rV   r6   r   r   
get_optionr(   rT   r;   )r.   r   r8   r9   entrys        r    add_messagezForwardMsgCache.add_message   s}    " 	 $!!#((D1=  !LM'--c2'--d3&+DMM#((#g'78r"   c                Z    | j                   j                  |d      }|r|j                  S dS )zReturn the message with the given ID if it exists in the cache.

        Parameters
        ----------
        hash : str
            The id of the message to retrieve.

        Returns
        -------
        ForwardMsg | None

        N)rV   r6   r   )r.   r   rZ   s      r    get_messagezForwardMsgCache.get_message   s+     !!$-!uyy+t+r"   c                    t        |       | j                  j                  |j                  d      }||j	                  |      sy|j                  ||      }|t        t        j                  d            k  S )z6Return True if a session has a reference to a message.NFglobal.maxCachedMessageAge)	r!   rV   r6   r   r?   rA   rL   r   rY   )r.   r   r8   r9   rZ   ages         r    has_message_referencez%ForwardMsgCache.has_message_reference   sl     	 $!!#((D1= 5 5g > ''1ABc&++,HIJJJr"   c                    | j                   j                         j                         D ]E  \  }}|j                  |      r|j	                  |       |j                         r9| j                   |= G y)zRemove refs for all entries for the given session.

        This should be called when an AppSession is disconnected or closed.

        Parameters
        ----------
        session : AppSession
        N)rV   copyitemsr?   rC   rF   )r.   r8   msg_hashrZ   s       r    remove_refs_for_sessionz'ForwardMsgCache.remove_refs_for_session   s\      $}}11399;OHe$$W-((1>># MM(+  <r"   c                   t        j                  d      }| j                  j                         j	                         D ]  \  }}|j                  |      s|j                  ||      }||kD  s0t        j                  dt        |      ||       |j                  |       |j                         rs| j                  |=  y)a8  Remove any cached messages that have expired from the given session.

        This should be called each time a AppSession finishes executing.

        Parameters
        ----------
        session : AppSession
        script_run_count : int
            The number of times the session's script has run

        r_   z4Removing expired entry [session=%s, hash=%s, age=%s]N)r   rY   rV   rc   rd   r?   rA   r   debugidrC   rF   )r.   r8   r9   max_agere   rZ   r`   s          r    "remove_expired_entries_for_sessionz2ForwardMsgCache.remove_expired_entries_for_session   s     ##$@A  $}}11399;OHe((1++G5EFCW}JwK	 ((1~~' h/!  <r"   c                8    | j                   j                          y)z!Remove all entries from the cacheN)rV   clearr3   s    r    rm   zForwardMsgCache.clear  s    r"   c           
         | j                   j                         D cg c]9  \  }}t        dd|j                  |j                  j	                         nd      ; }}}t        |      S c c}}w )NForwardMessageCacher   r   )category_name
cache_namebyte_length)rV   rd   r   r   ByteSizer   )r.   _rZ   statss       r    	get_statszForwardMsgCache.get_stats#  sq     !MM//1"
 25 349II4IEII..0q
 2 	 "
 5!!"
s   >A*NrH   )r   r
   r8   r   r9   rL   rI   rM   )r   rJ   rI   rG   )r   r
   r8   r   r9   rL   rI   rN   rO   rK   )rI   rM   )rI   zlist[CacheStat])rP   rQ   rR   rS   rT   r/   r4   r[   r]   ra   rf   rk   rm   rv   r   r"   r    r(   r(   ]   s    
;< ;<z= 99(29FI9	96, KK(2KFIK	K,*"0!"058"0	"0H	"r"   r(   )r   r
   rI   rJ   )r   r
   rI   r
   )
__future__r   r   typingr   r   weakrefr   	streamlitr   r   streamlit.loggerr	   streamlit.proto.ForwardMsg_pb2r
   streamlit.runtime.statsr   r   r   streamlit.utilr   collections.abcr   streamlit.runtime.app_sessionr   rP   r   __annotations__r!   r&   r(   r   r"   r    <module>r      sW    #  ' % " ' 5 N N ).8H% %D0O"( O"r"   