o
    NK&ht                     @  s  d dl mZ d dlZd dlZd dl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 d dlmZ d dl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mZ d dl m!Z! d dl"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/m0Z0 d dl1m2Z2 d dl3m4Z4m5Z5m6Z6 d dl7m8Z8 d dl9m:Z:m;Z; d dl<m=Z= d dl>m?Z?m@Z@mAZA d dlBmCZC d dlDmEZEmFZF d dlGmHZH d dlImJZJmKZKmLZLmMZM d dlNmOZO d dlPmQZQ d dlRmSZT d dlRmUZU d dlVmWZW d d lXmYZY d d!lZm[Z[ d d"l\m]Z] d d#l^m_Z_ d d$l`maZa d d%lbmcZc d d&ldmeZemfZf d d'lgmhZh d d(limjZj d d)lkmlZl d d*lmmnZn d d+lompZp e%rQd d,lqmrZr d d-l3msZs d d.ltmuZu d/Zve+eCe)d0 e)d1 f ZwG d2d3 d3e8d4ZxdS )5    )annotationsN)AbstractEventLoopCancelledErrorProtocol	all_tasksget_event_loopget_running_loopnew_event_loop)Mapping)suppresspartial)import_module)ManagerPipeget_contextget_start_methodset_start_method)BaseContext)Path)	SHUT_RDWRsocket)
SSLContext)sleep)TYPE_CHECKINGAnyCallableClassVarLiteralOptionalUnioncast)	setup_ext)get_logo)MOTD)ApplicationServerInfoModeServerStage)	SanicMeta)OS_IS_WINDOWSStartMethod)ServerKilled)Default_defaultis_atty)HTTP)get_ssl_contextprocess_to_context)SanicSSLContext)Colorsdeprecationerror_loggerlogger)setup_logging)ListenerType)Signal)try_use_uvloop)AsyncioServer)trigger_events)get_goodbye)try_windows_loop)HttpProtocol)WebSocketProtocol)serve)configure_socketremove_unix_socket)	AppLoader)WorkerManager)WorkerMultiplexer)Reloader)worker_serve)Sanic)ApplicationState)Config)zsanic-routingzsanic-testingz	sanic-ext      c                   @  s\  e Zd ZU ded< ded< ded< ded< d	ed
< ded< ded< ded< ded< eZded< dZded< dddZedddZ	dd Z
		ddddejddddd d!dddddd!dd"dddd#ddFdGZ		ddddejddddd d!dddddd!dd"dddddHddJdKZ		dddddd ddd!dddL
ddQdRZdddUdVZdddejddddded d!ddfddZd[Z	ddd]d^Z	ddd`daZeddbdcZe	dddddeZeejdfddgdhZeddidjZeddkdlZeddmdnZeddpdqZe	ddddrddydzZedd|d}Zeddd~dZ dddZ!dddZ"edd Z#edd Z$dS )StartupMixinzClassVar[dict[str, Sanic]]_app_registrystrnameboolasgirK   configz"dict[str, list[ListenerType[Any]]]	listenersrJ   statewebsocket_enabledrF   multiplexerzClassVar[bool]	test_modezClassVar[StartMethod]start_methodFSTART_METHOD_SETreturnNonec                 C  sD   | j s| jjdu st| jjtrtst  dS tr t  dS dS dS )zSet up the event loop.

        An internal method that sets up the event loop to uvloop if
        possible, or a Windows selector loop if on Windows.

        Returns:
            None
        TN)rS   rT   
USE_UVLOOP
isinstancer,   r)   r:   r>   self rb   G/var/www/html/venv/lib/python3.10/site-packages/sanic/mixins/startup.py
setup_loopb   s   	

zStartupMixin.setup_loopc                 C  s   | j S )a  Interface for interacting with the worker processes

        This is a shortcut for `app.multiplexer`. It is available only in a
        worker process using the Sanic server. It allows you to interact with
        the worker processes, such as sending messages and commands.

        See [Access to the multiplexer](/en/guide/deployment/manager#access-to-the-multiplexer) for more information.

        Returns:
            WorkerMultiplexer: The worker multiplexer instance

        Examples:
            ```python
            app.m.restart()    # restarts the worker
            app.m.terminate()  # terminates the worker
            app.m.scale(4)     # scales the number of workers to 4
        ```
        )rX   r`   rb   rb   rc   mt   s   zStartupMixin.mc                 O  s   d| j _| j|i | dS )u/  
        Try for yourself! `sanic server:app --coffee`

         ```
         ▄████████▄
        ██       ██▀▀▄
        ███████████  █
        ███████████▄▄▀
         ▀███████▀

         ```
        TN)rV   coffeerun)ra   argskwargsrb   rb   rc   make_coffee   s   zStartupMixin.make_coffeeNrL   d   Tr   )devdebugauto_reloadversionsslsockworkersprotocolbacklogregister_sys_signals
