o
    Zh0J                     @  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Zd dlmZ d dl	m
Z
mZmZ d dlZd dlmZ d dlmZ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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+ d dl,m-Z- d dl.m/Z/ d dl0m1Z1 d dl2m3Z3m4Z4m5Z5m6Z6m7Z7 d dl8m9Z9m:Z:m;Z;m<Z< d dl=m>Z> d dl?m@Z@ e
rd dlAZAd dlBmCZC d dlDmEZE eeFZGdeHd< d`ddZIdad!d"ZJd#ZKdeHd$< d%ZLdeHd&< d'ZMdeHd(< d)ZNdeHd*< d+ZOdeHd,< d-ZPdeHd.< d/ZQdeHd0< d1ZRdeHd2< d3ZSdeHd4< d5ZTdeHd6< d7eT d8ZUdeHd9< d:ZVdeHd;< d<ZWdeHd=< d>ZXdeHd?< d@ZYdeHdA< dBZZdeHdC< G dDdE dEe[Z\dbdGdHZ]dbdIdJZ^dcdNdOZ_dddTdUZ`dedXdYZadedZd[ZbG d\d] d]Zcdfd^d_ZddS )g    )annotationsN)Path)TYPE_CHECKINGAnyFinal)
HTTPServer)cli_utilconfig	file_utilutil)is_authlib_installed)ConfigOption)
get_logger)RuntimeRuntimeConfigRuntimeState)MemoryMediaFileStorage)MemorySessionStorage)MemoryUploadedFileManager)get_max_message_size_bytes)$create_default_cache_storage_manager)AppStaticFileHandler)BrowserWebSocketHandler)ComponentRequestHandler)MediaFileHandler)AddSlashHandlerHealthHandlerHostConfigHandlerRemoveSlashHandlerStaticFileHandler)get_cookie_secretis_tornado_version_less_thanis_xsrf_enabledmake_url_path_regex)StatsRequestHandler)UploadFileRequestHandler)	Awaitable)
SSLContextr   _LOGGERreturntuple[int, int]c                  C  sX   t d} | dur t| }tds|dk rtd|| ||fS tdr&dnd}|dfS )zGet the websocket ping interval and timeout from config or defaults.

    Returns
    -------
        tuple: (ping_interval, ping_timeout)
    zserver.websocketPingIntervalNz6.5.0   a  You have set server.websocketPingInterval to %s, but Tornado >= 6.5 requires websocket_ping_interval >= websocket_ping_timeout. To comply, we are setting both the ping interval and ping timeout to %s. Depending on the specific deployment setup, this may cause connection issues.   )r	   
get_optionintr!   r(   warning)configured_intervalintervaldefault_interval r3   \/var/www/html/Persson_Maskin/env/lib/python3.10/site-packages/streamlit/web/server/server.py(_get_websocket_ping_interval_and_timeoutD   s   

r5   dict[str, Any]c                  C  s   t  \} }d| |ddS )zqGet Tornado settings for the server.

    This is a function to allow for testing and dynamic configuration.
    T_streamlit_xsrf)compress_responsewebsocket_ping_intervalwebsocket_ping_timeoutxsrf_cookie_name)r5   )ping_intervalping_timeoutr3   r3   r4   get_tornado_settingsd   s   
r>   d   MAX_PORT_SEARCH_RETRIESzunix://UNIX_SOCKET_PREFIXz/mediaMEDIA_ENDPOINTz
/componentCOMPONENT_ENDPOINTz/app/staticSTATIC_SERVING_ENDPOINTz/_stcore/upload_fileUPLOAD_FILE_ENDPOINTz_stcore/streamSTREAM_ENDPOINTz(?:st-metrics|_stcore/metrics)METRIC_ENDPOINTz_stcore/messageMESSAGE_ENDPOINTz_stcore/healthNEW_HEALTH_ENDPOINTz(?:healthz|)HEALTH_ENDPOINTz_stcore/host-configHOST_CONFIG_ENDPOINTz3(?:script-health-check|_stcore/script-health-check)SCRIPT_HEALTH_CHECK_ENDPOINTz/oauth2callbackOAUTH2_CALLBACK_ENDPOINTz/auth/loginAUTH_LOGIN_ENDPOINTz/auth/logoutAUTH_LOGOUT_ENDPOINTc                   @  s   e Zd ZdS )RetriesExceededErrorN)__name__
__module____qualname__r3   r3   r3   r4   rQ      s    rQ   boolc                   C  s
   t dS )Nserver.port)r	   is_manually_setr3   r3   r3   r4   server_port_is_manually_set      
