
    g\C                       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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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l0m1Z1 d dl2m3Z3 d dl4m5Z5 d dl6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z< d dl=m>Z>m?Z?m@Z@mAZA d dlBmCZC d dlDmEZE e
rd dlFmGZG d dlHmIZI  eeJ      ZKdeLd<   ddddd ZMd!ZNdeLd"<   d#ZOdeLd$<   d%ZPdeLd&<   d'ZQdeLd(<   d)ZRdeLd*<   d+ZSdeLd,<   d-ZTdeLd.<   d/ZUdeLd0<   d1eU d2ZVdeLd3<   d4ZWdeLd5<   d6ZXdeLd7<   d8ZYdeLd9<   d:ZZdeLd;<   d<Z[deLd=<    G d> d?e\      Z]dId@Z^dIdAZ_dJdBZ`dKdCZadLdDZbdLdEZc G dF dG      ZddMdHZey)N    )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MessageCacheHandlerRemoveSlashHandlerStaticFileHandler)DEVELOPMENT_PORTget_cookie_secretis_xsrf_enabledmake_url_path_regex)StatsRequestHandler)UploadFileRequestHandler)	Awaitable)
SSLContextr   _LOGGERT      _streamlit_xsrf)compress_responsewebsocket_ping_intervalwebsocket_ping_timeoutxsrf_cookie_named   MAX_PORT_SEARCH_RETRIESzunix://UNIX_SOCKET_PREFIXz/mediaMEDIA_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                      e Zd Zy)RetriesExceededN)__name__
__module____qualname__     P/var/www/openai/venv/lib/python3.12/site-packages/streamlit/web/server/server.pyrC   rC   o   s    rH   rC   c                 ,    t        j                  d      S )Nserver.port)r
   is_manually_setrG   rH   rI   server_port_is_manually_setrM   s   s    !!-00rH   c                 b    t        j                  d      } | d uxr | j                  t              S Nserver.address)r
   
get_option
startswithr4   )addresss    rI   server_address_is_unix_socketrT   w   s/     01G$I7#5#56H#IIrH   c                    t        j                  d      }t        j                  d      }t        ||      }t        | t        j                  d      dz  dz  |      }t	               rt        |       yt        |       y)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
   rQ   _get_ssl_optionsr   rT   start_listening_unix_socketstart_listening_tcp_socket)app	cert_filekey_filerW   http_servers        rI   start_listeningr_   |   ss     !!"67I  !45H"9h7K))*@ADH4OK %&#K0";/rH   c                   t        |       t        |      k7  r*t        j                  d       t        j                  d       | r|rt        |       j                         s+t        j                  d|        t        j                  d       t        |      j                         s+t        j                  d|       t        j                  d       dd l}|j                  |j                  j                        }	 |j                  | |       |S y # |j                  $ r0 t        j                  d| |       t        j                  d       Y |S w xY w)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.)boolr*   errorsysexitr   existssslcreate_default_contextPurposeCLIENT_AUTHload_cert_chainSSLError)r\   r]   rf   ssl_ctxs       rI   rX   rX      s   I$x.(O	
 	X I%%'MM:IFHHQKH~$$&MM98DHHQK,,S[[-D-DE		##Ix8  || 	MM@	 HHQK	s   8D ;EEc                    t        j                  d      }t        j                  j	                  |t        t              d        }t        j                  j                  |      }| j                  |       y rO   )r
   rQ   ospath
expanduserlenr4   tornadonetutilbind_unix_socket
add_socket)r^   rS   	file_nameunix_sockets       rI   rY   rY      sW     01G""73/A+B+D#EFI//229=K;'rH   c                   d}d }|t         k  rjt        j                  d      }t        j                  d      }t        |      t        k(  rt
        j                  dt               	 | j                  ||       	 |t         k\  rt'        d| d	t          d
      y # t        $ r}|j                  t        j                  k(  rt               r,t
        j                  d|       t        j                  d       nUt
        j                  d|       |dz  }|t        k(  r|dz  }t        j                   d|t"        j$                         |dz  }n Y d }~nd }~ww xY w|t         k  rS)Nr   rP   rK   zyPort %s is reserved for internal development. It is strongly recommended to select an alternative port for `server.port`.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.)r3   r
   rQ   intr"   r*   warninglistenOSErrorerrno
