
    g0u                    <   U d dl m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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 d dlmZ d dl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,m-Z-m.Z.m/Z/m0Z0 d dl1m2Z2m3Z3 d dl4m5Z5 d dl6m7Z7 er$d dl8m9Z9 d dl:m;Z; d dl<m=Z= d dl>m?Z? d dl@mAZA d dlBmCZC dZDdeEd<    eeF      ZGdeEd <    G d! d"eH      ZI ed#$       G d% d&             ZJ G d' d(e	      ZK G d) d*e      ZL G d+ d,      ZMy)-    )annotationsN)	dataclassfield)Enum)TYPE_CHECKINGFinal
NamedTuple)config)LocalComponentRegistry)
get_logger)
ForwardMsg)
AppSession)get_data_cache_stats_provider!get_resource_cache_stats_provider)LocalDiskCacheStorageManager)ForwardMsgCachecreate_reference_msgpopulate_hash_if_needed)MediaFileManager)MemorySessionStorage)is_cacheable_msg)
ScriptData)ScriptCache)ActiveSessionInfoSessionClientSessionClientDisconnectedErrorSessionManagerSessionStorage)SCRIPT_RUN_WITHOUT_ERRORS_KEYSessionStateStatProvider)StatsManager)WebsocketSessionManager)	Awaitable)BaseComponentRegistry)BackMsg)CacheStorageManager)MediaFileStorage)UploadedFileManager<   r   SCRIPT_RUN_CHECK_TIMEOUT_LOGGERc                      e Zd ZdZy)RuntimeStoppedErrorz;Raised by operations on a Runtime instance that is stopped.N)__name__
__module____qualname____doc__     N/var/www/openai/venv/lib/python3.12/site-packages/streamlit/runtime/runtime.pyr-   r-   K   s    Er3   r-   T)frozenc                      e Zd ZU dZded<   ded<   ded<   ded	<    ee
      Zded<    ee
      Z	ded<   e
Zded<    ee
      Zded<   dZded<   y)RuntimeConfigz$Config options for StreamlitRuntime.strscript_path
str | Nonecommand_liner'   media_file_storager(   uploaded_file_manager)default_factoryr&   cache_storage_managerr$   component_registryztype[SessionManager]session_manager_classr   session_storageFboolis_helloN)r.   r/   r0   r1   __annotations__r   r   r?   r   r@   r"   rA   r   rB   rD   r2   r3   r4   r7   r7   O   s    .   )( /. 2742. 
 16.1- 
 3J/I ',<P&QO^Q Hdr3   r7   c                       e Zd ZdZdZdZdZdZy)RuntimeStateINITIALNO_SESSIONS_CONNECTEDONE_OR_MORE_SESSIONS_CONNECTEDSTOPPINGSTOPPEDN)r.   r/   r0   rH   rI   rJ   rK   rL   r2   r3   r4   rG   rG   z   s    G3%E"HGr3   rG   c                  N    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