rX   c                  C  s   t d} | d uo| tS )Nserver.address)r	   r-   
startswithrA   )addressr3   r3   r4   server_address_is_unix_socket   s   
r]   apptornado.web.ApplicationNonec                 C  sX   t d}t d}t||}t| t dd d |d}t r&t| dS t| dS )zMakes the server start listening at the configured port.

    In case the port is already taken it tries listening to the next available
    port.  It will error after MAX_PORT_SEARCH_RETRIES attempts.

    zserver.sslCertFilezserver.sslKeyFilezserver.maxUploadSizei   )max_buffer_sizessl_optionsN)r	   r-   _get_ssl_optionsr   r]   start_listening_unix_socketstart_listening_tcp_socket)r^   	cert_filekey_filerb   http_serverr3   r3   r4   start_listening   s   


ri   rf   
str | Nonerg   SSLContext | Nonec                 C  s   t | t |krtd td | rd|rdt|  s'td|  td t| s8td| td dd l}||j	j
}z	|| | W |S  |jyc   td| | td Y |S w d S )NzzOptions 'server.sslCertFile' and 'server.sslKeyFile' must be set together. Set missing options or delete existing options.r,   zCert file '%s' does not exist.zKey file '%s' does not exist.r   zWFailed to load SSL certificate. Make sure cert file '%s' and key file '%s' are correct.)rU   r(   errorsysexitr   existssslcreate_default_contextPurposeCLIENT_AUTHload_cert_chainSSLError	exception)rf   rg   rp   ssl_ctxr3   r3   r4   rc      s6   




rc   rh   r   c                 C  sh   t d}tj|ttd  }dd l}t|j	dr(|j	
|}| | d S td td d S )NrZ   r   bind_unix_socketz@Unix socket support is not available in this version of Tornado.r,   )r	   r-   ospath
expanduserlenrA   tornado.netutilhasattrnetutilrx   
add_socketr(   rl   rm   rn   )rh   r\   	file_nametornadounix_socketr3   r3   r4   rd      s   
rd   c              
   C  s   d}d }|t k r^td}td}z| || W nC tyY } z3|jtjkrNt r7t	d| t
d ntd| |d7 }td|tj |d7 }n W Y d }~nd }~ww |t k s|t krmtd| dt  d	d S )
Nr   rZ   rV   zPort %s is already in user,   z3Port %s already in use, trying to use the next one.z$Cannot start Streamlit server. Port zG is already in use, and Streamlit was unable to find a free port after z
 attempts.)r@   r	   r-   listenOSErrorerrno
EADDRINUSErX   r(   rl   rm   rn   debug
set_optionr   STREAMLIT_DEFINITIONrQ   )rh   
call_countportr\   er3   r3   r4   re      s@   


re   c                   @  s   e Zd ZdddZedd	d
Zd ddZed ddZdddZ	ed!ddZ
d"ddZed#ddZed#ddZdddZdS )$Servermain_script_pathstris_hellorU   r)   r`   c                 C  sp   t   |   || _d| _tt}t| tt	}t
t|d||t |ttddd| _| jj| dS )z+Create the server. It won't be started yet.Nzserver.disconnectedSessionTTL)ttl_seconds)script_pathcommand_linemedia_file_storageuploaded_file_managercache_storage_managerr   session_storage)_set_tornado_log_levelsinitialize_mimetypes_main_script_path_bootstrap_taskr   rB   r   initialize_storager   rE   r   r   r   r   r	   r-   _runtime	stats_mgrregister_provider)selfr   r   r   uploaded_file_mgrr3   r3   r4   __init__  s*   
zServer.__init__c                 C  s4   t dd t dd t dd t dd d	S )
zJEnsures that common mime-types are robust against system misconfiguration.z	text/htmlz.htmlzapplication/javascriptz.jsztext/cssz.cssz
image/webpz.webpN)	mimetypesadd_type)clsr3   r3   r4   r   <  s   zServer.initialize_mimetypesc                 C  s
   t | S N)r   repr_r   r3   r3   r4   __repr__D  rY   zServer.__repr__c                 C  s   | j S r   )r   r   r3   r3   r4   r   G  s   zServer.main_script_pathc                   sF   t d |  }t| td}t d| | j I dH  dS )zaStart the server.

        When this returns, Streamlit is ready to accept new sessions.
        zStarting server...rV   zServer started on port %sN)r(   r   _create_appri   r	   r-   r   start)r   r^   r   r3   r3   r4   r   K  s   

