U
    /e-                     @  s   d Z ddlmZ ddlZeeZddlmZm	Z	 ddl
mZmZmZmZmZmZmZmZ ddlmZ ddlmZ dd	lmZ erdd
lmZ ddlmZ ddlmZ dZeg df ZG dd dZ G dd dedZ!G dd dedZ"ee"gdf Z#dS )a   Provide the ``Application`` class.

Application instances are factories for creating new Bokeh Documents.

When a Bokeh server session is initiated, the Bokeh server asks the Application
for a new Document to service the session. To do this, the Application first
creates a new empty Document, then it passes this new Document to the
``modify_document`` method of each of its handlers. When all handlers have
updated the Document, it is used to service the user session.

    )annotationsN)ABCMetaabstractmethod)TYPE_CHECKINGAny	AwaitableCallableClassVarDictListTuple   )ID)Document)settings)HTTPServerRequest)ServerSession   )Handler)ApplicationServerContextSessionContextc                   @  s  e Zd ZU dZdZded< ded< ded< d	ed
< dddd	ddddZeddddZed	dddZ	eddddZ
eddddZdddddZd dd!d"Zd dd#d$d%Zd&dd'd(d)Zd&dd'd*d+Zd,dd-d.d/Zd,dd-d0d1Zd2d3d4d5d6ZdS )7r   zQ An Application is a factory for Document instances.

    .. autoclasstoc::

    TzClassVar[bool]_is_a_bokeh_application_classz
str | None_static_pathzList[Handler]	_handlerszDict[str, Any] | None	_metadataN)metadatar   None)handlersr   returnc                G  s*   d| _ g | _|| _|D ]}| | qdS )a?   Application factory.

        Args:
            handlers (seq[Handler]): List of handlers to call.
                The URL is taken from the first one only.

        Keyword Args:
            metadata (dict): arbitrary user-supplied JSON data to make available
                with the application.

                The server will provide a URL ``http://applicationurl/metadata``
                which returns a JSON blob of the form:

                .. code-block:: json

                    {
                        "data": {
                            "hi": "hi",
                            "there": "there"
                        },
                        "url": "/myapp"
                    }

                The user-supplied metadata is returned as-is under the
                ``"data"`` key in the blob.

        N)r   r   r   add)selfr   r   h r#   A/tmp/pip-unpacked-wheel-f5fndrjf/bokeh/application/application.py__init__\   s
    zApplication.__init__zTuple[Handler, ...]r   c                 C  s
   t | jS )zL The ordered list of handlers this Application is configured with.

        )tupler   r!   r#   r#   r$   r      s    zApplication.handlersc                 C  s   | j S )zO Arbitrary user-supplied metadata to associate with this application.

        )r   r(   r#   r#   r$   r      s    zApplication.metadataboolc                 C  s   t dd | jD S )


        c                 s  s   | ]}|j V  qd S )N)safe_to_fork).0handlerr#   r#   r$   	<genexpr>   s     z+Application.safe_to_fork.<locals>.<genexpr>)allr   r(   r#   r#   r$   r+      s    zApplication.safe_to_forkc                 C  s   | j S )zI Path to any (optional) static resources specified by handlers.

        )r   r(   r#   r#   r$   static_path   s    zApplication.static_path)r-   r   c                 C  sf   | j | dd | jD }|d t|dkrDtdt| nt|dkr\| | _nd| _dS )z Add a handler to the pipeline used to initialize new documents.

        Args:
            handler (Handler) : a handler for this Application to use to
                process Documents

        c                 S  s   h | ]}|  qS r#   )r0   )r,   r"   r#   r#   r$   	<setcomp>   s     z"Application.add.<locals>.<setcomp>Nr   z/More than one static path requested for app: %r)	r   appendr   discardlenRuntimeErrorlistpopr   )r!   r-   Zstatic_pathsr#   r#   r$   r       s    
zApplication.addr   c                 C  s   t  }| | |S )zO Creates and initializes a document using the Application's handlers.

        )r   initialize_document)r!   docr#   r#   r$   create_document   s    
zApplication.create_document)r9   r   c                 C  sD   | j D ](}|| |jrtd||j|j qt r@|  dS )zD Fills in a new document using the Application's handlers.

        z,Error running application handler %r: %s %s N)	r   Zmodify_documentfailedlogerrorZerror_detailr   Zperform_document_validationvalidate)r!   r9   r"   r#   r#   r$   r8      s    

zApplication.initialize_documentr   )server_contextr   c                 C  s   | j D ]}|| qdS )z Invoked to execute code when a new session is created.

        This method calls ``on_server_loaded`` on each handler, in order,
        with the server context passed as the only argument.

        N)r   on_server_loadedr!   r?   r"   r#   r#   r$   r@      s    