<   y)AsyncObjectszContainer for all asyncio objects that Runtime manages.
    These cannot be initialized until the Runtime's eventloop is assigned.
    zasyncio.AbstractEventLoop	eventloopzasyncio.Event	must_stophas_connectionneed_send_datazasyncio.Future[None]startedstoppedN)r.   r/   r0   r1   rE   r2   r3   r4   rN   rN      s7    
 )(  "! "! "! "!r3   rN   c                     e Zd ZU dZded<   ed"d       Zed#d       Zd$dZe	d%d       Z
e	d&d       Ze	d'd	       Ze	d(d
       Ze	d)d       Ze	d*d       Ze	d+d       Ze	d,d       Zd-dZd.dZd/dZd/dZd0dZ	 	 d1	 	 	 	 	 	 	 	 	 d2dZ	 	 d1	 	 	 	 	 	 	 	 	 d2dZd.dZd.dZd3dZ	 	 	 	 	 	 d4dZe	d5d       Zd5dZd6dZd/dZ d7dZ!d/dZ"d8d Z#d/d!Z$y)9RuntimeNzRuntime | None	_instancec                H    | j                   t        d      | j                   S )znReturn the singleton Runtime instance. Raise an Error if the
        Runtime hasn't been created yet.
        zRuntime hasn't been created!)rW   RuntimeErrorclss    r4   instancezRuntime.instance   s$    
 == =>>}}r3   c                    | j                   duS )a2  True if the singleton Runtime instance has been created.

        When a Streamlit app is running in "raw mode" - that is, when the
        app is run via `python app.py` instead of `streamlit run app.py` -
        the Runtime will not exist, and various Streamlit functions need
        to adapt.
        N)rW   rZ   s    r4   existszRuntime.exists   s     }}D((r3   c                   t         j                  t        d      | t         _        d| _        d| _        |j
                  | _        |j                  | _        t        j                  | _        |j                  | _        t               | _        |j                   | _        t%        |j&                        | _        |j*                  | _        t/               | _         |j2                  |j4                  | j"                  | j0                  | j6                        | _        t;               | _        | j<                  j?                  tA                      | j<                  j?                  tC                      | j<                  j?                  | j                         | j<                  j?                  | j"                         | j<                  j?                  tE        | j8                               y)a   Create a Runtime instance. It won't be started yet.

        Runtime is *not* thread-safe. Its public methods are generally
        safe to call only on the same thread that its event loop runs on.

        Parameters
        ----------
        config
            Config options.
        Nz Runtime instance already exists!)storage)rB   r=   script_cachemessage_enqueued_callback)#rV   rW   rY   _async_objs_loop_coroutine_taskr9   _main_script_pathrD   	_is_hellorG   rH   _stater@   _component_registryr   _message_cacher=   _uploaded_file_mgrr   r<   _media_file_mgrr?   _cache_storage_managerr   _script_cacherA   rB   _enqueued_some_message_session_mgrr!   
_stats_mgrregister_providerr   r   r    )selfr
   s     r4   __init__zRuntime.__init__   sr    (ABB  15 @D!!'!3!3"** $*#<#< -/"(">">/8Q8QR&,&B&B#(]8F88"22"&"9"9++&*&A&A	
 '.))*G*IJ))*K*MN))$*=*=>))$*A*AB))*B4CTCT*UVr3   c                    | j                   S N)rg   rr   s    r4   statezRuntime.state   s    {{r3   c                    | j                   S ru   )rh   rv   s    r4   r@   zRuntime.component_registry   s    '''r3   c                    | j                   S ru   )ri   rv   s    r4   message_cachezRuntime.message_cache   s    """r3   c                    | j                   S ru   )rj   rv   s    r4   uploaded_file_mgrzRuntime.uploaded_file_mgr   s    &&&r3   c                    | j                   S ru   )rl   rv   s    r4   r?   zRuntime.cache_storage_manager   s    ***r3   c                    | j                   S ru   )rk   rv   s    r4   media_file_mgrzRuntime.media_file_mgr   s    ###r3   c                    | j                   S ru   )rp   rv   s    r4   	stats_mgrzRuntime.stats_mgr   s    r3   c                6    | j                         j                  S )z?A Future that completes when the Runtime's run loop has exited.)_get_async_objsrT   rv   s    r4   rT   zRuntime.stopped   s     ##%---r3   c                V    | j                   j                  |      }|y|j                  S )zGet the SessionClient for the given session_id, or None
        if no such session exists.

        Notes
        -----
        Threading: SAFE. May be called on any thread.
        N)ro   get_active_session_infoclientrr   
session_idsession_infos      r4   
get_clientzRuntime.get_client	  s/     ((@@L"""r3   c                t    | j                   j                  |      }||j                  j                          yy)zClear the user_info for the given session_id.

        Notes
        -----
        Threading: SAFE. May be called on any thread.
        N)ro   get_session_infosessionclear_user_infor   s      r4   clear_user_info_for_sessionz#Runtime.clear_user_info_for_session  s7     ((99*E#  002 $r3   c           	       K   t        t        j                         t        j                         t        j                         t        j                         t        j                         t        j                               }|| _        t        j                  | j                         d      | _        |j                   d{    y7 w)a  Start the runtime. This must be called only once, before
        any other functions are called.

        When this coroutine returns, Streamlit is ready to accept new sessions.

        Notes
        -----
        Threading: UNSAFE. Must be called on the eventloop thread.
        )rO   rP   rQ   rR   rS   rT   zRuntime.loop_coroutine)nameN)