EADDRINUSErM   rb   rc   rd   debug
set_optionr   STREAMLIT_DEFINITIONrC   )r^   
call_countportrS   es        rI   rZ   rZ      sQ   JD
.
.##$45  /t9((OO% !		tW-. ,,24& 9>>U=VV`b
 	
 -+  	ww%***.0MM"=tDHHQKMMMt AID//	%%%t\-N-N !OJ'	! .
.s   %B 	E!B(EEc                      e Zd ZddZedd       ZddZedd       ZddZ	edd       Z
ddZedd       Zedd	       Zdd
Zy)Serverc                   t                | j                          || _        t        t              }t        j                  |       t        t              }t        t        |d||t               |t        t        j                  d                        | _        | j                  j                   j#                  |       y)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_manageris_hellosession_storage)_set_tornado_log_levelsinitialize_mimetypes_main_script_pathr   r5   r   initialize_storager   r6   r   r   r   r   r
   rQ   _runtime	stats_mgrregister_provider)selfmain_script_pathr   r   uploaded_file_mgrs        rI   __init__zServer.__init__   s    !!!#!1 4NC++,>?56JK,!#5&7&J&L! 4 & 1 12Q R!

 	112DErH   c                    t        j                  dd       t        j                  dd       t        j                  dd       t        j                  dd       y	)
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)clss    rI   r   zServer.initialize_mimetypes  sE     	;03U;:v.<1rH   c                ,    t        j                  |       S N)r   repr_r   s    rI   __repr__zServer.__repr__  s    zz$rH   c                    | j                   S r   )r   r   s    rI   r   zServer.main_script_path  s    %%%rH   c                
  K   t         j                  d       | j                         }t        |       t	        j
                  d      }t         j                  d|       | j                  j                          d{    y7 w)zaStart the server.

        When this returns, Streamlit is ready to accept new sessions.
        zStarting server...rK   zServer started on port %sN)r*   r   _create_appr_   r
   rQ   r   start)r   r[   r   s      rI   r   zServer.start  s`      	*+   /148mm!!###s   A9B;B<Bc                .    | j                   j                  S )z>A Future that completes when the Server's run loop has exited.)r   stoppedr   s    rI   r   zServer.stopped/  s     }}$$$rH   c                b    t        j                  d      }t        |t              t        d j
                  ift        |t              t        d fdift        |t              t        d j
                  j                  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        |d      t,        d j
                  j.                  ifg}t        j                  d      r,|j1                  t        |t2              t        d fdifg       t        j                  d      rB|j1                  t        |d      t4        d
t7        j8                   j:                        ifg       t=               rWddlm }m!}m"} |j1                  t        |tF              |d|ift        |tH              |d|ift        |tJ              |d|ifg       t        j                  d      rtL        jO                  d       nt7        jP                         }tL        jO                  d|       |j1                  t        |dd      tR        ft        |d      tT        d|z  dtV        t        gdft        |d      tX        fg       t[        j\                  j^                  |fta               tc               te               d tf        S )!zCreate our tornado web app.zserver.baseUrlPathruntimecallbackc                 0     j                   j                  S r   )r   is_ready_for_browser_connectionr   s   rI   <lambda>z$Server._create_app.<locals>.<lambda>A  s    T]]%R%RrH   cachestats_managerz)/(?P<session_id>[^/]+)/(?P<file_id>[^/]+))file_mgris_active_sessionz/(.*)ro    zcomponent/(.*)registryzserver.scriptHealthCheckEnabledc                 8     j                   j                         S r   )r   does_script_run_without_errorr   s   rI   r   z$Server._create_app.<locals>.<lambda>o  s    0[0[0]rH   zserver.enableStaticServingzapp/static/(.*)r   )AuthCallbackHandlerAuthLoginHandlerAuthLogoutHandlerbase_urlglobal.developmentModez/Serving static content from the Node dev serverzServing static content from %sz	(?!/)(.*)required)trailing_slashz(.*)z%s/z
index.html)ro   default_filenamereserved_paths
prohibited)cookie_secretxsrf_cookieswebsocket_max_message_size)4r
   rQ   r%   r7   r   r   r<   r   r9   r   message_cacher8   r&   r   r=   r   r6   r'   r   r   r5   r   r   component_registryextendr>   r   r   get_app_static_dirr   r   )streamlit.web.server.oauth_authlib_routesr   r   r   r?   r@   rA   r*   r   get_static_dirr    r!   r:   r   rr   webApplicationr#   r$   r   TORNADO_SETTINGS)r   baseroutesr   r   r   static_paths   `      rI   r   zServer._create_app4  s@     !56 $D/:'DMM* $D/:RS $D*:;#$--556 $D/:# $--"9"9: $D*>?!
 $,--VW ) $ ? ?)-)H)H
 $D^,<E*BC  $D*:;'T]]==>S.