zApplication.on_server_loadedc                 C  s   | j D ]}|| qdS )a{   Invoked to execute code when the server cleanly exits. (Before
        stopping the server's ``IOLoop``.)

        This method calls ``on_server_unloaded`` on each handler, in order,
        with the server context passed as the only argument.

        .. warning::
            In practice this code may not run, since servers are often killed
            by a signal.

        N)r   on_server_unloadedrA   r#   r#   r$   rB      s    
zApplication.on_server_unloadedr   )session_contextr   c                   s    | j D ]}||I dH  qdS )a7   Invoked to execute code when a new session is created.

        This method calls ``on_session_created`` on each handler, in order,
        with the session context passed as the only argument.

        May return a ``Future`` which will delay session creation until the
        ``Future`` completes.

        N)r   on_session_createdr!   rC   r"   r#   r#   r$   rD      s    

zApplication.on_session_createdc                   s    | j D ]}||I dH  qdS )a   Invoked to execute code when a session is destroyed.

        This method calls ``on_session_destroyed`` on each handler, in order,
        with the session context passed as the only argument.

        Afterwards, ``session_context.destroyed`` will be ``True``.

        N)r   on_session_destroyedrE   r#   r#   r$   rF      s    	
z Application.on_session_destroyedr   zDict[str, Any])requestr   c                 C  s$   i }| j D ]}||| q
|S )a#   Processes incoming HTTP request returning a dictionary of
        additional data to add to the session_context.

        Args:
            request: HTTP request

        Returns:
            A dictionary of JSON serializable data to be included on
            the session context.
        )r   updateprocess_request)r!   rG   Zrequest_datar"   r#   r#   r$   rI      s    
zApplication.process_request)__name__
__module____qualname____doc__r   __annotations__r%   propertyr   r   r+   r0   r    r:   r8   r@   rB   rD   rF   rI   r#   r#   r#   r$   r   K   s,   

$
r   c                   @  s&   e Zd ZdZeeddddZdS )r   z A harness for server-specific information and tasks related to
    collections of Bokeh sessions.

    *This base class is probably not of interest to general users.*

    zList[ServerSession]r&   c                 C  s   dS )zx ``SessionContext`` instances belonging to this application.

        *Subclasses must implement this method.*

        Nr#   r(   r#   r#   r$   sessions  s    zServerContext.sessionsN)rJ   rK   rL   rM   rO   r   rP   r#   r#   r#   r$   r     s   	r   )	metaclassc                   @  s   e Zd ZU dZded< ded< dddddd	Zeed
dddZeddddZ	eddddZ
edddddZdS )r   z A harness for server-specific information and tasks related to
    Bokeh sessions.

    *This base class is probably not of interest to general users.*

    r   _server_contextr   _idr   )r?   
session_idr   c                 C  s   || _ || _dS )r*   N)rR   rS   )r!   r?   rT   r#   r#   r$   r%   -  s    zSessionContext.__init__r)   r&   c                 C  s   dS )z If ``True``, the session has been discarded and cannot be used.

        A new session with the same ID could be created later but this instance
        will not come back to life.

        Nr#   r(   r#   r#   r$   	destroyed6  s    	zSessionContext.destroyedc                 C  s   | j S )zF The unique ID for the session associated with this context.

        )rS   r(   r#   r#   r$   idA  s    zSessionContext.idc                 C  s   | j S )z6 The server context for this session context

        )rR   r(   r#   r#   r$   r?   H  s    zSessionContext.server_contextz%Callable[[Document], Awaitable[None]]zAwaitable[None])funcr   c                 C  s   dS )a   Runs a function with the document lock held, passing the
        document to the function.

        *Subclasses must implement this method.*

        Args:
            func (callable): function that takes a single parameter (the Document)
                and returns ``None`` or a ``Future``

        Returns:
            a ``Future`` containing the result of the function

        Nr#   )r!   rW   r#   r#   r$   with_locked_documentQ  s    z#SessionContext.with_locked_documentN)rJ   rK   rL   rM   rN   r%   rO   r   rU   rV   r?   rX   r#   r#   r#   r$   r   "  s   
		r   )$rM   
__future__r   logging	getLoggerrJ   r<   abcr   r   typingr   r   r   r   r	   r
   r   r   Z
core.typesr   documentr   r   Ztornado.httputilr   Zserver.sessionr   Zhandlers.handlerr   __all__ZCallbackr   r   r   ZSessionDestroyedCallbackr#   r#   r#   r$   <module>   s&   
( D@