rN   asyncioget_running_loopEventFuturerc   create_task_loop_coroutinerd   rS   rr   
async_objss     r4   startzRuntime.start!  s      "..0mmo"==?"==?NN$NN$

 &$+$7$7  ")A%
!     s   B>C CCc                j      j                          fd}j                  j                  |       y)zRequest that Streamlit close all sessions and stop running.
        Note that Streamlit won't stop running immediately.

        Notes
        -----
        Threading: SAFE. May be called from any thread.
        c                     j                   t        j                  t        j                  fv ry t        j                  d       j                  t        j                          j                  j                          y )NzRuntime stopping...)	rg   rG   rK   rL   r+   debug
_set_staterP   set)r   rr   s   r4   stop_on_eventloopz'Runtime.stop.<locals>.stop_on_eventloopI  sT    {{|44l6J6JKKMM/0OOL112  $$&r3   N)r   rO   call_soon_threadsafe)rr   r   r   s   ` @r4   stopzRuntime.stop>  s/     ))+
	' 	112CDr3   c                8    | j                   j                  |      S )zTrue if the session_id belongs to an active session.

        Notes
        -----
        Threading: SAFE. May be called on any thread.
        )ro   is_active_session)rr   r   s     r4   r   zRuntime.is_active_sessionS  s       22:>>r3   c                   |r	|rJ d       | j                   t        j                  t        j                  fv rt	        d| j                    d      | j
                  j                  |t        | j                  | j                        |||      }| j                  t        j                         | j                         j                  j                          |S )a  Create a new session (or connect to an existing one) and return its unique ID.

        Parameters
        ----------
        client
            A concrete SessionClient implementation for communicating with
            the session's client.
        user_info
            A dict that contains information about the session's user. For now,
            it only (optionally) contains the user's email address.

            {
                "email": "example@example.com"
            }
        existing_session_id
            The ID of an existing session to reconnect to. If one is not provided, a new
            session is created. Note that whether the Runtime's SessionManager supports
            reconnecting to an existing session depends on the SessionManager that this
            runtime is configured with.
        session_id_override
            The ID to assign to a new session being created with this method. Setting
            this can be useful when the service that a Streamlit Runtime is running in
            wants to tie the lifecycle of a Streamlit session to some other session-like
            object that it manages. Only one of existing_session_id and
            session_id_override should be set.

        Returns
        -------
        str
            The session's unique string ID.

        Notes
        -----
        Threading: UNSAFE. Must be called on the eventloop thread.
        zFOnly one of existing_session_id and session_id_override should be set!zCan't connect_session (state=))r   script_data	user_infoexisting_session_idsession_id_override)rg   rG   rK   rL   r-   ro   connect_sessionr   re   rf   r   rJ   r   rQ   r   )rr   r   r   r   r   r   s         r4   r   zRuntime.connect_session\  s    T (,? 	
T	
@ ;;<00,2F2FGG%(Edkk]RS&TUU&&66"4#9#94>>J 3 3 7 

 	CCD--113r3   c                V    t         j                  d       | j                  ||||      S )zCreate a new session (or connect to an existing one) and return its unique ID.

        Notes
        -----
        This method is simply an alias for connect_session added for backwards
        compatibility.
        z:create_session is deprecated! Use connect_session instead.)r   r   r   r   )r+   warningr   )rr   r   r   r   r   s        r4   create_sessionzRuntime.create_session  s5     	TU## 3 3	 $ 
 	
