o
    ,&]ip                     @  s  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rd 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jAdkrdndZBde@d < eeCZDde@d!< G d"d# d#eEZFed$d%G d&d' d'ZGG d(d) d)e
ZHG d*d+ d+eZIG d,d- d-ZJdS ).    )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                   @  s   e Zd ZdZdS )RuntimeStoppedErrorz;Raised by operations on a Runtime instance that is stopped.N)__name__
__module____qualname____doc__ r.   r.   W/var/www/html/IGF-ODF-V3/venv/lib/python3.10/site-packages/streamlit/runtime/runtime.pyr)   J   s    r)   T)frozenc                   @  s   e Zd ZU dZded< ded< ded< ded	< eed
Zded< eed
Z	ded< ee
d
Zded< eZded< eed
Zded< dZded< dS )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   r9   r	   r:   r
   r;   r   r<   r   r=   r?   r.   r.   r.   r/   r1   N   s$   
 r1   c                   @  s    e Zd ZdZdZdZdZdZdS )RuntimeStateINITIALNO_SESSIONS_CONNECTEDONE_OR_MORE_SESSIONS_CONNECTEDSTOPPINGSTOPPEDN)r*   r+   r,   rB   rC   rD   rE   rF   r.   r.   r.   r/   rA   ~   s    rA   c                   @  sB   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
< dS )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-   r@   r.   r.   r.   r/   rG      s   
 rG   c                   @  s~  e Zd ZU dZded< edaddZedbdd	ZdcddZe	ddddZ
e	deddZe	dfddZe	dgddZe	dhddZe	didd Ze	djd"d#Ze	dkd%d&Zdld*d+Zdmd,d-Zdnd.d/Zdnd0d1Zdod2d3Z		dpdqd;d<Z		dpdqd=d>Zdmd?d@ZdmdAdBZdrdEdFZdsdIdJZe	dtdLdMZdtdNdOZdudQdRZdndSdTZ dvdXdYZ!dndZd[Z"dwd]d^Z#dnd_d`Z$dS )xRuntimeNzRuntime | None	_instancereturnc                 C     | j du r	td| j S )znReturn the singleton Runtime instance. Raise an Error if the
        Runtime hasn't been created yet.
        NzRuntime hasn't been created!)rO   RuntimeErrorclsr.   r.   r/   instance   s   
zRuntime.instancer>   c                 C  s
   | 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)rO   rS   r.   r.   r/   exists   s   
	zRuntime.existsconfigr1   Nonec                 C  s   t jdur	td| t _d| _d| _|j| _|j| _t	j
| _|j| _|j| _|j| _t|jd| _|j| _t | _| j  |j|j| j| j| jd| _t | _| j t!  | j t"  | j | j | j t#| j dS )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)r=   r7   script_cachemessage_enqueued_callback)$rN   rO   rR   _async_objs_loop_coroutine_taskr3   _main_script_pathr?   	_is_hellorA   rB   _stater:   _component_registryr;   _bidi_component_registryr7   _uploaded_file_mgrr   r6   _media_file_mgrr9   _cache_storage_managerr   _script_cache discover_and_register_componentsr<   r=   _enqueued_some_message_session_mgrr   
_stats_mgrregister_providerr   r   r   )selfrW   r.   r.   r/   __init__   s4   