access_logunixloop
reload_dirnoisy_exceptionsmotdfast	verbositymotd_displayauto_tlssingle_processhostOptional[str]portOptional[int]rl   rm   rn   Optional[bool]ro   HTTPVersionrp   /Union[None, SSLContext, dict, str, list, tuple]rq   Optional[socket]rr   intrs   Optional[type[Protocol]]rt   ru   rv   rw   rx   Optional[AbstractEventLoop]ry   Optional[Union[list[str], str]]rz   r{   r|   r}   r~   Optional[dict[str, str]]r   r   c                C  s   | j di d|d|d|d|d|d|d|d|d	|	d
|
d|d|d|d|d|d|d|d|d|d|d|d|d| |rR| jj}n| jj}|| d dS )al  Run the HTTP Server and listen until keyboard interrupt or term signal. On termination, drain connections before closing.

        .. note::
            When you need control over running the Sanic instance, this is the method to use.
            However, in most cases the preferred method is to use the CLI command:

            ```sh
            sanic server:app`
            ```

        If you are using this method to run Sanic, make sure you do the following:

        1. Use `if __name__ == "__main__"` to guard the code.
        2. Do **NOT** define the app instance inside the `if` block.

        See [Dynamic Applications](/en/guide/deployment/app-loader) for more information about the second point.

        Args:
            host (Optional[str]): Address to host on.
            port (Optional[int]): Port to host on.
            dev (bool): Run the server in development mode.
            debug (bool): Enables debug output (slows server).
            auto_reload (Optional[bool]): Reload app whenever its source code is changed.
                Enabled by default in debug mode.
            version (HTTPVersion): HTTP Version.
            ssl (Union[None, SSLContext, dict, str, list, tuple]): SSLContext, or location of certificate and key
                for SSL encryption of worker(s).
            sock (Optional[socket]): Socket for the server to accept connections from.
            workers (int): Number of processes received before it is respected.
            protocol (Optional[Type[Protocol]]): Subclass of asyncio Protocol class.
            backlog (int): A number of unaccepted connections that the system will allow
                before refusing new connections.
            register_sys_signals (bool): Register SIG* events.
            access_log (Optional[bool]): Enables writing access logs (slows server).
            unix (Optional[str]): Unix socket to listen on instead of TCP port.
            loop (Optional[AbstractEventLoop]): AsyncIO event loop.
            reload_dir (Optional[Union[List[str], str]]): Directory to watch for code changes, if auto_reload is True.
            noisy_exceptions (Optional[bool]): Log exceptions that are normally considered to be quiet/silent.
            motd (bool): Display Message of the Day.
            fast (bool): Enable fast mode.
            verbosity (int): Verbosity level.
            motd_display (Optional[Dict[str, str]]): Customize Message of the Day display.
            auto_tls (bool): Enable automatic TLS certificate handling.
            single_process (bool): Enable single process mode.

        Returns:
            None

        Raises:
            RuntimeError: Raised when attempting to serve HTTP/3 as a secondary server.
            RuntimeError: Raised when attempting to use both `fast` and `workers`.
            RuntimeError: Raised when attempting to use `single_process` with `fast`, `workers`, or `auto_reload`.
            TypeError: Raised when attempting to use `loop` with `create_server`.
            ValueError: Raised when `PROXIES_COUNT` is negative.

        Examples:
            ```python
            from sanic import Sanic, Request, json

            app = Sanic("TestApp")


            @app.get("/")
            async def handler(request: Request):
                return json({"foo": "bar"})


            if __name__ == "__main__":
                app.run(port=9999, dev=True)
            ```
        r   r   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   r   r   )primaryNrb   )prepare	__class__serve_singlerA   )ra   r   r   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   r   r   rA   rb   rb   rc   rg      sf   
b	

zStartupMixin.run)rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   rf   r   r   rf   c                C  s  |dkr| j jrtd|rd}d}|r|du rd}|| j _| j js(t|| j _|r2|	dkr2td|r@|s<|	dks<|r@td|du rJ|sJtd	|rS| jj| |r|t	|t
r]|g}|D ]}t|}| srtd
| d | j jt| q_|durtd|du r| ||||\}}|
du r| jrtnt}
||||d D ]\}}|durt| j|| q|rd| j _z	ttd}	W n ty   t pd}	Y nw |rd| j _| j||||||||	|
|||d}| j j t!|d dS )a{  Prepares one or more Sanic applications to be served simultaneously.

        This low-level API is typically used when you need to run multiple Sanic applications at the same time. Once prepared, `Sanic.serve()` should be called in the `if __name__ == "__main__"` block.

        .. note::
            "Preparing" and "serving" with this function is equivalent to using `app.run` for a single instance. This should only be used when running multiple applications at the same time.

        Args:
            host (Optional[str], optional): Hostname to listen on. Defaults to `None`.
            port (Optional[int], optional): Port to listen on. Defaults to `None`.
            dev (bool, optional): Development mode. Defaults to `False`.
            debug (bool, optional): Debug mode. Defaults to `False`.
            auto_reload (Optional[bool], optional): Auto reload feature. Defaults to `None`.
            version (HTTPVersion, optional): HTTP version to use. Defaults to `HTTP.VERSION_1`.
            ssl (Union[None, SSLContext, dict, str, list, tuple], optional): SSL configuration. Defaults to `None`.
            sock (Optional[socket], optional): Socket to bind to. Defaults to `None`.
            workers (int, optional): Number of worker processes. Defaults to `1`.
            protocol (Optional[Type[Protocol]], optional): Custom protocol class. Defaults to `None`.
            backlog (int, optional): Maximum number of pending connections. Defaults to `100`.
            register_sys_signals (bool, optional): Register system signals. Defaults to `True`.
            access_log (Optional[bool], optional): Access log. Defaults to `None`.
            unix (Optional[str], optional): Unix socket. Defaults to `None`.
            loop (Optional[AbstractEventLoop], optional): Event loop. Defaults to `None`.
            reload_dir (Optional[Union[List[str], str]], optional): Reload directory. Defaults to `None`.
            noisy_exceptions (Optional[bool], optional): Display exceptions. Defaults to `None`.
            motd (bool, optional): Display message of the day. Defaults to `True`.
            fast (bool, optional): Fast mode. Defaults to `False`.
            verbosity (int, optional): Verbosity level. Defaults to `0`.
            motd_display (Optional[Dict[str, str]], optional): Custom MOTD display. Defaults to `None`.
            coffee (bool, optional): Coffee mode. Defaults to `False`.
            auto_tls (bool, optional): Auto TLS. Defaults to `False`.
            single_process (bool, optional): Single process mode. Defaults to `False`.

        Raises:
            RuntimeError: Raised when attempting to serve HTTP/3 as a secondary server.
            RuntimeError: Raised when attempting to use both `fast` and `workers`.
            RuntimeError: Raised when attempting to use `single_process` with `fast`, `workers`, or `auto_reload`.
            TypeError: Raised when attempting to use `loop` with `create_server`.
            ValueError: Raised when `PROXIES_COUNT` is negative.

        Examples:
            ```python
            if __name__ == "__main__":
                app.prepare()
                app.serve()
            ```
        rM   zServing HTTP/3 instances as a secondary server is not supported. There can only be a single HTTP/3 worker and it must be the first instance prepared.TNrL   z+You cannot use both fast=True and workers=XzASingle process cannot be run with multiple workers or auto-reloadFzOCannot run Sanic.serve with register_sys_signals=False. Use Sanic.serve_single.z
Directory z could not be locatedzloop is not a valid argument. To use an existing loop, change to create_server().
See more: https://sanic.readthedocs.io/en/latest/sanic/deploying.html#asynchronous-support)
ACCESS_LOGAUTO_RELOADr$   NOISY_EXCEPTIONSr   )r   r   rm   ro   rp   rq   rw   rr   rs   rt   ru   r   )settings)"rV   server_infoRuntimeErrorr}   rn   rR   rT   MOTD_DISPLAYupdater_   rP   r   is_dirr6   warningreload_dirsadd	TypeErrorget_addressrW   r@   r?   itemssetattrr|   lenossched_getaffinityAttributeError	cpu_countrf   _helperappendr%   )ra   r   r   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   rf   r   r   	directorydirec	attributevalueserver_settingsrb   rb   rc   r     s   K


zStartupMixin.prepare)
rm   rp   rq   rs   rt   rv   rw   return_asyncio_serverasyncio_server_kwargsrz   r   r   Optional[dict[str, Any]]Optional[AsyncioServer]c       
           s   |du r|  || \}}\}}|du r| jrtnt}||d D ]\}}|dur2t| j|| q#|
s<d}
tdd | j||||||	t	 |||
d
}t
| jjtsXtd |dd}|d	d}|sh|rmtd
 tdd|i|I dH S )a
  
        Low level API for creating a Sanic Server instance.

        This method will create a Sanic Server instance, but will not start
        it. This is useful for integrating Sanic into other systems. But, you
        should take caution when using it as it is a low level API and does
        not perform any of the lifecycle events.

        .. note::
            This does not support multiprocessing and is not the preferred
            way to run a Sanic application. Proceed with caution.

        You will need to start the server yourself as shown in the example
        below. You are responsible for the lifecycle of the server, including
        app startup using `await app.startup()`. No events will be triggered
        for you, so you will need to trigger them yourself if wanted.

        Args:
            host (Optional[str]): Address to host on.
            port (Optional[int]): Port to host on.
            debug (bool): Enables debug output (slows server).
            ssl (Union[None, SSLContext, dict, str, list, tuple]): SSLContext,
                or location of certificate and key for SSL encryption
                of worker(s).
            sock (Optional[socket]): Socket for the server to accept
                connections from.
            protocol (Optional[Type[Protocol]]): Subclass of
                `asyncio.Protocol` class.
            backlog (int): Number of unaccepted connections that the system
                will allow before refusing new connections.
            access_log (Optional[bool]): Enables writing access logs
                (slows server).
            return_asyncio_server (bool): _DEPRECATED_
            asyncio_server_kwargs (Optional[Dict[str, Any]]): Key-value
                arguments for asyncio/uvloop `create_server` method.
            noisy_exceptions (Optional[bool]): Log exceptions that are normally
                considered to be quiet/silent.

        Returns:
            Optional[AsyncioServer]: AsyncioServer if `return_asyncio_server`
                is `True` else `None`.

        Examples:
            ```python
            import asyncio
            import uvloop
            from sanic import Sanic, response


            app = Sanic("Example")


            @app.route("/")
            async def test(request):
                return response.json({"answer": "42"})


            async def main():
                server = await app.create_server()
                await server.startup()
                await server.serve_forever()


            if __name__ == "__main__":
                asyncio.set_event_loop(uvloop.new_event_loop())
                asyncio.run(main())
            ```
        Nr   r   Tz\The `return_asyncio_server` argument is deprecated and ignored. It will be removed in v24.3.gL8@)
r   r   rm   rp   rq   rw   rx   rs   rt   	run_asynczYou are trying to change the uvloop configuration, but this is only effective when using the run(...) method. When using the create_server(...) method Sanic will use the already existing loop.
main_start	main_stopzKListener events for the main process are not available with create_server()r   rb   )r   rW   r@   r?   r   r   rT   r4   r   r   r_   r^   r,   r5   r   popr6   rA   )ra   r   r   rm   rp   rq   rs   rt   rv   rw   r   r   rz   r   r   r   r   r   rb   rb   rc   create_server  s^   U
zStartupMixin.create_server	terminate
unregisterc              	   C  s   |rt | dr| j  | jjtjurB| jdd t D ] }t	t
 | dkr-|  W d   n1 s7w   Y  qt   |rL| j|  dS dS )a;  This kills the Sanic server, cleaning up after itself.

        Args:
            terminate (bool): Force kill all requests immediately without
                allowing them to finish processing.
            unregister (bool): Unregister the app from the global registry.

        Returns:
            None
        rX   r   )timeout	RunServerN)hasattrrX   r   rV   stager'   STOPPEDshutdown_tasksr   r   r   get_namecancelr   stopr   unregister_app)ra   r   r   taskrb   rb   rc   r   `  s   