r3   c                    | j                   j                  |      }|r@| j                  j                  |j                         | j                   j                  |       | j                          y)a9  Close and completely shut down a session.

        This differs from disconnect_session in that it always completely shuts down a
        session, permanently losing any associated state (session state, uploaded files,
        etc.).

        This function may be called multiple times for the same session,
        which is not an error. (Subsequent calls just no-op.)

        Parameters
        ----------
        session_id
            The session's unique ID.

        Notes
        -----
        Threading: UNSAFE. Must be called on the eventloop thread.
        N)ro   r   ri   remove_refs_for_sessionr   close_session_on_session_disconnectedr   s      r4   r   zRuntime.close_session  sW    & ((99*E778L8LM++J7%%'r3   c                    | j                   j                  |      }|r@| j                  j                  |j                         | j                   j                  |       | j                          y)aZ  Disconnect a session. It will stop producing ForwardMsgs.

        Differs from close_session because disconnected sessions can be reconnected to
        for a brief window (depending on the SessionManager/SessionStorage
        implementations used by the runtime).

        This function may be called multiple times for the same session,
        which is not an error. (Subsequent calls just no-op.)

        Parameters
        ----------
        session_id
            The session's unique ID.

        Notes
        -----
        Threading: UNSAFE. Must be called on the eventloop thread.
        N)ro   r   ri   r   r   disconnect_sessionr   r   s      r4   r   zRuntime.disconnect_session  sY    & ((@@L 778L8LM00<%%'r3   c                ,   | j                   t        j                  t        j                  fv rt	        d| j                    d      | j
                  j                  |      }|t        j                  d|       y|j                  j                  |       y)a+  Send a BackMsg to an active session.

        Parameters
        ----------
        session_id
            The session's unique ID.
        msg
            The BackMsg to deliver to the session.

        Notes
        -----
        Threading: UNSAFE. Must be called on the eventloop thread.
        zCan't handle_backmsg (state=r   Nz3Discarding BackMsg for disconnected session (id=%s))rg   rG   rK   rL   r-   ro   r   r+   r   r   handle_backmsg)rr   r   msgr   s       r4   r   zRuntime.handle_backmsg  s     ;;<00,2F2FGG%(DT[[MQR&STT((@@LMMEz ++C0r3   c                ,   | j                   t        j                  t        j                  fv rt	        d| j                    d      | j
                  j                  |      }|t        j                  d|       y|j                  j                  |       y)a.  Handle an Exception raised during deserialization of a BackMsg.

        Parameters
        ----------
        session_id
            The session's unique ID.
        exc
            The Exception.

        Notes
        -----
        Threading: UNSAFE. Must be called on the eventloop thread.
        z6Can't handle_backmsg_deserialization_exception (state=r   Nz=Discarding BackMsg Exception for disconnected session (id=%s))rg   rG   rK   rL   r-   ro   r   r+   r   r   handle_backmsg_exception)rr   r   excr   s       r4   (handle_backmsg_deserialization_exceptionz0Runtime.handle_backmsg_deserialization_exception  s      ;;<00,2F2FGG%HUVW  ((@@LMMO 55c:r3   c                   K   | j                   t        j                  t        j                  t        j                  fvryyw)N)Tok)Funavailable)rg   rG   rH   rK   rL   rv   s    r4   is_ready_for_browser_connectionz'Runtime.is_ready_for_browser_connection!  s:     ;;  !!  
 

 #s   >A c                  K   t        t        | j                  | j                        | j                  | j
                  | j                  ddi      }	 |j                  d       t        j                         }t        |j                  vrlt        j                         |z
  t        k  rNt        j                  d       d{    t        |j                  vrt        j                         |z
  t        k  rNt        |j                  vr	 |j                          y|j                  t           }|rdnd}||f|j                          S 7 # |j                          w xY ww)	aJ  Load and execute the app's script to verify it runs without an error.

        Returns
        -------
        (True, "ok") if the script completes without error, or (False, err_msg)
        if the script raises an exception.

        Notes
        -----
        Threading: UNSAFE. Must be called on the eventloop thread.
        emailztest@example.com)r   r=   ra   rb   r   Ng?)Ftimeoutr   error)r   r   re   rf   rj   rm   rn   request_reruntimeperf_counterr   session_stater*   r   sleepshutdown)rr   r   nowr   r   s        r4   does_script_run_without_errorz%Runtime.does_script_run_without_error,  s-     "4#9#94>>J"&"9"9++&*&A&A 23
	!!$'##%C-W5J5JJ&&(3.2JJmmC((( .W5J5JJ&&(3.2JJ -G4I4II'  &&'DEB$'Cs7 ) sC   AEA-E ?E 4E 5E EE 5EE EEc                T    t         j                  d| j                  |       || _        y )NzRuntime state: %s -> %s)r+   r   rg   )rr   	new_states     r4   r   zRuntime._set_stateW  s    /iHr3   c                V  K   | j                         }	 | j                  t        j                  k(  r | j	                  t        j
                         n6| j                  t        j                  k(  rnt        d| j                         |j                  j                  d       |j                  j                         s>| j                  t        j
                  k(  rt        j                  t        j                  |j                  j                               t        j                  |j                  j                               ft        j                          d{   \  }}|D ]  }|j#                           n| j                  t        j                  k(  r|j$                  j'                          | j(                  j+                         D ]S  }|j,                  j/                         }|D ]2  }	 | j1                  ||       t        j8                  d       d{    4 U t        j8                  d       d{    nnt        j                  t        j                  |j                  j                               t        j                  |j$                  j                               ft        j                          d{   \  }}|D ]  }|j#                           |j                  j                         s>| j(                  j;                         D ]1  }| j(                  j=                  |j,                  j6                         3 | j	                  t        j>                         |j@                  j                  d       y7 *# t2        $ r3 | j(                  j5                  |j,                  j6                         Y w xY w7 7 7 # tB        $ rN}	|j@                  jE                  |	       tG        jH                          tJ        jM                  d       Y d}	~	yd}	~	ww xY ww)zThe main Runtime loop.

        This function won't exit until `stop` is called.

        Notes
        -----
        Threading: UNSAFE. Must be called on the eventloop thread.
        zBad Runtime state at start: N)return_whenr   g{Gz?zJ
Please report this bug at https://github.com/streamlit/streamlit/issues.
)'r   rg   rG   rH   r   rI   rJ   rY   rS   
set_resultrP   is_setr   waitr   rQ   FIRST_COMPLETEDcancelrR   clearro   list_active_sessionsr   flush_browser_queue_send_messager   r   idr   list_sessionsr   rL   rT   	Exceptionset_exception	traceback	print_excr+   info)
rr   r   _pending_taskstaskactive_session_infomsg_listr   r   es
             r4   r   zRuntime._loop_coroutine[  sG     ))+
