
    /_ip                    T   U d dl mZ d dl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 d dl m!Z! d dl"m#Z# d dl$m%Z% d dl&m'Z'm(Z(m)Z)m*Z*m+Z+ d dl,m-Z-m.Z. d dl/m0Z0 d dl1m2Z2 er$d dl3m4Z4 d dl5m6Z6 d dl7m8Z8 d dl9m:Z: d dl;m<Z< d dl=m>Z> dZ?de@d<   ej                  dk(  rdndZBde@d <    eeC      ZDde@d!<    G d" d#eE      ZF ed$%       G d& d'             ZG G d( d)e
      ZH G d* d+e      ZI G d, d-      ZJy).    )annotationsN)	dataclassfield)Enum)TYPE_CHECKINGFinal
NamedTuple)LocalComponentRegistry)BidiComponentManager)
get_logger)
ForwardMsg)
AppSession)get_data_cache_stats_provider!get_resource_cache_stats_provider)LocalDiskCacheStorageManager)MediaFileManager)MemorySessionStorage)
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win32g      ?_SIGNAL_CHECK_INTERVAL_LOGGERc                      e Zd ZdZy)RuntimeStoppedErrorz;Raised by operations on a Runtime instance that is stopped.N)__name__
__module____qualname____doc__     X/var/www/html/land_sniper/venv/lib/python3.12/site-packages/streamlit/runtime/runtime.pyr+   r+   J   s    Er1   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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_registryr   bidi_component_registryztype[SessionManager]session_manager_classr   session_storageFboolis_helloN)r,   r-   r.   r/   __annotations__r   r   r=   r
   r>   r   r?   r   r@   r   rA   rC   r0   r1   r2   r5   r5   N   s    .   )( /. 2742. 
 16.1- 
 5:,51 
 3J/I ',<P&QO^Q Hdr1   r5   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-   r.   rG   rH   rI   rJ   rK   r0   r1   r2   rF   rF   ~   s    G3%E"HGr1   rF   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-   r.   r/   rD   r0   r1   r2   rM   rM      s7    
 )(  "! "! "! "!r1   rM   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!)rV   RuntimeErrorclss    r2   instancezRuntime.instance   s$    
 == =>>}}r1   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)rV   rY   s    r2   existszRuntime.exists   s     }}D((r1   c                   t         j                  t        d      | t         _        d| _        d| _        |j
                  | _        |j                  | _        t        j                  | _        |j                  | _        |j                  | _        |j                   | _        t%        |j&                        | _        |j*                  | _        t/               | _        | j                  j3                          |j5                  |j6                  | j"                  | j0                  | j8                        | _        t=               | _        | j>                  jA                  tC                      | j>                  jA                  tE                      | j>                  jA                  | j"                         | j>                  jA                  tG        | j:                               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)rA   r;   script_cachemessage_enqueued_callback)$rU   rV   rX   _async_objs_loop_coroutine_taskr7   _main_script_pathrC   	_is_hellorF   rG   _stater>   _component_registryr?   _bidi_component_registryr;   _uploaded_file_mgrr   r:   _media_file_mgrr=   _cache_storage_managerr   _script_cache discover_and_register_componentsr@   rA   _enqueued_some_message_session_mgrr   
_stats_mgrregister_providerr   r   r   )selfconfigs     r2   __init__zRuntime.__init__   st    (ABB  15 @D!!'!3!3"** $*#<#< (.(F(F%"(">">/8Q8QR&,&B&B#(] 	%%FFH"88"22"&"9"9++&*&A&A	 9 
 '.))*G*IJ))*K*MN))$*A*AB))*B4CTCT*UVr1   c                    | j                   S N)rf   rr   s    r2   statezRuntime.state   s    {{r1   c                    | j                   S rv   )rg   rw   s    r2   r>   zRuntime.component_registry   s    '''r1   c                    | j                   S rv   )rh   rw   s    r2   r?   zRuntime.bidi_component_registry   s    ,,,r1   c                    | j                   S rv   )ri   rw   s    r2   uploaded_file_mgrzRuntime.uploaded_file_mgr   s    &&&r1   c                    | j                   S rv   )rk   rw   s    r2   r=   zRuntime.cache_storage_manager   s    ***r1   c                    | j                   S rv   )rj   rw   s    r2   media_file_mgrzRuntime.media_file_mgr   s    ###r1   c                    | j                   S rv   )rp   rw   s    r2   	stats_mgrzRuntime.stats_mgr   s    r1   c                6    | j                         j                  S )z?A Future that completes when the Runtime's run loop has exited.)_get_async_objsrS   rw   s    r2   rS   zRuntime.stopped  s     ##%---r1   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      r2   