zStartupMixin.stoptype[Protocol]r   dict[str, Any]c                   st   j jr j jdk rtd jjs|rtjntj j_t	 jj j j
 t|tr.t|}t|}|tju s9|rEtr@tt  t |}|pHd j_|pNd j_| j_| j_| j_| j_|
|||||| t |	||d} j|d t r jjstjdst !t"j# dt"j$  dD ]\}}} j%| & }|r|'   fd	d
|D }|||< q|rd|d< |S )z2Helper function used by `run` and `create_server`.r   znPROXIES_COUNT cannot be negative. https://sanic.readthedocs.io/en/latest/sanic/config.html#proxy-configuration )rs   r   r   ro   rq   rw   rp   appsignalrx   ru   rt   )r   SANIC_IGNORE_PRODUCTION_WARNINGztSanic is running in PRODUCTION mode. Consider using '--debug' or '--dev' while actively developing your application.))main_process_startr   F)main_process_stopr   Tc                   s   g | ]}t | qS rb   r   ).0listenerr`   rb   rc   
<listcomp>  s    z(StartupMixin._helper.<locals>.<listcomp>Tr   )(rT   PROXIES_COUNT
ValueErrorrV   is_debugr&   DEBUG
PRODUCTIONmoder7   NO_COLORr_   r   r/   r1   	VERSION_3r   r!   rI   r0   r   r   rr   rp   rw   rq   ServerSignalr{   r.   r   environgetr5   r   r3   YELLOWENDrU   copyreverse)ra   r   r   rm   ro   rp   rq   rw   rr   rx   rs   rt   ru   r   r   r   
event_namesettings_namer   rU   rb   r`   rc   r   x  sl   




zStartupMixin._helperr   c                 C  sz   t jdst jdst jdst jdrdS | |}| jjr;t| jjd}| 	|\}}t
|||| dS dS )ab  Outputs the message of the day (MOTD).

        It generally can only be called once per process, and is usually
        called by the `run` method in the main process.

        Args:
            server_settings (Optional[Dict[str, Any]], optional): Settings for
                the server. Defaults to `None`.

        Returns:
            None
        SANIC_WORKER_NAMESANIC_MOTD_OUTPUTSANIC_WORKER_PROCESSSANIC_SERVER_RUNNINGN)rf   )r   r   r   get_server_locationrT   r$   r#   rV   rf   get_motd_dataoutput)ra   r   serve_locationlogodisplayextrarb   rb   rc   r{     s   




zStartupMixin.motd%tuple[dict[str, Any], dict[str, Any]]c              	   C  sr  | j j dg}| j jr|d | j jr|d n| j jdkr'|d n|d| j j d |rBd| j j|d	  f}n| jrGdnd
}| j	d||t
 t

 d}i }| jjrzd}| j jrv|ddgdd | j jD 7 }||d< g }tD ]"}|dd}	zt|	}
|| d|
j  W q~ ty   Y q~w |rd||d< | jjr|| jj ||fS )aZ  Retrieves the message of the day (MOTD) data.

        Args:
            server_settings (Optional[Dict[str, Any]], optional): Settings for
                the server. Defaults to `None`.

        Returns:
            Tuple[Dict[str, Any], Dict[str, Any]]: A tuple containing two
                dictionaries with the relevant MOTD data.
        ,z
goin' fastASGIrL   zsingle workerzw/ z workersz, ro   unknown )r   r   serverpythonplatformenabledr   c                 s  s    | ]	}t | V  qd S N)rP   absolute)r   pathrb   rb   rc   	<genexpr>"  s
    

z-StartupMixin.get_motd_data.<locals>.<genexpr>zauto-reload-_z==packages)rV   r   r|   r   rS   rr   joinr   r   rQ   r   python_versionrT   r   r   SANIC_PACKAGESreplacer   __version__ImportErrorr   r   )ra   r   r   r   r   r   reload_displayr   package_namemodule_namemodulerb   rb   rc   r     s`   

	zStartupMixin.get_motd_datac                 C  sH   z| j jd j}| |W S  ty#   | jrdnd}d| d Y S w )z^Retrieve the server location.

        Returns:
            str: The server location.
        r   r   r   zhttp://<>)rV   r   r   r   
