
    -eqQ                       d Z ddlmZ ddlZ ej        e          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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 m!Z!m"Z" d	dl#m$Z$m%Z% d	dl&m'Z' ddlm(Z(m)Z) ddl*m+Z+m,Z, erd	dl-m.Z. d	dl/m0Z0 d	dl1m2Z2 d	dl3m4Z4 ddl5m6Z6 dZ7 G d d          Z8 G d de8          Z9 G d de'          Z:dS )a$   Provide basic Bokeh server objects that use a Tornado ``HTTPServer`` and
``BokeTornado`` Tornado Application to service Bokeh Server Applications.
There are two public classes in this module:

:class:`~bokeh.server.server.BaseServer`
    This is a lightweight class to explicitly coordinate the components needed
    to run a Bokeh server (A :class:`~bokeh.server.tornado.BokehTornado`
    instance, and Tornado ``HTTPServer`` and a Tornado ``IOLoop``)

:class:`~bokeh.server.server.Server`
    This higher-level convenience class only needs to be configured with Bokeh
    :class:`~bokeh.application.application.Application` instances, and will
    automatically create and coordinate the lower level Tornado components.

See :ref:`ug_server_introduction` for general information on the Bokeh server.

    )annotationsN)	FrameType)TYPE_CHECKINGAnyMapping)netutilversion)
HTTPServer)IOLoop   )__version__)
properties)BoolIntNullableString)DEFAULT_SERVER_PORT
server_url)Options   )(DEFAULT_WEBSOCKET_MAX_MESSAGE_SIZE_BYTESBokehTornado)bind_socketscreate_hosts_allowlist)Application)	ModifyDoc)ID)BrowserTarget)ServerSession)
BaseServerServerc                      e Zd ZdZd.d
Zed/d            Zd0dZd1d2dZd0dZ	d0dZ
d3dZd4d5dZd6d7d!Zd"Zd0d#Zd8d(Zed9d*            Zed:d+            Zed;d,            Zed:d-            ZdS )<r    a4   Explicitly coordinate the level Tornado components required to run a
    Bokeh server:

    * A Tornado ``IOLoop`` to run the Bokeh server machinery.

    * a ``BokehTornado`` Tornado application that defines the Bokeh server
      machinery.

    * a Tornado ``HTTPServer`` to direct HTTP requests

    All three of these components must be passed to ``BaseServer``, which will
    initialize the ``BokehTornado`` instance on the ``io_loop``. The
    ``http_server`` must have been previously created and initialized with the
    ``BokehTornado`` instance.

    io_loopr   tornado_appr   http_serverr
   returnNonec                    d| _         d| _        || _        || _        || _        | j                            |           dS )a7   Create a ``BaseServer`` instance.

        Args:
            io_loop (IOLoop) :
                A Tornado ``IOLoop`` to run the Bokeh Tornado application on.

            tornado_app (BokehTornado) :
                An instance of the Bokeh Tornado application that generates
                Bokeh Documents and Sessions.

            http_server (HTTPServer) :
                A Tornado ``HTTPServer`` to service HTTP requests for Bokeh
                applications. Should have already be configured with the
                ``tornado_app`` when created.

        FN)_started_stopped_http_loop_tornado
initialize)selfr#   r$   r%   s       3lib/python3.11/site-packages/bokeh/server/server.py__init__zBaseServer.__init__f   sC    $  

#  )))))    c                    | j         S )zG The Tornado ``IOLoop`` that this Bokeh Server is running on.

        )r,   r/   s    r0   r#   zBaseServer.io_loop       
 zr2   c                h    | j         r
J d            d| _         | j                                         dS )a   Install the Bokeh Server and its background tasks on a Tornado
        ``IOLoop``.

        This method does *not* block and does *not* affect the state of the
        Tornado ``IOLoop``  You must start and stop the loop yourself, i.e.
        this method is typically useful when you are already explicitly
        managing an ``IOLoop`` yourself.

        To start a Bokeh server and immediately "run forever" in a blocking
        manner, see :func:`~bokeh.server.server.BaseServer.run_until_shutdown`.

        zAlready startedTN)r)   r-   startr4   s    r0   r7   zBaseServer.start   s<     =33"3333r2   Twaitboolc                    | j         r