` >?MM ,D2NO%&(]
 9:MM ,D2CD,!=!=d>S>S!TU  !  MM ,D2JK+#T* ,D2EF(#T* ,D2FG)#T*( 56MMKL#224KMM:KHMM , +j + ,D&9)$)K$70< !4 4	/	 ,DN'1@ {{&&
+-(*'A'C
 
 	
rH   c                P    | j                   j                  t        j                  k(  S r   )r   stater   ONE_OR_MORE_SESSIONS_CONNECTEDr   s    rI   browser_is_connectedzServer.browser_is_connected  s    }}""l&Q&QQQrH   c                @    ddl m} | j                  |j                  k(  S )Nr   )streamlit_app)streamlit.hellor   r   __file__)r   r   s     rI   is_running_hellozServer.is_running_hello  s    1%%)?)???rH   c                f    t        j                  dd       | j                  j                          y )Nz  Stopping...blue)fg)r	   print_to_clir   stopr   s    rI   r   zServer.stop  s"    o&9rH   N)r   strr   ra   returnNone)r   r   )r   zAwaitable[None])r   tornado.web.Applicationr   ra   )rD   rE   rF   r   classmethodr   r   propertyr   r   r   r   r   r   r   rG   rH   rI   r   r      s    F: 2 2  & &$  % %T
l R R @ @
rH   r   c                 \   t        j                  d      st        j                  d      j	                  t        j
                         t        j                  d      j	                  t        j
                         t        j                  d      j	                  t        j
                         y y )Nr   ztornado.accessztornado.applicationztornado.general)r
   rQ   logging	getLoggersetLevelERRORrG   rH   rI   r   r     sr    56 	*+44W]]C/099'--H+,55gmmD 7rH   r   )r[   r   r   r   )r\   
str | Noner]   r   r   zSSLContext | None)r^   r   r   r   r   )f
__future__r   r}   r   r   rn   rc   pathlibr   typingr   r   r   tornado.concurrentrr   tornado.lockstornado.netutiltornado.webtornado.websocket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    r!    streamlit.web.server.server_utilr"   r#   r$   r%   *streamlit.web.server.stats_request_handlerr&   0streamlit.web.server.upload_file_request_handlerr'   collections.abcr(   rf   r)   rD   r*   __annotations__r   r3   r4   r5   r6   r7   r8   r9   r:   r<   r=   r>   r?   r@   rA   	ExceptionrC   rM   rT   r_   rX   rY   rZ   r   r   rG   rH   rI   <module>r     s   #    	 
  , ,      ) 7 7 4 0 ' B B N I T E N R R D   K U)H% %   ! !) " "%  $ & E %   4 e 4* *: :, % ,- U -'(;'<A> >4 e 4: e  #4 % 3* U *, e ,	i 	1J
0.$N(-
`d dNErH   