IndexErrorrS   )ra   r   locationrb   rb   rc   r   ;  s   zStartupMixin.serve_locationc                 C  s   d}d}| s|S | d }| d }|  ddurd}|  dr)| d  d	| d
}n|  dr7| d  ^}}}|sS|rS|rSd|v rGd| dn|}| d| d| }|S )a  Using the server settings, retrieve the server location.

        Args:
            server_settings (Optional[Dict[str, Any]], optional): Settings for
                the server. Defaults to `None`.

        Returns:
            str: The server location.
        r   httpr   r   rp   Nhttpsrw   r   z://...rq   :[]z://)r   getsockname)r   r   protor   r   r   display_hostrb   rb   rc   r   I  s    

z StartupMixin.get_server_locationtuple[str, int]c                 C  s(   | pd} |p|dks|rdnd}| |fS )aK  Retrieve the host address and port, with default values based on the given parameters.

        Args:
            host (Optional[str]): Host IP or FQDN for the service to use. Defaults to `"127.0.0.1"`.
            port (Optional[int]): Port number. Defaults to `8443` if version is 3 or `auto_tls=True`, else `8000`
            version (HTTPVersion, optional): HTTP Version. Defaults to `HTTP.VERSION_1` (HTTP/1.1).
            auto_tls (bool, optional): Automatic TLS flag. Defaults to `False`.

        Returns:
            Tuple[str, int]: Tuple containing the host and port
        z	127.0.0.1rM   i   i@  rb   )r   r   ro   r   rb   rb   rc   r   l  s   zStartupMixin.get_addressc                 C  s   t dd | j D S )zCheck if any applications have auto-reload enabled.

        Returns:
            bool: `True` if any applications have auto-reload enabled, else
                `False`.
        c                 s      | ]}|j jV  qd S r   )rV   rn   r   r   rb   rb   rc   r         z2StartupMixin.should_auto_reload.<locals>.<genexpr>)anyrO   valuesclsrb   rb   rc   should_auto_reload  s   zStartupMixin.should_auto_reloadc                 C  s   t | jts	| jS dS )Nspawn)r_   rZ   r,   r  rb   rb   rc   _get_startup_method  s
   