J d            d| _         | j                            |           | j                                         dS )aK   Stop the Bokeh Server.

        This stops and removes all Bokeh Server ``IOLoop`` callbacks, as well
        as stops the ``HTTPServer`` that this instance was configured with.

        Args:
            fast (bool):
                Whether to wait for orderly cleanup (default: True)

        Returns:
            None

        zAlready stoppedTN)r*   r-   stopr+   )r/   r8   s     r0   r;   zBaseServer.stop   sP     =33"33334   
r2   c                    | j                                          | j                            | j         j                   dS )z Stop listening on ports. The server will no longer be usable after
        calling this function.

        .. note::
            This function is mostly useful for tests

        Returns:
            None

        N)r+   r;   r#   add_callbackclose_all_connectionsr4   s    r0   unlistenzBaseServer.unlisten   s7     	
!!$*"BCCCCCr2   c                R   | j         s|                                  t          j        | j                   t          j        t
          j        | j                   	 | j                                         n# t          $ r t          d           Y nw xY w|                                  dS )a   Run the Bokeh Server until shutdown is requested by the user,
        either via a Keyboard interrupt (Ctrl-C) or SIGTERM.

        Calling this method will start the Tornado ``IOLoop`` and block
        all execution in the calling process.

        Returns:
            None

        z
Interrupted, shutting downN)r)   r7   atexitregister_atexitsignalSIGTERM_sigtermr,   KeyboardInterruptprintr;   r4   s    r0   run_until_shutdownzBaseServer.run_until_shutdown   s     } 	JJLLL%%%fndm444	2J  	2 	2 	2011111	2		s   A4 4BBapp_pathstr
session_idr   r   c                8    | j                             ||          S )ak   Get an active a session by name application path and session ID.

        Args:
            app_path (str) :
                The configured application path for the application to return
                a session for.

            session_id (str) :
                The session ID of the session to retrieve.

        Returns:
            ServerSession

        )r-   get_session)r/   rJ   rL   s      r0   rN   zBaseServer.get_session   s     }((:>>>r2   N
str | Nonelist[ServerSession]c                    || j                             |          S g }| j         j        D ]}|| j                             |          z  } |S )ai   Gets all currently active sessions for applications.

        Args:
            app_path (str, optional) :
                The configured application path for the application to return
                sessions for. If None, return active sessions for all
                applications. (default: None)

        Returns:
            list[ServerSession]

        )r-   get_sessions	app_paths)r/   rJ   all_sessionspaths       r0   rR   zBaseServer.get_sessions   s[     =--h777,.M+ 	= 	=DDM66t<<<LLr2   tabbrowsernewr   c                    |                     d          st          d          d}| j        | j        dk    r| j        }d| d| j         | j         | }dd	lm}  ||||
           dS )a   Opens an app in a browser window or tab.

        This method is useful for testing or running Bokeh server applications
        on a local machine but should not call when running Bokeh server for
        an actual deployment.

        Args:
            app_path (str) : the app path to open
                The part of the URL after the hostname:port, with leading slash.

            browser (str, optional) : browser to show with (default: None)
                For systems that support it, the **browser** argument allows
                specifying which browser to display in, e.g. "safari", "firefox",
                "opera", "windows-default" (see the :doc:`webbrowser <python:library/webbrowser>`
                module documentation in the standard lib for more details).

            new (str, optional) : window or tab (default: "tab")
                If ``new`` is 'tab', then opens a new tab.
                If ``new`` is 'window', then opens a new window.

        Returns:
            None

        /zapp_path must start with a /	localhostN zhttp://:r   )view)rW   rX   )