zRuntime.__init__rA   c                 C     | j S N)r`   rl   r.   r.   r/   state      zRuntime.stater   c                 C  rn   ro   )ra   rp   r.   r.   r/   r:      rr   zRuntime.component_registryr
   c                 C  rn   ro   )rb   rp   r.   r.   r/   r;      rr   zRuntime.bidi_component_registryr#   c                 C  rn   ro   )rc   rp   r.   r.   r/   uploaded_file_mgr   rr   zRuntime.uploaded_file_mgrr!   c                 C  rn   ro   )re   rp   r.   r.   r/   r9      rr   zRuntime.cache_storage_managerr   c                 C  rn   ro   )rd   rp   r.   r.   r/   media_file_mgr   rr   zRuntime.media_file_mgrr   c                 C  rn   ro   )rj   rp   r.   r.   r/   	stats_mgr   rr   zRuntime.stats_mgrAwaitable[None]c                 C  s
   |   jS )z?A Future that completes when the Runtime's run loop has exited.)_get_async_objsrM   rp   r.   r.   r/   rM     s   
zRuntime.stopped
session_idr2   SessionClient | Nonec                 C  s   | j |}|du rdS |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)ri   get_active_session_infoclientrl   rx   session_infor.   r.   r/   
get_client  s   zRuntime.get_clientc                 C  s&   | j |}|dur|j  dS dS )zClear the user_info for the given session_id.

        Notes
        -----
        Threading: SAFE. May be called on any thread.
        N)ri   get_session_infosessionclear_user_infor|   r.   r.   r/   clear_user_info_for_session  s   z#Runtime.clear_user_info_for_sessionc                   sX   t t t t t t t d}|| _tj|  dd| _|j	I dH  dS )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.
        )rH   rI   rJ   rK   rL   rM   zRuntime.loop_coroutine)nameN)
rG   asyncioget_running_loopEventFuturer\   create_task_loop_coroutiner]   rL   rl   
async_objsr.   r.   r/   start'  s   zRuntime.startc                   s(      d fdd} j| dS )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.
        rP   rX   c                     s:   j tjtjfv rd S td tj  j  d S )NzRuntime stopping...)	r`   rA   rE   rF   r(   debug
_set_staterI   setr.   r   rl   r.   r/   stop_on_eventloopO  s
   
z'Runtime.stop.<locals>.stop_on_eventloopNrP   rX   )rw   rH   call_soon_threadsafe)rl   r   r.   r   r/   stopD  s   	zRuntime.stopc                 C  s   | j |S )zTrue if the session_id belongs to an active session.

        Notes
        -----
        Threading: SAFE. May be called on any thread.
        )ri   is_active_session)rl   rx   r.   r.   r/   r   Y  s   zRuntime.is_active_sessionr{   r   	user_infodict[str, str | bool | None]existing_session_idr4   session_id_overridec                 C  sr   |r|rt d| jtjtjfv rtd| j d| jj|t| j	| j
|||d}| t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_datar   r   r   )rR   r`   rA   rE   rF   r)   ri   connect_sessionr   r^   r_   r   rD   rw   rJ   r   )rl   r{   r   r   r   rx   r.   r.   r/   r   b  s    *zRuntime.connect_sessionc                 C  s   t d | j||||d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   )rl   r{   r   r   r   r.   r.   r/   create_session  s   
zRuntime.create_sessionc                 C  (   | j |}|r| j | |   dS )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)ri   r   close_session_on_session_disconnectedr|   r.   r.   r/   r        zRuntime.close_sessionc                 C  r   )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)ri   rz   disconnect_sessionr   r|   r.   r.   r/   r     r   zRuntime.disconnect_sessionmsgr    c                 C  X   | j tjtjfv rtd| j  d| j|}|du r$td| dS |j	
| dS )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))r`   rA   rE   rF   r)   ri   rz   r(   r   r   handle_backmsg)rl   rx   r   r}   r.   r.   r/   r     s   zRuntime.handle_backmsgexcBaseExceptionc                 C  r   )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))r`   rA   rE   rF   r)   ri   rz   r(   r   r   handle_backmsg_exception)rl   rx   r   r}   r.   r.   r/   (handle_backmsg_deserialization_exception  s   z0Runtime.handle_backmsg_deserialization_exceptiontuple[bool, str]c                   s    | j tjtjtjfvrdS dS )N)Tok)Funavailable)r`   rA   rB   rE   rF   rp   r.   r.   r/   is_ready_for_browser_connection   s   z'Runtime.is_ready_for_browser_connectionc                   s   t t| j| j| j| j| jddid}zK|d t	 }t
|jvr@t	 | tk r@tdI dH  t
|jvr@t	 | tk s+t
|jvrLW |  dS |jt
 }|rUdnd}||fW |  S |  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   r7   rZ   r[   r   Ng?)Ftimeoutr   error)r   r   r^   r_   rc   rf   rh   request_reruntimeperf_counterr   session_stater%   r   sleepshutdown)rl   r   nowr   r   r.   r.   r/   does_script_run_without_error+  s.   