z StartupMixin._get_startup_methodc              	   C  st   | j r| jsd S |  }z	t|| jd W n ty4   t }| }||kr3td| d| dd  w d| _ d S )N)forceStart method '' was requested, but '' was already set.
For more information, see: https://sanic.dev/en/guide/running/manager.html#overcoming-a-coderuntimeerrorcodeT)r[   rY   r  r   r   r   r   )r  methodctxactualrb   rb   rc   _set_startup_method  s"   
z StartupMixin._set_startup_methodr   c                 C  s@   |   }td| t }||krtd| d| dd t S )Nz+Creating multiprocessing context using '%s'r  r  r  )r  r6   rm   r   r   r   )r  r   r"  rb   rb   rc   _get_context  s   zStartupMixin._get_context)
app_loaderfactoryr   Optional[Sanic]r%  Optional[AppLoader]r&  Optional[Callable[[], Sanic]]c          !      C  s  |    dtjd< t| j }|r| }n.|s3|r| }|s3z|d }W n ty2   tddw |j	j
sD|D ]}|j	j
  q9dS z|j	j
d }W n ty]   td|j ddw g }t }dd	i}	t| d}
zz\|jd
d |jdd |jd}|jd}|jd}|  t }t||| dd dd |D D }d|jd< td\}}| }	i |j||	d}|s|rt|d}n
tt| j|jd}|j|d< ||d< i |d< |j|j	j|j	jd|jj|jj d|j!j"d|d< |D ]'}g |d |j< |j	j
D ]}dd |j# D |_|d |j $| qq |d}t%|t&r8|j'|d< t(|j	j)t*|| + ||f|	}| , rh|j	j-j.d d! |D  }t/|d||}|j0d"|i d#d$ d}|jj1r|2 \}}d%d |d& 3d'D }t4d(}d)|j5 }i ||g||d*}|6|||	|jj7|jj8|jj9|jj:|jj;}|j0d+|i d#d$ ||_<||_=|jd, }t||| |>  W n t?y   d-}
Y n t@y   |j}tABd.  w W tCDd/ |D ]}|j	j
  |jEF  |jGF  q|D ]}z|HtI W n
 tJy   Y nw |K  qg }t||| |K  | L  | M  d0}| N|	rVtOd1 |d-8 }|dkrPtAPd2 n| N|	s=|H  |d3} | rftQ|  tCRtS  ntCDd/ |D ]}|j	j
  |jEF  |jGF  qt|D ]}z|HtI W n
 tJy   Y nw |K  qg }t||| |K  | L  | M  d0}| N|	rtOd1 |d-8 }|dkrtAPd2 n| N|	s|H  |d3} | rtQ|  tCRtS  w |
