Skip to content

Commit

Permalink
Add signal reservations (#2060)
Browse files Browse the repository at this point in the history
* Add signal reservations

* Simplify reservations
  • Loading branch information
ahopkins authored Mar 14, 2021
1 parent d4660d0 commit 2fea954
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 10 deletions.
33 changes: 23 additions & 10 deletions sanic/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import asyncio

from inspect import isawaitable
from typing import Any, Dict, List, Optional, Union
from typing import Any, Dict, List, Optional, Tuple, Union

from sanic_routing import BaseRouter, Route # type: ignore
from sanic_routing.exceptions import NotFound # type: ignore
Expand All @@ -13,6 +13,12 @@
from sanic.models.handler_types import SignalHandler


RESERVED_NAMESPACES = (
"server",
"http",
)


class Signal(Route):
def get_handler(self, raw_path, method, _):
method = method or self.router.DEFAULT_METHOD
Expand Down Expand Up @@ -97,15 +103,7 @@ def add( # type: ignore
event: str,
condition: Optional[Dict[str, Any]] = None,
) -> Signal:
parts = path_to_parts(event, self.delimiter)

if (
len(parts) != 3
or parts[0].startswith("<")
or parts[1].startswith("<")
):
raise InvalidSignal(f"Invalid signal event: {event}")

parts = self._build_event_parts(event)
if parts[2].startswith("<"):
name = ".".join([*parts[:-1], "*"])
else:
Expand All @@ -131,3 +129,18 @@ def finalize(self, do_compile: bool = True):
signal.ctx.event = asyncio.Event()

return super().finalize(do_compile=do_compile)

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)

if parts[0] in RESERVED_NAMESPACES:
raise InvalidSignal(
"Cannot declare reserved signal event: %s" % event
)
return parts
20 changes: 20 additions & 0 deletions tests/test_signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,23 @@ def bp_signal():
match="<Blueprint bp> has not yet been registered to an app",
):
bp.event("foo.bar.baz")


@pytest.mark.parametrize(
"event,expected",
(
("foo.bar.baz", True),
("server.init.before", False),
("http.request.start", False),
("sanic.notice.anything", True),
),
)
def test_signal_reservation(app, event, expected):
if not expected:
with pytest.raises(
InvalidSignal,
match=f"Cannot declare reserved signal event: {event}",
):
app.signal(event)(lambda: ...)
else:
app.signal(event)(lambda: ...)

0 comments on commit 2fea954

Please sign in to comment.