R	{{l222 B BC K KK"%A$++#OPP ))$/ **113;;,"D"DD
 .5\\#//
0D0D0I0I0KL#//
0I0I0N0N0PQ %,$;$;. ($A} !. !.[[L$O$OO--335/3/@/@/U/U/W+#6#>#>#R#R#T#+C" $ 2 23F L #*--"222 $, 0X "-----  *1++J,@,@,E,E,GH++J,E,E,J,J,LM !( 7 7* $ = *DKKM *g !**113n !% 1 1 ? ? A !!//0D0D0G0GH	 !B OOL001))$/q($ $B " $ 1 1 D D$7$?$?$B$B!"" 3 .$0  	,,Q/!LL 	s   P)EO NBO .N O O O 9O	:BO  O8O ;BO P)O 8O?O OO 	O O 	P&AP!P)!P&&P)c                   t        |      |j                  _        |}|j                  j                  rt        |       | j                  j                  ||j                  |j                        r+t        j                  d|j                         t        |      }t        j                  d|j                         | j                  j                  ||j                  |j                         |j                  d      dk(  r|j                  t        j                   k(  s2t#        j$                  d      r|j                  t        j&                  k(  rnt        j                  dt#        j$                  d             |xj                  dz  c_        | j                  j)                  |j                  |j                         |j*                  j-                  |       y	)
a  Send a message to a client.

        If the client is likely to have already cached the message, we may
        instead send a "reference" message that contains only the hash of the
        message.

        Parameters
        ----------
        session_info : ActiveSessionInfo
            The ActiveSessionInfo associated with websocket
        msg : ForwardMsg
            The message to send to the client

        Notes
        -----
        Threading: UNSAFE. Must be called on the eventloop thread.
        z$Sending cached message ref (hash=%s)zCaching message (hash=%s)typescript_finishedz4global.includeFragmentRunsInForwardMessageCacheCountzYScript run finished successfully; removing expired entries from MessageCache (max_age=%s)zglobal.maxCachedMessageAge   N)r   metadata	cacheabler   ri   has_message_referencer   script_run_countr+   r   hashr   add_message
WhichOneofr   r   FINISHED_SUCCESSFULLYr
   
get_option"FINISHED_FRAGMENT_RUN_SUCCESSFULLY"remove_expired_entries_for_sessionr   write_forward_msg)rr   r   r   msg_to_sends       r4   r   zRuntime._send_message  sr   $ "2#!6<<!!#C(""88\))<+H+H
 DchhO237
 MM5sxx@++\))<+H+H >>&!%66:#C#CC!!J '':+X+XX MM !!">?	 ))Q.)BB$$l&C&C
 	--k:r3   c                    | j                         }|j                  j                  |j                  j                         y)a  Callback called by AppSession after the AppSession has enqueued a
        message. Sets the "needs_send_data" event, which causes our core
        loop to wake up and flush client message queues.

        Notes
        -----
        Threading: SAFE. May be called on any thread.
        N)r   rO   r   rR   r   r   s     r4   rn   zRuntime._enqueued_some_message  s2     ))+