rtT|
 dS dS )4a&  Serve one or more Sanic applications.

        This is the main entry point for running Sanic applications. It
        should be called in the `if __name__ == "__main__"` block.

        Args:
            primary (Optional[Sanic], optional): The primary Sanic application
                to serve. Defaults to `None`.
            app_loader (Optional[AppLoader], optional): An AppLoader instance
                to use for loading applications. Defaults to `None`.
            factory (Optional[Callable[[], Sanic]], optional): A factory
                function to use for loading applications. Defaults to `None`.

        Raises:
            RuntimeError: Raised when no applications are found.
            RuntimeError: Raised when no server information is found for the
                primary application.
            RuntimeError: Raised when attempting to use `loop` with
                `create_server`.
            RuntimeError: Raised when attempting to use `single_process` with
                `fast`, `workers`, or `auto_reload`.
            RuntimeError: Raised when attempting to serve HTTP/3 as a
                secondary server.
            RuntimeError: Raised when attempting to use both `fast` and
                `workers`.
            TypeError: Raised when attempting to use `loop` with
                `create_server`.
            ValueError: Raised when `PROXIES_COUNT` is negative.

        Examples:
            ```python
            if __name__ == "__main__":
                app.prepare()
                Sanic.serve()
            ```
        truer   r   Did not find any applications.Nz No server information found for z+. Perhaps you need to run app.prepare(...)?rV   NONEr   r   r   r   r   c                 S  s   g | ]}|r|qS rb   rb   )r   rq   rb   rb   rc   r     s    z&StartupMixin.serve.<locals>.<listcomp>c                 S  s$   g | ]}|j jD ]}t|jqqS rb   )rV   r   rB   r   )r   r   r   rb   rb   rc   r     s    Trun_multiple)monitor_publisherworker_state)r&  app_namer%  r   )r}   r   r   )rn   rV   rT   