startswith
ValueErroraddressportprefixbokeh.util.browserr^   )r/   rJ   rW   rX   address_stringurlr^   s          r0   showzBaseServer.show   s    2 ""3'' 	=;<<< %<#(:(:!\NKKKKDKKKK++++++S's++++++r2   Fc                    | j         rd S d| _         t                              d           | j        s|                     d           d S d S )NTzShutdown: cleaning upF)r8   )_atexit_ranlogdebugr*   r;   r4   s    r0   rC   zBaseServer._atexit  s[     	F		)***} 	"II5I!!!!!	" 	"r2   signumintframeFrameType | Nonec                t    t          d| d           | j                            | j        j                   d S )NzReceived signal z, shutting down)rH   r,   add_callback_from_signalr;   )r/   rl   rn   s      r0   rF   zBaseServer._sigterm$  s<    8888999
++DJO<<<<<r2   
int | Nonec                    t          d | j        j                                        D                       }|                                d         S )zQ The configured port number that the server listens on for HTTP requests
        c              3  X   K   | ]%}|j         t          j        t          j        fv !|V  &d S NfamilysocketAF_INETAF_INET6.0socks     r0   	<genexpr>z"BaseServer.port.<locals>.<genexpr>-  D       
 
{v~v??? ????
 
r2   r   nextr+   _socketsvaluesgetsocknamer/   r}   s     r0   rb   zBaseServer.port)  Y      
 
!Z07799
 
 
 
 
 !!!$$r2   c                    t          d | j        j                                        D                       }|                                d         S )zM The configured address that the server listens on for HTTP requests
        c              3  X   K   | ]%}|j         t          j        t          j        fv !|V  &d S ru   rv   r{   s     r0   r~   z%BaseServer.address.<locals>.<genexpr>7  r   r2   r   r   r   s     r0   ra   zBaseServer.address3  r   r2   c                    | j         j        S )z> The configured URL prefix to use for all Bokeh server paths. )r-   rc   r4   s    r0   rc   zBaseServer.prefix=  s     }##r2   c                    | j         j        S )z5 A path to a Jinja2 template to use for index at "/" )r-   indexr4   s    r0   r   zBaseServer.indexB  s     }""r2   )r#   r   r$   r   r%   r
   r&   r'   )r&   r   )r&   r'   )T)r8   r9   r&   r'   )rJ   rK   rL   r   r&   r   ru   )rJ   rO   r&   rP   )NrV   )rJ   rK   rW   rO   rX   r   r&   r'   )rl   rm   rn   ro   r&   r'   r&   rr   r&   rO   r&   rK   )__name__
__module____qualname____doc__r1   propertyr#   r7   r;   r?   rI   rN   rR   rg   ri   rC   rF   rb   ra   rc   r    r2   r0   r    r    T   s        "* * * *6    X   "    &D D D D   ,? ? ? ?"    (#, #, #, #, #,J K" " " "= = = =
 % % % X% % % % X% $ $ $ X$ # # # X# # #r2   r    c                  p     e Zd ZdZ	 dd fdZedd            Zedd            Zedd            Z xZ	S )r!   a   A high level convenience class to run a Bokeh server.

    This class can automatically coordinate the three the base level
    components required to run a Bokeh server:

    * A Tornado ``IOLoop`` to run the Bokeh server machinery.

    * a ``BokehTornado`` Tornado application that defines the Bokeh server
      machinery.

    * a Tornado ``HTTPServer`` to direct HTTP requests

    This high level ``Server`` class has some limitations. In particular, it is
    not possible to set an explicit ``io_loop`` and ``num_procs`` other than 1
    at the same time. To do that, it is necessary to use ``BaseServer`` and
    coordinate the three components above explicitly.

    Napplications?Mapping[str, Application | ModifyDoc] | Application | ModifyDocr#   IOLoop | Nonehttp_server_kwargsdict[str, Any] | Nonekwargsr   r&   r'   c           	        t                               dt           dt           d           t	          |          }|j        dk    r|t          d          |j        dk    rt          j        dk    rt          d          |j	        rt          j        dk    rt          d	          |i }|
                    d