11*2K2K2O2OPr3   c                H    | j                   t        d      | j                   S )zpReturn our AsyncObjects instance. If the Runtime hasn't been
        started, this will raise an error.
        zRuntime hasn't started yet!)rc   rY   rv   s    r4   r   zRuntime._get_async_objs  s(     #<==r3   c                
   | j                   t        j                  k(  rf| j                  j	                         dk(  rH| j                         j                  j                          | j                  t        j                         yyy)zlSet the runtime state to NO_SESSIONS_CONNECTED if the last active
        session was disconnected.
        r   N)
rg   rG   rJ   ro   num_active_sessionsr   rQ   r   r   rI   rv   s    r4   r   z Runtime._on_session_disconnected  se    
 KK<FFF!!5571<  "11779OOL>>? = Gr3   )returnrV   )r   rC   )r
   r7   )r   rG   )r   r$   )r   r   )r   r(   )r   r&   )r   r   )r   r!   )r   zAwaitable[None])r   r8   r   zSessionClient | None)r   r8   r   None)r   r   )r   r8   r   rC   )NN)
r   r   r   zdict[str, str | bool | None]r   r:   r   r:   r   r8   )r   r8   r   r%   r   r   )r   r8   r   BaseExceptionr   r   )r   ztuple[bool, str])r   rG   r   r   )r   r   r   r   r   r   )r   rN   )%r.   r/   r0   rW   rE   classmethodr\   r^   rs   propertyrw   r@   rz   r|   r?   r   r   rT   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rn   r   r   r2   r3   r4   rV   rV      s    $I~$  ) )/Wb   ( ( # # ' ' + + $ $   . .#	3!:E*? +/*.;; 0; (	;
 (; 
;B +/*.

 0
 (	

 (
 

,(2(@14;;$1;	;> $ $)V ^@>;@
Q 	@r3   rV   )N
__future__r   r   r   r   dataclassesr   r   enumr   typingr   r   r	   	streamlitr
   1streamlit.components.lib.local_component_registryr   streamlit.loggerr   streamlit.proto.ForwardMsg_pb2r   streamlit.runtime.app_sessionr   streamlit.runtime.cachingr   r   :streamlit.runtime.caching.storage.local_disk_cache_storager   #streamlit.runtime.forward_msg_cacher   r   r   $streamlit.runtime.media_file_managerr   (streamlit.runtime.memory_session_storager   streamlit.runtime.runtime_utilr   streamlit.runtime.script_datar   +streamlit.runtime.scriptrunner.script_cacher   !streamlit.runtime.session_managerr   r   r   r   r   streamlit.runtime.stater   r    streamlit.runtime.statsr!   +streamlit.runtime.websocket_session_managerr"   collections.abcr#   2streamlit.components.types.base_component_registryr$   streamlit.proto.BackMsg_pb2r%   !streamlit.runtime.caching.storager&   $streamlit.runtime.media_file_storager'   'streamlit.runtime.uploaded_file_managerr(   r*   rE   r.   r+   r   r-   r7   rG   rN   rV   r2   r3   r4   <module>r     s    #    (  3 3  T ' 5 4 
 B I ; 4 C  1 O)X3EEK #% % $H% %F) F $! ! !T4 ": "0~	@ ~	@r3   