zServer.startAwaitable[None]c                 C  s   | j jS )z>A Future that completes when the Server's run loop has exited.)r   stoppedr   r3   r3   r4   r   [  s   zServer.stoppedr_   c              
     s  t d}t|ttd jift|ttd fddift|tt	d jj
ift|ttft|t dt jj jjdft|t d	td
dift|t d	td jjifg}t drq|t|ttd fddifg t dr|t|t d	td
t jifg t rddlm}m }m!} |t|t"|d|ift|t#|d|ift|t$|d|ifg t drt%&d n.t' }t%&d| |t|dddt(ft|dt)| ddt*tgdft|ddt+fg t,j-j.|ft/ t0 t1 dt2 S )zCreate our tornado web app.zserver.baseUrlPathruntimecallbackc                     s    j jS r   )r   is_ready_for_browser_connectionr3   r   r3   r4   <lambda>m  s    z$Server._create_app.<locals>.<lambda>stats_managerz)/(?P<session_id>[^/]+)/(?P<file_id>[^/]+))file_mgris_active_sessionz/(.*)rz    registryzserver.scriptHealthCheckEnabledc                     s
    j  S r   )r   does_script_run_without_errorr3   r   r3   r4   r     s   
 zserver.enableStaticServingr   )AuthCallbackHandlerAuthLoginHandlerAuthLogoutHandlerbase_urlglobal.developmentModez/Serving static content from the Node dev serverzServing static content from %sz	(?!/)(.*)required)trailing_slashz(.*)/z
index.html)rz   default_filenamereserved_paths
prohibited)cookie_secretxsrf_cookieswebsocket_max_message_size)3r	   r-   r#   rF   r   r   rK   r   rG   r$   r   rL   r   rE   r%   r   r   rB   r   rC   r   component_registryextendrM   rD   r   r
   get_app_static_dirr   r   )streamlit.web.server.oauth_authlib_routesr   r   r   rN   rO   rP   r(   r   get_static_dirr   r   rI   r   r   webApplicationr    r"   r   r>   )r   baseroutesr   r   r   static_pathr3   r   r4   r   `  s   



+




 zServer._create_appc                 C  s   | j jtjkS r   )r   stater   ONE_OR_MORE_SESSIONS_CONNECTEDr   r3   r3   r4   browser_is_connected  s   zServer.browser_is_connectedc                 C  s   ddl m} | j|jkS )Nr   )streamlit_app)streamlit.hellor   r   __file__)r   r   r3   r3   r4   is_running_hello  s   zServer.is_running_helloc                 C  s   t jddd | j  d S )Nz  Stopping...blue)fg)r   print_to_clir   stopr   r3   r3   r4   r     s   zServer.stopN)r   r   r   rU   r)   r`   r)   r`   )r)   r   )r)   r   )r)   r_   r)   rU   )rR   rS   rT   r   classmethodr   r   propertyr   r   r   r   r   r   r   r3   r3   r3   r4   r     s"    
"


 r   c                   C  sH   t ds"tdtj tdtj tdtj d S d S )Nr   ztornado.accessztornado.applicationztornado.general)r	   r-   logging	getLoggersetLevelERRORr3   r3   r3   r4   r      s
   
r   )r)   r*   )r)   r6   r   )r^   r_   r)   r`   )rf   rj   rg   rj   r)   rk   )rh   r   r)   r`   r   )e
__future__r   r   r   r   ry   rm   pathlibr   typingr   r   r   tornado.webr   tornado.httpserverr   	streamlitr   r	   r
   r   streamlit.auth_utilr   streamlit.config_optionr   streamlit.loggerr   streamlit.runtimer   r   r   +streamlit.runtime.memory_media_file_storager   (streamlit.runtime.memory_session_storager   .streamlit.runtime.memory_uploaded_file_managerr   streamlit.runtime.runtime_utilr   *streamlit.web.cache_storage_manager_configr   ,streamlit.web.server.app_static_file_handlerr   .streamlit.web.server.browser_websocket_handlerr   .streamlit.web.server.component_request_handlerr   'streamlit.web.server.media_file_handlerr   streamlit.web.server.routesr   r   r   r   r    streamlit.web.server.server_utilr    r!   r"   r#   *streamlit.web.server.stats_request_handlerr$   0streamlit.web.server.upload_file_request_handlerr%   asynciocollections.abcr&   rp   r'   rR   r(   __annotations__r5   r>   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rK   rL   rM   rN   rO   rP   	ExceptionrQ   rX   r]   ri   rc   rd   re   r   r   r3   r3   r3   r4   <module>   s|   

 





'
% h