|j                   |j        rit                               d           ddl}|                    |j        j                  }|                    |j        |j        |j                   ||d<   |j	        rUt)          j        |j	                  g}|j	        | _        d\  | _        | _        |j        rt5          |j        d          }	nKg }	nHt7          |j        |j                  \  }| _        |j        | _        t5          |j        | j                  }	t=          | j        | j        |j        du          | _        	 tA          |f|	| j        |j!        |j"        |j#        d|}
|j        dk    r:tI          d |
j%        &                                D                       s
J d            tO          |
fi |}|(                    |j                   |)                    |           n(# tT          $ r |D ]}|+                                  w xY w|tY          j-                    }t]                      /                    ||
|           dS )a   Create a ``Server`` instance.

        Args:
            applications (dict[str, Application] or Application or callable) :
                A mapping from URL paths to Application instances, or a single
                Application to put at the root URL.

                The Application is a factory for Documents, with a new Document
                initialized for each Session. Each application is identified
                by a path that corresponds to a URL, like "/" or "/myapp"

                If a single Application is provided, it is mapped to the URL
                path "/" automatically.

                As a convenience, a callable may also be provided, in which
                an Application will be created for it using
                ``FunctionHandler``.

            io_loop (IOLoop, optional) :
                An explicit Tornado ``IOLoop`` to run Bokeh Server code on. If
                None, ``IOLoop.current()`` will be used (default: None)

            http_server_kwargs (dict, optional) :
                Extra arguments passed to ``tornado.httpserver.HTTPServer``.

                E.g. ``max_buffer_size`` to specify the maximum upload size.
                More details can be found at:

                http://www.tornadoweb.org/en/stable/httpserver.html#http-server

                If None, no extra arguments are passed (default: None)

        Additionally, the following options may be passed to configure the
        operation of ``Server``:

        .. bokeh-options:: _ServerOpts
            :module: bokeh.server.server

        Any remaining keyword arguments will be passed as-is to
        ``BokehTornado``.

        zStarting Bokeh server version z (running on Tornado )r   NzSetting both num_procs and io_loop in Server is incompatible. Use BaseServer to coordinate an explicit IOLoop and multi-process HTTPServerwin32z&num_procs > 1 not supported on Windowsz*Unix sockets are not supported on windows.xheaderszConfiguring for SSL terminationr   )certfilekeyfilepasswordssl_optionsNN)extra_websocket_originsabsolute_urlrc   r    websocket_max_message_size_bytesc              3  .   K   | ]}|j         j        V  d S ru   )applicationsafe_to_fork)r|   app_contexts     r0   r~   z"Server.__init__.<locals>.<genexpr>  s(      uuK;2?uuuuuur2   ztUser application code has run before attempting to start multiple processes. This is considered an unsafe operation.)0rj   infor   tornado_version_ServerOpts	num_procsRuntimeErrorsysplatformunix_socket
setdefaultuse_xheadersssl_certfilesslcreate_default_contextPurposeCLIENT_AUTHload_cert_chainssl_keyfilessl_passwordr   bind_unix_socket_unix_socket_address_portallow_websocket_originr   r   ra   rb   r   _absolute_urlr   rc   r   websocket_max_message_sizeallr   r   r
   r7   add_sockets	Exceptioncloser   currentsuperr1   )r/   r   r#   r   r   optsr   contextsocketsr   r$   r%   s	__class__s                r0   r1   zServer.__init___  sa   X 	f+ffTcfffggg6"">A'"5 ]   >A#,'"9"9GHHH 	M 7 7KLLL%!#%%j$2CDDD 	8HH6777JJJ001HIIG##T->HXcgct#uuu07}- 	e/0@AABG $ 0D(2%DM4:* -*@A\^b*c*c''*,''".t|TY"G"GGTZ LDM&<T=XZ^Zc&d&d#'tz4CT\`C`aa	&| 1?V484F.2k-1ZHLHg1 1 *01 1K ~""uuS^SkSrSrStStuuuuu U UTU U U %[GG4FGGKdn---##G,,,, 	 	 	  					 ?n&&G+{;;;;;s   B(J, ,%Krr   c                    | j         S )zZ The configured port number that the server listens on for HTTP
        requests.
        )r   r4   s    r0   rb   zServer.port  r5   r2   rK   c                    | j         S )zA The configured unix socket that the server listens to.

        )r   r4   s    r0   r   zServer.unix_socket  s    
   r2   rO   c                    | j         S )zW The configured address that the server listens on for HTTP
        requests.

        )r   r4   s    r0   ra   zServer.address  s     }r2   r   )
