2021-03-14 08:09:07 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
|
2021-11-14 21:21:14 +00:00
|
|
|
from enum import Enum
|
2021-03-14 08:09:07 +00:00
|
|
|
from inspect import isawaitable
|
2021-12-23 23:27:54 +00:00
|
|
|
from typing import Any, Dict, List, Optional, Tuple, Union, cast
|
2021-03-14 08:09:07 +00:00
|
|
|
|
2022-06-27 09:19:26 +01:00
|
|
|
from sanic_routing import BaseRouter, Route, RouteGroup
|
|
|
|
from sanic_routing.exceptions import NotFound
|
|
|
|
from sanic_routing.utils import path_to_parts
|
2021-03-14 08:09:07 +00:00
|
|
|
|
|
|
|
from sanic.exceptions import InvalidSignal
|
2021-08-05 20:55:42 +01:00
|
|
|
from sanic.log import error_logger, logger
|
2021-03-14 08:09:07 +00:00
|
|
|
from sanic.models.handler_types import SignalHandler
|
|
|
|
|
|
|
|
|
2021-11-14 21:21:14 +00:00
|
|
|
class Event(Enum):
|
|
|
|
SERVER_INIT_AFTER = "server.init.after"
|
|
|
|
SERVER_INIT_BEFORE = "server.init.before"
|
|
|
|
SERVER_SHUTDOWN_AFTER = "server.shutdown.after"
|
|
|
|
SERVER_SHUTDOWN_BEFORE = "server.shutdown.before"
|
|
|
|
HTTP_LIFECYCLE_BEGIN = "http.lifecycle.begin"
|
|
|
|
HTTP_LIFECYCLE_COMPLETE = "http.lifecycle.complete"
|
|
|
|
HTTP_LIFECYCLE_EXCEPTION = "http.lifecycle.exception"
|
|
|
|
HTTP_LIFECYCLE_HANDLE = "http.lifecycle.handle"
|
|
|
|
HTTP_LIFECYCLE_READ_BODY = "http.lifecycle.read_body"
|
|
|
|
HTTP_LIFECYCLE_READ_HEAD = "http.lifecycle.read_head"
|
|
|
|
HTTP_LIFECYCLE_REQUEST = "http.lifecycle.request"
|
|
|
|
HTTP_LIFECYCLE_RESPONSE = "http.lifecycle.response"
|
|
|
|
HTTP_ROUTING_AFTER = "http.routing.after"
|
|
|
|
HTTP_ROUTING_BEFORE = "http.routing.before"
|
2022-09-15 13:49:21 +01:00
|
|
|
HTTP_HANDLER_AFTER = "http.handler.after"
|
|
|
|
HTTP_HANDLER_BEFORE = "http.handler.before"
|
2021-11-14 21:21:14 +00:00
|
|
|
HTTP_LIFECYCLE_SEND = "http.lifecycle.send"
|
|
|
|
HTTP_MIDDLEWARE_AFTER = "http.middleware.after"
|
|
|
|
HTTP_MIDDLEWARE_BEFORE = "http.middleware.before"
|
|
|
|
|
|
|
|
|
2021-08-05 20:55:42 +01:00
|
|
|
RESERVED_NAMESPACES = {
|
|
|
|
"server": (
|
2021-11-14 21:21:14 +00:00
|
|
|
Event.SERVER_INIT_AFTER.value,
|
|
|
|
Event.SERVER_INIT_BEFORE.value,
|
|
|
|
Event.SERVER_SHUTDOWN_AFTER.value,
|
|
|
|
Event.SERVER_SHUTDOWN_BEFORE.value,
|
2021-08-05 20:55:42 +01:00
|
|
|
),
|
|
|
|
"http": (
|
2021-11-14 21:21:14 +00:00
|
|
|
Event.HTTP_LIFECYCLE_BEGIN.value,
|
|
|
|
Event.HTTP_LIFECYCLE_COMPLETE.value,
|
|
|
|
Event.HTTP_LIFECYCLE_EXCEPTION.value,
|
|
|
|
Event.HTTP_LIFECYCLE_HANDLE.value,
|
|
|
|
Event.HTTP_LIFECYCLE_READ_BODY.value,
|
|
|
|
Event.HTTP_LIFECYCLE_READ_HEAD.value,
|
|
|
|
Event.HTTP_LIFECYCLE_REQUEST.value,
|
|
|
|
Event.HTTP_LIFECYCLE_RESPONSE.value,
|
|
|
|
Event.HTTP_ROUTING_AFTER.value,
|
|
|
|
Event.HTTP_ROUTING_BEFORE.value,
|
2022-09-15 13:49:21 +01:00
|
|
|
Event.HTTP_HANDLER_AFTER.value,
|
|
|
|
Event.HTTP_HANDLER_BEFORE.value,
|
2021-11-14 21:21:14 +00:00
|
|
|
Event.HTTP_LIFECYCLE_SEND.value,
|
|
|
|
Event.HTTP_MIDDLEWARE_AFTER.value,
|
|
|
|
Event.HTTP_MIDDLEWARE_BEFORE.value,
|
2021-08-05 20:55:42 +01:00
|
|
|
),
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def _blank():
|
|
|
|
...
|
2021-03-14 13:21:59 +00:00
|
|
|
|
|
|
|
|
2021-03-14 08:09:07 +00:00
|
|
|
class Signal(Route):
|
2021-04-19 22:53:42 +01:00
|
|
|
...
|
|
|
|
|
|
|
|
|
|
|
|
class SignalGroup(RouteGroup):
|
|
|
|
...
|
2021-03-14 08:09:07 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SignalRouter(BaseRouter):
|
|
|
|
def __init__(self) -> None:
|
|
|
|
super().__init__(
|
|
|
|
delimiter=".",
|
|
|
|
route_class=Signal,
|
2021-04-19 22:53:42 +01:00
|
|
|
group_class=SignalGroup,
|
2021-03-14 08:09:07 +00:00
|
|
|
stacking=True,
|
|
|
|
)
|
2022-03-24 11:52:05 +00:00
|
|
|
self.allow_fail_builtin = True
|
2021-03-14 08:09:07 +00:00
|
|
|
self.ctx.loop = None
|
|
|
|
|
|
|
|
def get( # type: ignore
|
|
|
|
self,
|
|
|
|
event: str,
|
|
|
|
condition: Optional[Dict[str, str]] = None,
|
|
|
|
):
|
|
|
|
extra = condition or {}
|
|
|
|
try:
|
2021-04-19 22:53:42 +01:00
|
|
|
group, param_basket = self.find_route(
|
|
|
|
f".{event}",
|
|
|
|
self.DEFAULT_METHOD,
|
|
|
|
self,
|
2021-06-21 13:10:26 +01:00
|
|
|
{"__params__": {}, "__matches__": {}},
|
2021-04-19 22:53:42 +01:00
|
|
|
extra=extra,
|
|
|
|
)
|
2021-03-14 08:09:07 +00:00
|
|
|
except NotFound:
|
|
|
|
message = "Could not find signal %s"
|
|
|
|
terms: List[Union[str, Optional[Dict[str, str]]]] = [event]
|
|
|
|
if extra:
|
|
|
|
message += " with %s"
|
|
|
|
terms.append(extra)
|
|
|
|
raise NotFound(message % tuple(terms))
|
|
|
|
|
2021-08-05 20:55:42 +01:00
|
|
|
# Regex routes evaluate and can extract params directly. They are set
|
|
|
|
# on param_basket["__params__"]
|
2021-06-21 13:10:26 +01:00
|
|
|
params = param_basket["__params__"]
|
|
|
|
if not params:
|
2021-08-05 20:55:42 +01:00
|
|
|
# If param_basket["__params__"] does not exist, we might have
|
|
|
|
# param_basket["__matches__"], which are indexed based matches
|
|
|
|
# on path segments. They should already be cast types.
|
2021-06-21 13:10:26 +01:00
|
|
|
params = {
|
|
|
|
param.name: param_basket["__matches__"][idx]
|
|
|
|
for idx, param in group.params.items()
|
|
|
|
}
|
|
|
|
|
2021-04-19 22:53:42 +01:00
|
|
|
return group, [route.handler for route in group], params
|
|
|
|
|
2021-03-14 08:09:07 +00:00
|
|
|
async def _dispatch(
|
|
|
|
self,
|
|
|
|
event: str,
|
|
|
|
context: Optional[Dict[str, Any]] = None,
|
|
|
|
condition: Optional[Dict[str, str]] = None,
|
2021-08-05 20:55:42 +01:00
|
|
|
fail_not_found: bool = True,
|
|
|
|
reverse: bool = False,
|
|
|
|
) -> Any:
|
|
|
|
try:
|
|
|
|
group, handlers, params = self.get(event, condition=condition)
|
|
|
|
except NotFound as e:
|
2022-03-24 11:52:05 +00:00
|
|
|
is_reserved = event.split(".", 1)[0] in RESERVED_NAMESPACES
|
|
|
|
if fail_not_found and (not is_reserved or self.allow_fail_builtin):
|
2021-08-05 20:55:42 +01:00
|
|
|
raise e
|
|
|
|
else:
|
2021-11-07 19:39:03 +00:00
|
|
|
if self.ctx.app.debug and self.ctx.app.state.verbosity >= 1:
|
2021-08-05 20:55:42 +01:00
|
|
|
error_logger.warning(str(e))
|
|
|
|
return None
|
2021-03-14 08:09:07 +00:00
|
|
|
|
2021-04-19 22:53:42 +01:00
|
|
|
events = [signal.ctx.event for signal in group]
|
|
|
|
for signal_event in events:
|
|
|
|
signal_event.set()
|
2021-03-14 08:09:07 +00:00
|
|
|
if context:
|
|
|
|
params.update(context)
|
|
|
|
|
2021-12-23 23:27:54 +00:00
|
|
|
signals = group.routes
|
2021-08-05 20:55:42 +01:00
|
|
|
if not reverse:
|
2021-12-23 23:27:54 +00:00
|
|
|
signals = signals[::-1]
|
2021-03-14 08:09:07 +00:00
|
|
|
try:
|
2021-12-23 23:27:54 +00:00
|
|
|
for signal in signals:
|
|
|
|
params.pop("__trigger__", None)
|
2022-09-18 15:17:23 +01:00
|
|
|
requirements = getattr(
|
|
|
|
signal.handler, "__requirements__", None
|
|
|
|
)
|
2021-12-23 23:27:54 +00:00
|
|
|
if (
|
|
|
|
(condition is None and signal.ctx.exclusive is False)
|
2022-09-18 15:17:23 +01:00
|
|
|
or (condition is None and not requirements)
|
|
|
|
or (condition == requirements)
|
2021-12-23 23:27:54 +00:00
|
|
|
) and (signal.ctx.trigger or event == signal.ctx.definition):
|
|
|
|
maybe_coroutine = signal.handler(**params)
|
2021-03-14 08:09:07 +00:00
|
|
|
if isawaitable(maybe_coroutine):
|
2021-08-05 20:55:42 +01:00
|
|
|
retval = await maybe_coroutine
|
|
|
|
if retval:
|
|
|
|
return retval
|
|
|
|
elif maybe_coroutine:
|
|
|
|
return maybe_coroutine
|
|
|
|
return None
|
2021-03-14 08:09:07 +00:00
|
|
|
finally:
|
2021-04-19 22:53:42 +01:00
|
|
|
for signal_event in events:
|
|
|
|
signal_event.clear()
|
2021-03-14 08:09:07 +00:00
|
|
|
|
|
|
|
async def dispatch(
|
|
|
|
self,
|
|
|
|
event: str,
|
|
|
|
*,
|
|
|
|
context: Optional[Dict[str, Any]] = None,
|
|
|
|
condition: Optional[Dict[str, str]] = None,
|
2021-08-05 20:55:42 +01:00
|
|
|
fail_not_found: bool = True,
|
|
|
|
inline: bool = False,
|
|
|
|
reverse: bool = False,
|
|
|
|
) -> Union[asyncio.Task, Any]:
|
|
|
|
dispatch = self._dispatch(
|
|
|
|
event,
|
|
|
|
context=context,
|
|
|
|
condition=condition,
|
|
|
|
fail_not_found=fail_not_found and inline,
|
|
|
|
reverse=reverse,
|
2021-03-14 08:09:07 +00:00
|
|
|
)
|
2022-09-18 15:17:23 +01:00
|
|
|
logger.debug(f"Dispatching signal: {event}", extra={"verbosity": 1})
|
2021-08-05 20:55:42 +01:00
|
|
|
|
|
|
|
if inline:
|
|
|
|
return await dispatch
|
|
|
|
|
|
|
|
task = asyncio.get_running_loop().create_task(dispatch)
|
2021-03-14 08:09:07 +00:00
|
|
|
await asyncio.sleep(0)
|
|
|
|
return task
|
|
|
|
|
|
|
|
def add( # type: ignore
|
|
|
|
self,
|
|
|
|
handler: SignalHandler,
|
|
|
|
event: str,
|
|
|
|
condition: Optional[Dict[str, Any]] = None,
|
2021-12-23 23:27:54 +00:00
|
|
|
exclusive: bool = True,
|
2021-03-14 08:09:07 +00:00
|
|
|
) -> Signal:
|
2021-12-23 23:27:54 +00:00
|
|
|
event_definition = event
|
2021-03-14 13:21:59 +00:00
|
|
|
parts = self._build_event_parts(event)
|
2021-03-14 08:09:07 +00:00
|
|
|
if parts[2].startswith("<"):
|
|
|
|
name = ".".join([*parts[:-1], "*"])
|
2021-12-23 23:27:54 +00:00
|
|
|
trigger = self._clean_trigger(parts[2])
|
2021-03-14 08:09:07 +00:00
|
|
|
else:
|
|
|
|
name = event
|
2021-12-23 23:27:54 +00:00
|
|
|
trigger = ""
|
|
|
|
|
|
|
|
if not trigger:
|
|
|
|
event = ".".join([*parts[:2], "<__trigger__>"])
|
2021-03-14 08:09:07 +00:00
|
|
|
|
|
|
|
handler.__requirements__ = condition # type: ignore
|
2021-12-23 23:27:54 +00:00
|
|
|
handler.__trigger__ = trigger # type: ignore
|
2021-03-14 08:09:07 +00:00
|
|
|
|
2021-12-23 23:27:54 +00:00
|
|
|
signal = super().add(
|
2021-03-14 08:09:07 +00:00
|
|
|
event,
|
|
|
|
handler,
|
|
|
|
name=name,
|
2021-04-19 22:53:42 +01:00
|
|
|
append=True,
|
2021-03-14 08:09:07 +00:00
|
|
|
) # type: ignore
|
|
|
|
|
2021-12-23 23:27:54 +00:00
|
|
|
signal.ctx.exclusive = exclusive
|
|
|
|
signal.ctx.trigger = trigger
|
|
|
|
signal.ctx.definition = event_definition
|
|
|
|
|
|
|
|
return cast(Signal, signal)
|
|
|
|
|
2021-08-05 20:55:42 +01:00
|
|
|
def finalize(self, do_compile: bool = True, do_optimize: bool = False):
|
|
|
|
self.add(_blank, "sanic.__signal__.__init__")
|
|
|
|
|
2021-03-14 08:09:07 +00:00
|
|
|
try:
|
|
|
|
self.ctx.loop = asyncio.get_running_loop()
|
|
|
|
except RuntimeError:
|
|
|
|
raise RuntimeError("Cannot finalize signals outside of event loop")
|
|
|
|
|
2021-04-19 22:53:42 +01:00
|
|
|
for signal in self.routes:
|
2021-03-14 08:09:07 +00:00
|
|
|
signal.ctx.event = asyncio.Event()
|
|
|
|
|
2021-08-05 20:55:42 +01:00
|
|
|
return super().finalize(do_compile=do_compile, do_optimize=do_optimize)
|
2021-03-14 13:21:59 +00:00
|
|
|
|
|
|
|
def _build_event_parts(self, event: str) -> Tuple[str, str, str]:
|
|
|
|
parts = path_to_parts(event, self.delimiter)
|
|
|
|
if (
|
|
|
|
len(parts) != 3
|
|
|
|
or parts[0].startswith("<")
|
|
|
|
or parts[1].startswith("<")
|
|
|
|
):
|
|
|
|
raise InvalidSignal("Invalid signal event: %s" % event)
|
|
|
|
|
2021-08-05 20:55:42 +01:00
|
|
|
if (
|
|
|
|
parts[0] in RESERVED_NAMESPACES
|
|
|
|
and event not in RESERVED_NAMESPACES[parts[0]]
|
|
|
|
and not (parts[2].startswith("<") and parts[2].endswith(">"))
|
|
|
|
):
|
2021-03-14 13:21:59 +00:00
|
|
|
raise InvalidSignal(
|
|
|
|
"Cannot declare reserved signal event: %s" % event
|
|
|
|
)
|
|
|
|
return parts
|
2021-12-23 23:27:54 +00:00
|
|
|
|
|
|
|
def _clean_trigger(self, trigger: str) -> str:
|
|
|
|
trigger = trigger[1:-1]
|
|
|
|
if ":" in trigger:
|
|
|
|
trigger, _ = trigger.split(":")
|
|
|
|
return trigger
|