shared_ctxpassthruc                 S     i | ]\}}|d vr||qS ))r   r   r   rp   rb   r   kvrb   rb   rc   
<dictcomp>;  
    z&StartupMixin.serve.<locals>.<dictcomp>rp   c                 s  r  r   )rV   r   r  rb   rb   rc   r   Q  r  z%StartupMixin.serve.<locals>.<genexpr>rG   F)	transientc                 S  s   g | ]}|  qS rb   )strip)r   pkgrb   rb   rc   r   Y  s    r   r   saniczsanic==)r   r   	Inspectormain_process_readyrL   +Experienced exception while trying to serveServer Stoppedrk   g?z?Worker shutdown timed out. Some processes may still be running.rw   )Ur#  r   r   listrO   r  loadr  r   rV   r   clearrQ   r   r"   r   r   rU   r   rd   r	   r<   r   dictrD   r   get_apprn   r}   r   rT   r   r   r1  __dict__r   r   r_   r2   r<  rE   rr   rH   r$  r  r   unionrG   manage	INSPECTORr   splitr   r   inspector_classINSPECTOR_HOSTINSPECTOR_PORTINSPECTOR_API_KEYINSPECTOR_TLS_KEYINSPECTOR_TLS_CERT
_inspector_managerrg   r+   BaseExceptionr5   	exceptionr6   inforouterresetsignal_routershutdownr   OSErrorclose_cleanup_env_vars_cleanup_apps_get_process_statesr   r   rC   rm   r=   _exit)!r  r   r%  r&  appsr   primary_server_infosockssync_managerr/  	exit_coder   r   rx   monitor_submonitor_pubri   r   rp   managerr   reloader	inspectorr   r   r   r  sanic_versionapp_inforeadyrq   limitrw   rb   rb   rc   rA     s  ,

	










	



	
zStartupMixin.serve	list[str]c                   s    fdd|   D S )Nc                   s&   g | ]}| d   r dvr qS )rV   )
TERMINATEDFAILED	COMPLETEDr,  )r   )r   srV   rb   rc   r     s    z4StartupMixin._get_process_states.<locals>.<listcomp>)r  )r/  rb   rs  rc   r^    s   
z StartupMixin._get_process_statesc              	   C  s  dt jd< t| j }|s z|d }W n ty   tdw |jjs1|D ]}|jj	  q&dS |jjd }|
t|j|d dd |j D }|j|d	< d|d
< t|}i |d< g |d |j< |jjD ]}dd |j D |_|d |j | qgzDztdddi| W n ty   td  w W td |D ]}|jj	  |j  |j  q|r|  |   |   dS td |D ]}|jj	  |j  |j  q|r|  |   |   w )a  Serve a single process of a Sanic application.

        Similar to `serve`, but only serves a single process. When used,
        certain features are disabled, such as `fast`, `workers`,
        `multiplexer`, `auto_reload`, and the Inspector. It is almost
        never needed to use this method directly. Instead, you should
        use the CLI:

        ```sh
        sanic app.sanic:app --single-process
        ```

        Or, if you need to do it programmatically, you should use the
        `single_process` argument of `run`:

        ```python
        app.run(single_process=True)
        ```

        Args:
            primary (Optional[Sanic], optional): The primary Sanic application
                to serve. Defaults to `None`.

        Raises:
            RuntimeError: Raised when no applications are found.
            RuntimeError: Raised when no server information is found for the
                primary application.
            RuntimeError: Raised when attempting to serve HTTP/3 as a
                secondary server.
            RuntimeError: Raised when attempting to use both `fast` and
                `workers`.
            ValueError: Raised when `PROXIES_COUNT` is negative.
        r*  r   r   r+  N)r`  c                 S  r3  )r   r   r   rb   r4  rb   rb   rc   r7    s    z-StartupMixin.serve_single.<locals>.<dictcomp>r0  r%  r   c                 S  r3  rt  rb   r4  rb   rb   rc   r7    r8  r.  r?  r@  rb   )r   r   rA  rO   r  r  r   rV   r   rC  before_server_startr   _start_serversr   r   rQ   rB   r   rH   rS  r5   rT  r6   rU  rV  rW  rX  r[  r\  r]  )r  r   r`  r   ra  ri   rq   r   rb   rb   rc   r     sl   
#






zStartupMixin.serve_singlerI   r`  list[Sanic]c                   s  |D ]}|j |j urB|jj|jjkrB|jjrBdt| d|jj dt| d|jj d	}t r;dtj|tj	g}t
j|dd |jjD ]}|jtjurd	|j_g |jd
g |jdg }|rst
dt| dt|  |jd s~t |jd< i |jdt|jjd d}d|vr||d< ztdi |I d H |_W n6 ty }	 z*d}
t|	}t rtj|
tj|tj	g}n|
|g}d|}t
j|dd W Y d }	~	qFd }	~	ww |j| ||dd qFqd S )NzThe primary application z is running with zS worker(s). All application instances will run with the same number. You requested z to run with zF worker(s), which will be ignored in favor of the primary application.r   T)exc_infoFr   r   zSanic found z listener(s) on secondary applications attached to the main process. These will be ignored since main process listeners can only be attached to your primary application: rx   rL   )r   
reuse_portr   z?An OSError was detected on startup. The encountered error was: r   )rQ   rb   )rQ   rV   rr   r   reprr.   r   r3   r   r   r5   r   r   r'   SERVINGr   r   r   r   r   rR   rA   r   rZ  rP   REDadd_task_run_server)ra   r   r   r`  r   messager   handlers
serve_argsefirst_messagesecond_messagemessage_partsrb   rb   rc   rv    s   
	
