L ipTUddlmZddlZddlZddlZddlZddlmZmZddl m Z ddl m Z m Z mZddlmZddlmZddlmZdd lmZdd lmZdd lmZmZdd lmZdd lmZddl m!Z!ddl"m#Z#ddl$m%Z%ddl&m'Z'm(Z(m)Z)m*Z*m+Z+ddl,m-Z-m.Z.ddl/m0Z0ddl1m2Z2e r$ddl3m4Z4ddl5m6Z6ddl7m8Z8ddl9m:Z:ddl;mZ>dZ?de@d<ejdk(rdndZBde@d <eeCZDde@d!<Gd"d#eEZFed$%Gd&d'ZGGd(d)e ZHGd*d+eZIGd,d-ZJy).) annotationsN) dataclassfield)Enum) TYPE_CHECKINGFinal NamedTuple)LocalComponentRegistry)BidiComponentManager) get_logger) ForwardMsg) AppSession)get_data_cache_stats_provider!get_resource_cache_stats_provider)LocalDiskCacheStorageManager)MediaFileManager)MemorySessionStorage) ScriptData) ScriptCache)ActiveSessionInfo SessionClientSessionClientDisconnectedErrorSessionManagerSessionStorage)SCRIPT_RUN_WITHOUT_ERRORS_KEYSessionStateStatProvider) StatsManager)WebsocketSessionManager) Awaitable)BaseComponentRegistry)BackMsg)CacheStorageManager)MediaFileStorage)UploadedFileManager<rSCRIPT_RUN_CHECK_TIMEOUTwin32g?_SIGNAL_CHECK_INTERVAL_LOGGERceZdZdZy)RuntimeStoppedErrorz;Raised by operations on a Runtime instance that is stopped.N)__name__ __module__ __qualname____doc___/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/streamlit/runtime/runtime.pyr+r+JsEr1r+T)frozenceZdZUdZded<ded<ded<ded <ee Zd ed <ee Z d ed<ee Z ded<e Z ded<ee Zded<dZded<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_registryztype[SessionManager]session_manager_classrsession_storageFboolis_helloN)r,r-r.r/__annotations__rrr=r r>r r?rr@rrArCr0r1r2r5r5Ns.)(/.2742. 16.1- 5:,51 3J/I', >}}r1c|jduS)a2True 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)rVrYs r2existszRuntime.existss}}D((r1ctj td|t_d|_d|_|j |_|j|_tj|_ |j|_ |j|_|j |_t%|j&|_|j*|_t/|_|jj3|j5|j6|j"|j0|j8|_t=|_|j>jAtC|j>jAtE|j>jA|j"|j>jAtG|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)rAr; script_cachemessage_enqueued_callback)$rUrVrX _async_objs_loop_coroutine_taskr7_main_script_pathrC _is_hellorFrG_stater>_component_registryr?_bidi_component_registryr;_uploaded_file_mgrrr:_media_file_mgrr=_cache_storage_managerr _script_cache discover_and_register_componentsr@rA_enqueued_some_message _session_mgrr _stats_mgrregister_providerrrr)selfconfigs r2__init__zRuntime.__init__st    (AB B 15@D!!'!3!3"** $*#<#< (.(F(F%"(">">/8Q8QR&,&B&B#(] %%FFH"88"22"&"9"9++&*&A&A 9 '. ))*G*IJ ))*K*MN ))$*A*AB ))*B4CTCT*UVr1c|jSN)rfrrs r2statez Runtime.states {{r1c|jSrv)rgrws r2r>zRuntime.component_registrys'''r1c|jSrv)rhrws r2r?zRuntime.bidi_component_registrys,,,r1c|jSrv)rirws r2uploaded_file_mgrzRuntime.uploaded_file_mgrs&&&r1c|jSrv)rkrws r2r=zRuntime.cache_storage_managers***r1c|jSrv)rjrws r2media_file_mgrzRuntime.media_file_mgrs###r1c|jSrv)rprws r2 stats_mgrzRuntime.stats_mgrs r1c6|jjS)z?A Future that completes when the Runtime's run loop has exited.)_get_async_objsrSrws r2rSzRuntime.stoppeds##%---r1cV|jj|}|y|jS)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)roget_active_session_infoclientrr session_id session_infos r2 get_clientzRuntime.get_clients/((@@L  """r1ct|jj|}||jjyy)zClear the user_info for the given session_id. Notes ----- Threading: SAFE. May be called on any thread. N)roget_session_infosessionclear_user_infors r2clear_user_info_for_sessionz#Runtime.clear_user_info_for_sessions7((99*E  #  0 0 2 $r1c Kttjtjtjtjtjtj}||_tj |jd|_|jd{y7w)aStart 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. )rNrOrPrQrRrSzRuntime.loop_coroutine)nameN) rMasyncioget_running_loopEventFuturerb create_task_loop_coroutinercrRrr async_objss r2startz Runtime.start's"..0mmo"==?"==?NN$NN$  &$+$7$7  ")A% !    sB>CCCcljdfd }jj|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. cjtjtjfvrytj dj tjjjy)NzRuntime stopping...) rfrFrJrKr)debug _set_staterOset)rrrsr2stop_on_eventloopz'Runtime.stop..stop_on_eventloopOsT{{|44l6J6JKK MM/ 0 OOL11 2  $ $ &r1NreturnNone)rrNcall_soon_threadsafe)rrrrs` @r2stopz Runtime.stopDs/))+  ' 112CDr1c8|jj|S)zTrue if the session_id belongs to an active session. Notes ----- Threading: SAFE. May be called on any thread. )rois_active_session)rrrs r2rzRuntime.is_active_sessionYs  22:>>r1c|r |r td|jtjtjfvrt d|jd|j j|t|j|j|||}|jtj|jjj|S)aCreate 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.zCan't connect_session (state=))r script_data user_infoexisting_session_idsession_id_override)rXrfrFrJrKr+roconnect_sessionrrdrerrIrrPr)rrrrrrrs r2rzRuntime.connect_sessionbsT #6,  ;;<00,2F2FG G%(Edkk]RS&TU U&&66"4#9#94>>J 3 3 7   CCD --113r1cVtjd|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.)rrrr)r)warningr)rrrrrrs r2create_sessionzRuntime.create_sessions5 TU## 3 3 $  r1c|jj|}|r|jj||jy)a9Close 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)ror close_session_on_session_disconnectedrs r2rzRuntime.close_sessions=&((99*E     + +J 7 %%'r1c|jj|}|r|jj||jy)aZDisconnect 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)rordisconnect_sessionrrs r2rzRuntime.disconnect_sessions=&((@@L     0 0 < %%'r1c,|jtjtjfvrt d|jd|j j |}|tjd|y|jj|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. zCan't handle_backmsg (state=rNz3Discarding BackMsg for disconnected session (id=%s)) rfrFrJrKr+rorr)rrhandle_backmsg)rrrmsgrs r2rzRuntime.handle_backmsgs ;;<00,2F2FG G%(DT[[MQR&ST T((@@L   MMEz  ++C0r1c,|jtjtjfvrt d|jd|j j |}|tjd|y|jj|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=rNz=Discarding BackMsg Exception for disconnected session (id=%s)) rfrFrJrKr+rorr)rrhandle_backmsg_exception)rrrexcrs r2(handle_backmsg_deserialization_exceptionz0Runtime.handle_backmsg_deserialization_exceptions ;;<00,2F2FG G%H UVW ((@@L   MMO  55c:r1cK|jtjtjtjfvryyw)N)Tok)F unavailable)rfrFrGrJrKrws r2is_ready_for_browser_connectionz'Runtime.is_ready_for_browser_connection s: ;;   ! !    #s>AcKtt|j|j|j|j |j ddi} |jdtj}t|jvrltj|z tkrNtjdd{t|jvrtj|z tkrNt|jvr |jy|jt}|rdnd}||f|jS7#|jwxYww) aJLoad 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. emailztest@example.com)rr;r`rarNg?)Ftimeoutrerror)rrrdrerirlrn request_reruntime perf_counterr session_stater&rsleepshutdown)rrrnowrrs r2does_script_run_without_errorz%Runtime.does_script_run_without_error+s-"4#9#94>>J"&"9"9++&*&A&A 23     ! !$ '##%C-W5J5JJ&&(3.2JJmmC(((.W5J5JJ&&(3.2JJ-G4I4II'     &&'DEB$'Cs7    )    sCAEA-E?E4E5EEE5EEEEcTtjd|j|||_y)NzRuntime state: %s -> %s)r)rrf)rr new_states r2rzRuntime._set_stateVs /iH r1cK|j} |jtjk(r |j tj n6|jtj k(rntd|j|jjd|jjsZ|jtj k(rtjtj|jjtj|jjftj t"d{\}}|D]}|j%|st"nj|jtj k(r|j&j)|j*j-D]S}|j.j1}|D]2} |j3||tj:dd{4Utj:dd{nntjtj|jjtj|j&jftj t"d{\}}|D]}|j%|st"Y|jjsZ|j*j=D]1}|j*j?|j.j83|j tj@|jBjdy7A#t4$r3|j*j7|j.j8YwxYw777#tD$rN} |jBjG| tIjJtLjOdYd} ~ yd} ~ wwxYww)zThe main Runtime loop. This function won't exit until `stop` is called. Notes ----- Threading: UNSAFE. Must be called on the eventloop thread. zBad Runtime state at start: N) return_whenrrg{Gz?zJ Please report this bug at https://github.com/streamlit/streamlit/issues. )(rrfrFrGrrHrIrXrR set_resultrOis_setrwaitrrPFIRST_COMPLETEDr(cancelrQclearrolist_active_sessionsrflush_browser_queue _send_messagerridr list_sessionsrrKrS Exception set_exception traceback print_excr)info) rrr done_tasks pending_taskstaskactive_session_infomsg_listrres r2rzRuntime._loop_coroutineZs))+ ^ {{l222 B BC K KK"%A$++#OPP    ) )$ / **113;;,"D"DD 7>ll#// 0D0D0I0I0KL#// 0I0I0N0N0PQ%,$;$; 671-J !.& &&*@*L [[L$O$OO--335/3/@/@/U/U/W 3+#6#>#>#R#R#T#+ 3C" $ 2 23F L#*--"222 3 3"-----3:,,++J,@,@,E,E,GH++J,E,E,J,J,LM!( 7 723-) M*"DKKM""&<&HA!**113F!% 1 1 ? ? A I !!// 0D0D0G0GH  I OOL00 1    ) )$ /I10$B" $ 1 1 D D$7$?$?$B$B!"" 3. -<     , ,Q /    ! LL   sQE O+N  BO+;N# O+%O"& O+O%B O+O(AO+BO+Q O+#8OO+OO+%O+(O++ Q4AP=8Q=QQc|jddk(r2|jtjk(r|xjdz c_|j j |y)aSend 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. typescript_finishedN) WhichOneofrr FINISHED_SUCCESSFULLYscript_run_countrwrite_forward_msg)rrrrs r2rzRuntime._send_messagesQ( >>& !%6 6   :#C#C C  ) )Q . ) --c2r1c|j}|jj|jjy)aCallback 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)rrNrrQrrs r2rnzRuntime._enqueued_some_messages2))+ 11*2K2K2O2OPr1cH|j td|jS)zpReturn our AsyncObjects instance. If the Runtime hasn't been started, this will raise an error. zRuntime hasn't started yet!)rbrXrws r2rzRuntime._get_async_objss(    #<= =r1c |jtjk(rf|jj dk(rH|j j j|jtjyyy)zlSet the runtime state to NO_SESSIONS_CONNECTED if the last active session was disconnected. rN) rfrFrIronum_active_sessionsrrPrrrHrws r2rz Runtime._on_session_disconnectedse KK<FF F!!5571<  " 1 1 7 7 9 OOL>> ?= Gr1)rrU)rrB)rsr5rr)rrF)rr )rr )rr$)rr")rr)rr)rzAwaitable[None])rr6rzSessionClient | None)rr6rrr)rr6rrB)NN) rrrzdict[str, str | bool | None]rr8rr8rr6)rr6rr!rr)rr6r BaseExceptionrr)rztuple[bool, str])rrFrr)rrrr rr)rrM)%r,r-r.rVrD classmethodr[r]rtpropertyrxr>r?r|r=rrrSrrrrrrrrrrrrrrrrrnrrr0r1r2rUrUs $I~$))1Wf((--''++$$.. # 3!:E*?+/*. ==0=( = ( = =F+/*.   0 (  (   ,(0(014;;$1; ;>$$)V jX38 Q  @r1rU)K __future__rrsysrr dataclassesrrenumrtypingrrr 1streamlit.components.lib.local_component_registryr )streamlit.components.v2.component_managerr streamlit.loggerr streamlit.proto.ForwardMsg_pb2r streamlit.runtime.app_sessionrstreamlit.runtime.cachingrr:streamlit.runtime.caching.storage.local_disk_cache_storager$streamlit.runtime.media_file_managerr(streamlit.runtime.memory_session_storagerstreamlit.runtime.script_datar+streamlit.runtime.scriptrunner.script_cacher!streamlit.runtime.session_managerrrrrrstreamlit.runtime.staterrstreamlit.runtime.statsr+streamlit.runtime.websocket_session_managerrcollections.abcr2streamlit.components.types.base_component_registryr streamlit.proto.BackMsg_pb2r!!streamlit.runtime.caching.storager"$streamlit.runtime.media_file_storager#'streamlit.runtime.uploaded_file_managerr$r&rDplatformr(r,r)rr+r5rFrMrUr0r1r2rs# (33TJ'54BI4C1O)X3EEK#%%$(+||w'>DHH%%F)F $&&&^4":"0a @a @r1