z%Runtime.does_script_run_without_error	new_statec                 C  s   t d| j| || _d S )NzRuntime state: %s -> %s)r(   r   r`   )rl   r   r.   r.   r/   r   V  s   
zRuntime._set_statec           
   
     s8  |   }z| jtjkr| tj n| jtjkrntd| j |j	d |j
 s| jtjkr`tjt|j
 t|j ftjtdI dH \}}|D ]}|  qQ|s_tdur_q(nI| jtjkr|j  | j D ].}|j }|D ]$}z| || W n ty   | j|jj Y nw tdI dH  qyqptdI dH  nn1tjt|j
 t|j ftjtdI dH \}}|D ]}|  q|stdurq(|j
 r-| j D ]
}| j|jj q| tj  |j!	d W dS  t"y }	 z|j!#|	 t$%  t&'d W Y d}	~	dS d}	~	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.
)(rw   r`   rA   rB   r   rC   rD   rR   rL   
set_resultrI   is_setr   waitr   rJ   FIRST_COMPLETEDr'   cancelrK   clearri   list_active_sessionsr   flush_browser_queue_send_messager   r   idr   list_sessionsr   rF   rM   	Exceptionset_exception	traceback	print_excr(   info)
rl   r   
done_taskspending_taskstaskactive_session_infomsg_listr   r}   er.   r.   r/   r   Z  s~   







CzRuntime._loop_coroutiner}   r   r   c                 C  s8   | ddkr|jtjkr| jd7  _|j| dS )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)rl   r}   r   r.   r.   r/   r     s   zRuntime._send_messagec                 C  s   |   }|j|jj dS )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)rw   rH   r   rK   r   r   r.   r.   r/   rh     s   	zRuntime._enqueued_some_messagerG   c                 C  rQ   )zpReturn our AsyncObjects instance. If the Runtime hasn't been
        started, this will raise an error.
        NzRuntime hasn't started yet!)r\   rR   rp   r.   r.   r/   rw     s   
zRuntime._get_async_objsc                 C  s@   | j tjkr| j dkr|  j  | tj	 dS dS dS )zlSet the runtime state to NO_SESSIONS_CONNECTED if the last active
        session was disconnected.
        r   N)
r`   rA   rD   ri   num_active_sessionsrw   rJ   r   r   rC   rp   r.   r.   r/   r     s   z Runtime._on_session_disconnected)rP   rN   )rP   r>   )rW   r1   rP   rX   )rP   rA   )rP   r   )rP   r
   )rP   r#   )rP   r!   )rP   r   )rP   r   )rP   rv   )rx   r2   rP   ry   )rx   r2   rP   rX   r   )rx   r2   rP   r>   )NN)
r{   r   r   r   r   r4   r   r4   rP   r2   )rx   r2   r   r    rP   rX   )rx   r2   r   r   rP   rX   )rP   r   )r   rA   rP   rX   )r}   r   r   r   rP   rX   )rP   rG   )%r*   r+   r,   rO   r@   classmethodrU   rV   rm   propertyrq   r:   r;   rs   r9   rt   ru   rM   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rh   rw   r   r.   r.   r.   r/   rN      s^   
 

3





C






+

l

rN   )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%   r@   platformr'   r*   r(   r   r)   r1   rA   rG   rN   r.   r.   r.   r/   <module>   sN   /