zStartupMixin._start_serversr   r   r%   c                   s   zqz4|j s
td|jjtju r-tj|_|j  I d H  |j  I d H  |j 	 I d H  |j 
 I d H  W n( ty^   |j sDtd|j  I d H  |j  I d H  |j  I d H  Y nw W tj|_d |_ d S W tj|_d |_ d S tj|_d |_ w )NzCould not locate AsyncioServer)r   r   rV   r   r'   r   r{  startupbefore_startafter_startserve_foreverr   before_stopr[  
after_stop)ra   r   r   rb   rb   rc   r~  a  s2   


zStartupMixin._run_serverc               	   C  s0   d} | D ]}zt j|= W q ty   Y qw d S )N)SANIC_RELOADER_PROCESSr   r   r   r   r   )r   r   KeyError)	variablesvarrb   rb   rc   r\  }  s   zStartupMixin._cleanup_env_varsc                 C  s4   | j  D ]}|jj  |j  |j  qd S r   )rO   r  rV   r   rC  rV  rW  rX  )r  r   rb   rb   rc   r]    s
   
zStartupMixin._cleanup_apps)r\   r]   )r\   rF   )NN)0r   r   r   r   rl   rR   rm   rR   rn   r   ro   r   rp   r   rq   r   rr   r   rs   r   rt   r   ru   rR   rv   r   rw   r   rx   r   ry   r   rz   r   r{   rR   r|   rR   r}   r   r~   r   r   rR   r   rR   r\   r]   )2r   r   r   r   rl   rR   rm   rR   rn   r   ro   r   rp   r   rq   r   rr   r   rs   r   rt   r   ru   rR   rv   r   rw   r   rx   r   ry   r   rz   r   r{   rR   r|   rR   r}   r   r~   r   rf   rR   r   rR   r   rR   r\   r]   )r   r   r   r   rm   rR   rp   r   rq   r   rs   r   rt   r   rv   r   rw   r   r   rR   r   r   rz   r   r\   r   )TF)r   rR   r   rR   r\   r]   )r   r   r   r   rm   rR   ro   r   rp   r   rq   r   rw   r   rr   r   rx   r   rs   r   rt   r   ru   rR   r   rR   r   rR   r\   r   r   )r   r   r\   r]   )r   r   r\   r   )r\   rP   )r   r   r\   rP   )
r   r   r   r   ro   r   r   rR   r\   r  )r\   rR   )r\   r   )r   r'  r%  r(  r&  r)  r\   r]   )r\   rn  )r   r'  r\   r]   )r   rI   r`  rw  r\   r]   )r   rN   r   r%   r\   r]   )%__name__
__module____qualname____annotations__r-   rZ   r[   rd   propertyre   rj   r/   	VERSION_1rg   r   r   r   r?   r   r{   r   r   staticmethodr   r   classmethodr  r  r#  r$  rA   r^  r   rv  r~  r\  r]  rb   rb   rb   rc   rN   T   s  
 
  9 ]J"	 o

_
Q
rN   )	metaclass)y
__future__r   r   r   asyncior   r   r   r   r   r   r	   collections.abcr
   
contextlibr   	functoolsr   	importlibr   multiprocessingr   r   r   r   r   multiprocessing.contextr   pathlibr   r   r   rp   r   timer   typingr   r   r   r   r   r   r    r!   sanic.application.extr"   sanic.application.logor#   sanic.application.motdr$   sanic.application.stater%   r&   r'   sanic.base.metar(   sanic.compatr)   r*   sanic.exceptionsr+   sanic.helpersr,   r-   r.   sanic.http.constantsr/   sanic.http.tlsr0   r1   sanic.http.tls.contextr2   	sanic.logr3   r4   r5   r6   sanic.logging.setupr7   sanic.models.handler_typesr8   sanic.serverr9   r   r:   sanic.server.async_serverr;   sanic.server.eventsr<   sanic.server.goodbyer=   sanic.server.loopr>   $sanic.server.protocols.http_protocolr?   )sanic.server.protocols.websocket_protocolr@   sanic.server.runnersrA   sanic.server.socketrB   rC   sanic.worker.loaderrD   sanic.worker.managerrE   sanic.worker.multiplexerrF   sanic.worker.reloaderrG   sanic.worker.serverH   r<  rI   rJ   sanic.configrK   r   r   rN   rb   rb   rb   rc   <module>   sf    $	(