r   r   r#   r   r   r   r   r   r&   r'   r   r   r   )
r   r   r   r   r1   r   rb   r   ra   __classcell__)r   s   @r0   r!   r!   K  s         ( X\r< r< r< r< r< r< r<h    X ! ! ! X!    X    r2   r!   c                     e Zd ZU  edd          Z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dd          Zded<    eed          Zded<    e ej        e          d          Zded<    edd          Z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ed!          Zded"<   d#S )$r   r   a  
    The number of worker processes to start for the HTTP server. If an explicit
    ``io_loop`` is also configured, then ``num_procs=1`` is the only compatible
    value. Use ``BaseServer`` to coordinate an explicit ``IOLoop`` with a
    multi-process HTTP server.

    A value of 0 will auto detect number of cores.

    Note that due to limitations inherent in Tornado, Windows does not support
    ``num_procs`` values greater than one! In this case consider running
    multiple Bokeh server instances behind a load balancer.
    )defaulthelprm   r   zD
    The address the server should listen on for HTTP requests.
    )r   rO   ra   zH
    The port number the server should listen on for HTTP requests.
    rb   z
    The unix socket the server should bind to. Other network args
    such as port, address, ssl options etc are incompatible with unix sockets.
    Unix socket support is not available on windows.
    r   r\   z9
    A URL prefix to use for all Bokeh server paths.
    rK   rc   z>
    A path to a Jinja2 template to use for the index "/"
    r   z
    A list of hosts that can connect to the websocket.

    This is typically required when embedding a Bokeh server app in an external
    web site using :func:`~bokeh.embed.server_document` or similar.

    If None, "localhost" is used.
    zlist[str] | Noner   Fz
    Whether to have the Bokeh server override the remote IP and URI scheme
    and protocol for all requests with ``X-Real-Ip``, ``X-Forwarded-For``,
    ``X-Scheme``, ``X-Forwarded-Proto`` headers (if they are provided).
    r9   r   z=
    The path to a certificate file for SSL termination.
    r   z=
    The path to a private key file for SSL termination.
    r   z>
    A password to decrypt the SSL keyfile, if necessary.
    r   z?
    Set the Tornado ``websocket_max_message_size`` value.
    r   N)r   r   r   r   r   __annotations__r   r   ra   r   rb   r   rc   r   pListr   r   r   r   r   r   r   r   r   r2   r0   r   r     s        S * 	 	 	I 	 	 	 	 $8F 2 	 	 	G 	 	 	 	 / 7 	 	 	D 	 	 	 	  (x 6  	  	  	K 	 	 	 	 & + 	 	 	F 	 	 	 	 ! / 	 	 	E 	 	 	 	 08xv N 0	 0	 0	 	 	 	 	 e 3 	 	 	L 	 	 	 	  (x 6  	  	  	L 	 	 	 	 'hv 5 	 	 	K 	 	 	 	  (x 6  	  	  	L 	 	 	 	 '*c2Z b '	 '	 '	 	 	 	 	 	 	r2   r   );r   
__future__r   logging	getLoggerr   rj   rA   rD   rx   r   typesr   typingr   r   r   tornador   r	   r   tornado.httpserverr
   tornado.ioloopr   r\   r   corer   r   core.propertiesr   r   r   r   	resourcesr   r   util.optionsr   r   r   utilr   r   application.applicationr   application.handlers.functionr   
core.typesr   util.browserr   sessionr   __all__r    r!   r   r   r2   r0   <module>r      s   * # " " " " " g!!    



       . . . . . . . . . . 8 7 7 7 7 7 7 7 ) ) ) ) ) ) ! ! ! ! ! !       " " " " " "            8 7 7 7 7 7 7 7 " " " " " " K K K K K K K K 6 6 6 6 6 6 6 6 '555555999999,,,,,,&&&&&&q# q# q# q# q# q# q# q#n\ \ \ \ \Z \ \ \HB	 B	 B	 B	 B	' B	 B	 B	 B	 B	r2   