o
    Zhn                     @  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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-m.Z. d dl/m0Z0 erd dl1m2Z2 d dl3m4Z4 d dl5m6Z6 d dl7m8Z8 d dl9m:Z: d dl;m<Z< dZ=de>d< ej?dkrdndZ@de>d< eeAZBde>d < G d!d" d"eCZDed#d$G d%d& d&ZEG d'd( d(e
ZFG d)d* d*eZGG d+d, d,ZHdS )-    )annotationsN)	dataclassfield)Enum)TYPE_CHECKINGFinal
NamedTuple)LocalComponentRegistry)
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-   Z/var/www/html/Persson_Maskin/env/lib/python3.10/site-packages/streamlit/runtime/runtime.pyr(   I   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
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_registryztype[SessionManager]session_manager_classr   session_storageFboolis_helloN)r)   r*   r+   r,   __annotations__r   r   r8   r	   r9   r   r:   r   r;   r=   r-   r-   r-   r.   r0   M   s   
 r0   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+   r@   rA   rB   rC   rD   r-   r-   r-   r.   r?   x   s    r?   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.   rE      s   
 rE   c                   @  sp  e Zd ZU dZded< ed^ddZed_dd	Zd`ddZe	daddZ
e	dbddZe	dcddZe	ddddZe	deddZe	dfdd Ze	dgd"d#Zdhd'd(Zdid)d*Zdjd+d,Zdjd-d.Zdkd/d0Z		dldmd8d9Z		dldmd:d;Zdid<d=Zdid>d?ZdndBdCZdodFdGZe	dpdIdJZdpdKdLZdqdNdOZdjdPdQZdrdUdVZ djdWdXZ!dsdZd[Z"djd\d]Z#dS )t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!)rM   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)rM   rQ   r-   r-   r.   exists   s   
	zRuntime.existsconfigr0   Nonec                 C  s   t jdur	td| t _d| _d| _|j| _|j| _t	j
| _|j| _|j| _t|jd| _|j| _t | _|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;   r6   script_cachemessage_enqueued_callback)!rL   rM   rP   _async_objs_loop_coroutine_taskr2   _main_script_pathr=   	_is_hellor?   r@   _stater9   _component_registryr6   _uploaded_file_mgrr   r5   _media_file_mgrr8   _cache_storage_managerr   _script_cacher:   r;   _enqueued_some_message_session_mgrr   
_stats_mgrregister_providerr   r   r   )selfrU   r-   r-   r.   __init__   s0   
zRuntime.__init__r?   c                 C     | j S N)r^   rh   r-   r-   r.   state      zRuntime.stater   c                 C  rj   rk   )r_   rl   r-   r-   r.   r9      rn   zRuntime.component_registryr"   c                 C  rj   rk   )r`   rl   r-   r-   r.   uploaded_file_mgr   rn   zRuntime.uploaded_file_mgrr    c                 C  rj   rk   )rb   rl   r-   r-   r.   r8      rn   zRuntime.cache_storage_managerr   c                 C  rj   rk   )ra   rl   r-   r-   r.   media_file_mgr   rn   zRuntime.media_file_mgrr   c                 C  rj   rk   )rf   rl   r-   r-   r.   	stats_mgr   rn   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_objsrK   rl   r-   r-   r.   rK      s   
zRuntime.stopped
session_idr1   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)re   get_active_session_infoclientrh   rt   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)re   get_session_infosessionclear_user_inforx   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.
        )rF   rG   rH   rI   rJ   rK   zRuntime.loop_coroutine)nameN)
rE   asyncioget_running_loopEventFuturerZ   create_task_loop_coroutiner[   rJ   rh   
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.
        rN   rV   c                     s:   j tjtjfv rd S td tj  j  d S )NzRuntime stopping...)	r^   r?   rC   rD   r'   debug
_set_staterG   setr-   r   rh   r-   r.   stop_on_eventloopA  s
   
z'Runtime.stop.<locals>.stop_on_eventloopNrN   rV   )rs   rF   call_soon_threadsafe)rh   r   r-   r   r.   stop6  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.
        )re   is_active_session)rh   rt   r-   r-   r.   r   K  s   zRuntime.is_active_sessionrw   r   	user_infodict[str, str | bool | None]existing_session_idr3   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=))rw   script_datar   r   r   )rP   r^   r?   rC   rD   r(   re   connect_sessionr   r\   r]   r   rB   rs   rH   r   )rh   rw   r   r   r   rt   r-   r-   r.   r   T  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.)rw   r   r   r   )r'   warningr   )rh   rw   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)re   r{   close_session_on_session_disconnectedrx   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)re   rv   disconnect_sessionr   rx   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^   r?   rC   rD   r(   re   rv   r'   r   r|   handle_backmsg)rh   rt   r   ry   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^   r?   rC   rD   r(   re   rv   r'   r   r|   handle_backmsg_exception)rh   rt   r   ry   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^   r?   r@   rC   rD   rl   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   r6   rX   rY   r   Ng?)Ftimeoutr   error)r   r   r\   r]   r`   rc   rd   request_reruntimeperf_counterr   session_stater$   r   sleepshutdown)rh   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^   )rh   r   r-   r-   r.   r   H  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.
)(rs   r^   r?   r@   r   rA   rB   rP   rJ   
set_resultrG   is_setr   waitr   rH   FIRST_COMPLETEDr&   cancelrI   clearre   list_active_sessionsr|   flush_browser_queue_send_messager   r   idr   list_sessionsr   rD   rK   	Exceptionset_exception	traceback	print_excr'   info)
rh   r   
done_taskspending_taskstaskactive_session_infomsg_listr   ry   er-   r-   r.   r   L  s~   







CzRuntime._loop_coroutinery   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_countrw   write_forward_msg)rh   ry   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)rs   rF   r   rI   r   r   r-   r-   r.   rd     s   	zRuntime._enqueued_some_messagerE   c                 C  rO   )zpReturn our AsyncObjects instance. If the Runtime hasn't been
        started, this will raise an error.
        NzRuntime hasn't started yet!)rZ   rP   rl   r-   r-   r.   rs     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^   r?   rB   re   num_active_sessionsrs   rH   r   r   rA   rl   r-   r-   r.   r     s   z Runtime._on_session_disconnected)rN   rL   )rN   r<   )rU   r0   rN   rV   )rN   r?   )rN   r   )rN   r"   )rN   r    )rN   r   )rN   r   )rN   rr   )rt   r1   rN   ru   )rt   r1   rN   rV   r   )rt   r1   rN   r<   )NN)
rw   r   r   r   r   r3   r   r3   rN   r1   )rt   r1   r   r   rN   rV   )rt   r1   r   r   rN   rV   )rN   r   )r   r?   rN   rV   )ry   r   r   r   rN   rV   )rN   rE   )$r)   r*   r+   rM   r>   classmethodrS   rT   ri   propertyrm   r9   ro   r8   rp   rq   rK   rz   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rd   rs   r   r-   r-   r-   r.   rL      sZ   
 

/


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


+

l

rL   )I
__future__r   r   sysr   r   dataclassesr   r   enumr   typingr   r   r   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.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(   r0   r?   rE   rL   r-   r-   r-   r.   <module>   sL   *