get_clientzRuntime.get_client  s/     ((@@L"""r1   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      r2   clear_user_info_for_sessionz#Runtime.clear_user_info_for_session  s7     ((99*E#  002 $r1   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.
        )rN   rO   rP   rQ   rR   rS   zRuntime.loop_coroutine)nameN)
rM   asyncioget_running_loopEventFuturerb   create_task_loop_coroutinerc   rR   rr   
async_objss     r2   startzRuntime.start'  s      "..0mmo"==?"==?NN$NN$

 &$+$7$7  ")A%
!     s   B>C CCc                l      j                         d 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...)	rf   rF   rJ   rK   r)   debug
_set_staterO   set)r   rr   s   r2   stop_on_eventloopz'Runtime.stop.<locals>.stop_on_eventloopO  sT    {{|44l6J6JKKMM/0OOL112  $$&r1   NreturnNone)r   rN   call_soon_threadsafe)rr   r   r   s   ` @r2   stopzRuntime.stopD  s/     ))+
	' 	112CDr1   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     r2   r   zRuntime.is_active_sessionY  s       22:>>r1   c                   |r|rt        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.
        z`Only one of existing_session_id and session_id_override should be set. This should never happen.zCan't connect_session (state=))r   script_data	user_infoexisting_session_idsession_id_override)rX   rf   rF   rJ   rK   r+   ro   connect_sessionr   rd   re   r   rI   r   rP   r   )rr   r   r   r   r   r   s         r2   r   zRuntime.connect_sessionb  s    T #6, 
 ;;<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r1   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        r2   create_sessionzRuntime.create_session  s5     	TU## 3 3	 $ 
 	
r1   c                    | j                   j                  |      }|r| 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   close_session_on_session_disconnectedr   s      r2   r   zRuntime.close_session  s=    & ((99*E++J7%%'r1   c                    | j                   j                  |      }|r| 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   disconnect_sessionr   r   s      r2   r   zRuntime.disconnect_session  s=    & ((@@L00<%%'r1   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))rf   rF   rJ   rK   r+   ro   r   r)   r   r   handle_backmsg)rr   r   msgr   s       r2   r   zRuntime.handle_backmsg  s     ;;<00,2F2FGG%(DT[[MQR&STT((@@LMMEz ++C0r1   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))rf   rF   rJ   rK   r+   ro   r   r)   r   r   handle_backmsg_exception)rr   r   excr   s       r2   (handle_backmsg_deserialization_exceptionz0Runtime.handle_backmsg_deserialization_exception  s      ;;<00,2F2FGG%HUVW  ((@@LMMO 55c:r1   c                   K   | j                   t        j                  t        j                  t        j                  fvryyw)N)Tok)Funavailable)rf   rF   rG   rJ   rK   rw   s    r2   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;   r`   ra   r   Ng?)Ftimeoutr   error)r   r   rd   re   ri   rl   rn   request_reruntimeperf_counterr   session_stater&   r   sleepshutdown)rr   r   nowr   r   s        r2   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   rf   )rr   	new_states     r2   r   zRuntime._set_stateV  s    /iHr1   c                  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                         sZ| j                  t        j
                  k(  rt        j                  t        j                  |j                  j                               t        j                  |j                  j                               ft        j                   t"               d{   \  }}|D ]  }|j%                           |st"        ǌ| j                  t        j                  k(  r|j&                  j)                          | j*                  j-                         D ]S  }|j.                  j1                         }|D ]2  }	 | j3                  ||       t        j:                  d       d{    4 U t        j:                  d       d{    nnt        j                  t        j                  |j                  j                               t        j                  |j&                  j                               ft        j                   t"               d{   \  }}|D ]  }|j%                           |st"        Y|j                  j                         sZ| j*                  j=                         D ]1  }| j*                  j?                  |j.                  j8                         3 | j	                  t        j@                         |jB                  j                  d       y7 A# t4        $ r3 | j*                  j7                  |j.                  j8                         Y w xY w7 7 7 # tD        $ rN}	|jB                  jG                  |	       tI        jJ                          tL        jO                  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   r   g{Gz?zJ
Please report this bug at https://github.com/streamlit/streamlit/issues.
)(r   rf   rF   rG   r   rH   rI   rX   rR   
set_resultrO   is_setr   waitr   rP   FIRST_COMPLETEDr(   cancelrQ   clearro   list_active_sessionsr   flush_browser_queue_send_messager   r   idr   list_sessionsr   rK   rS   	Exceptionset_exception	traceback	print_excr)   info)
rr   r   
done_taskspending_taskstaskactive_session_infomsg_listr   r   es
             r2   r   zRuntime._loop_coroutineZ  s     ))+
^	{{l222 B BC K KK"%A$++#OPP ))$/ **113;;,"D"DD
 7>ll#//
0D0D0I0I0KL#//
0I0I0N0N0PQ %,$;$; 67 1-J !. && &*@*L [[L$O$OO--335/3/@/@/U/U/W 3+#6#>#>#R#R#T#+ 	3C" $ 2 23F L #*--"222	33 "-----  3:,,++J,@,@,E,E,GH++J,E,E,J,J,LM !( 7 723 -)
M * "DKKM" "&<&HA !**113F !% 1 1 ? ? A I !!//0D0D0G0GH	I OOL001))$/I10 $B " $ 1 1 D D$7$?$?$B$B!"" 3 .-<  	,,Q/!LL 	s   QEO+ N  BO+ ;N#O+ %O"& O+ O%BO+ O(AO+ BO+ Q O+ #8OO+ OO+ %O+ (O+ +	Q4AP=8Q=QQc                    |j                  d      dk(  r2|j                  t        j                  k(  r|xj                  dz  c_        |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.
        typescript_finished   N)
WhichOneofr   r   FINISHED_SUCCESSFULLYscript_run_countr   write_forward_msg)rr   r   r   s      r2   r   zRuntime._send_message  sQ    ( >>&!%66:#C#CC))Q.) 	--c2r1   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   rN   r   rQ   r   r   s     r2   rn   zRuntime._enqueued_some_message  s2     ))+
11*2K2K2O2OPr1   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!)rb   rX   rw   s    r2   r   zRuntime._get_async_objs  s(     #<==r1   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)
rf   rF   rI   ro   num_active_sessionsr   rP   r   r   rH   rw   s    r2   r   z Runtime._on_session_disconnected  se    
 KK<FFF!!5571<  "11779OOL>>? = Gr1   )r   rU   )r   rB   )rs   r5   r   r   )r   rF   )r   r    )r   r   )r   r$   )r   r"   )r   r   )r   r   )r   zAwaitable[None])r   r6   r   zSessionClient | None)r   r6   r   r   r   )r   r6   r   rB   )NN)
r   r   r   zdict[str, str | bool | None]r   r8   r   r8   r   r6   )r   r6   r   r!   r   r   )r   r6   r   BaseExceptionr   r   )r   ztuple[bool, str])r   rF   r   r   )r   r   r   r   r   r   )r   rM   )%r,   r-   r.   rV   rD   classmethodr[   r]   rt   propertyrx   r>   r?   r|   r=   r   r   rS   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rn   r   r   r0   r1   r2   rU   rU      s    $I~$  ) )1Wf   ( ( - - ' ' + + $ $   . .#	3!:E*? +/*.== 0= (	=
 (= 
=F +/*.

 0
 (	

 (
 

,(0(014;;$1;	;> $ $)V jX38
Q 	@r1   rU   )K
__future__r   r   sysr   r   dataclassesr   r   enumr   typingr   r   r	   1streamlit.components.lib.local_component_registryr
   )streamlit.components.v2.component_managerr   streamlit.loggerr   streamlit.proto.ForwardMsg_pb2r   streamlit.runtime.app_sessionr   streamlit.runtime.cachingr   r   :streamlit.runtime.caching.storage.local_disk_cache_storager   $streamlit.runtime.media_file_managerr   (streamlit.runtime.memory_session_storager   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&   rD   platformr(   r,   r)   r   r+   r5   rF   rM   rU   r0   r1   r2   <module>r     s    #  
   (  3 3 T J ' 5 4 B I 4 C  1 O)X3EEK #% % $ (+||w'>D  HH% %F) F $& & &^4 ": "0a	@ a	@r1   