Initial commit.
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
# Copyright 2026 Logan Fick
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Internal infrastructure: registries, module-scoped wrappers, and dispatchers."""
|
||||
|
||||
from .commands import CommandDispatcher, CommandRegistry, ModuleCommands
|
||||
from .events import EventDispatcher, EventRegistry, ModuleEvents
|
||||
from .routes import ModuleRoutes, RouteDispatcher, RouteRegistry
|
||||
|
||||
__all__ = [
|
||||
# Commands.
|
||||
"CommandDispatcher",
|
||||
"CommandRegistry",
|
||||
"ModuleCommands",
|
||||
# Events.
|
||||
"EventDispatcher",
|
||||
"EventRegistry",
|
||||
"ModuleEvents",
|
||||
# Routes.
|
||||
"ModuleRoutes",
|
||||
"RouteDispatcher",
|
||||
"RouteRegistry",
|
||||
]
|
||||
@@ -0,0 +1,701 @@
|
||||
# Copyright 2026 Logan Fick
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Command registry, module-scoped wrapper, and dispatcher.
|
||||
|
||||
Internal infrastructure for managing command registration and dispatch.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import math
|
||||
import time
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import TYPE_CHECKING, cast
|
||||
|
||||
from ..api.commands import CommandEvent, CommandHandler, CommandInfo, CommandMark
|
||||
from ..api.event_types import ChatEvent
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from types import ModuleType
|
||||
|
||||
from ..api.context import EventContext, ModuleContext
|
||||
from ..api.owncast_client import OwncastClient
|
||||
|
||||
type BuiltinCommandHandler = Callable[[ChatEvent, "OwncastClient"], Awaitable[None]]
|
||||
|
||||
logger = logging.getLogger("owlbot.commands")
|
||||
|
||||
|
||||
class CommandRegistry:
|
||||
"""
|
||||
Holds all registered commands for a bot instance.
|
||||
|
||||
Instance-scoped to enable proper dependency injection and allow multiple
|
||||
bot instances to coexist without sharing state.
|
||||
"""
|
||||
|
||||
def __init__(self, prefix: str = "!") -> None:
|
||||
"""
|
||||
Initialize the command registry.
|
||||
|
||||
:param prefix: Command prefix character (e.g., "!" for "!ping").
|
||||
"""
|
||||
# Maps primary command names to their CommandInfo objects.
|
||||
self._commands: dict[str, CommandInfo] = {}
|
||||
|
||||
# Maps all triggers (primary names and aliases) to their primary command name.
|
||||
# This allows O(1) lookup for any trigger without scanning all commands.
|
||||
self._aliases: dict[str, str] = {}
|
||||
|
||||
self.prefix = prefix
|
||||
|
||||
logger.debug(f"CommandRegistry initialized with prefix '{prefix}'.")
|
||||
|
||||
def register(
|
||||
self,
|
||||
name: str,
|
||||
handler: CommandHandler,
|
||||
*,
|
||||
aliases: list[str] | tuple[str, ...] | None = None,
|
||||
requires_authenticated: bool = False,
|
||||
requires_moderator: bool = False,
|
||||
cooldown: int | float = 0,
|
||||
module_name: str,
|
||||
) -> None:
|
||||
"""
|
||||
Register a command handler.
|
||||
|
||||
:param name: Primary command name (case-insensitive).
|
||||
:param handler: Async function to handle the command.
|
||||
:param aliases: Optional list of alternative names.
|
||||
:param requires_authenticated: If True, user must be logged in.
|
||||
:param requires_moderator: If True, user must have moderator privileges.
|
||||
:param cooldown: Minimum seconds between invocations (0 to disable).
|
||||
:param module_name: Name of the module registering this command.
|
||||
:raises ValueError: If command name or alias conflicts with existing command.
|
||||
"""
|
||||
name_lower = name.lower()
|
||||
alias_set = frozenset(a.lower() for a in (aliases or []))
|
||||
|
||||
all_triggers = {name_lower} | alias_set
|
||||
for trigger in all_triggers:
|
||||
if trigger in self._aliases:
|
||||
existing = self._aliases[trigger]
|
||||
raise ValueError(
|
||||
f"Command trigger '{trigger}' conflicts with existing "
|
||||
f"command '{existing}'"
|
||||
)
|
||||
|
||||
info = CommandInfo(
|
||||
name=name_lower,
|
||||
handler=handler,
|
||||
module_name=module_name,
|
||||
aliases=alias_set,
|
||||
requires_authenticated=requires_authenticated,
|
||||
requires_moderator=requires_moderator,
|
||||
cooldown=cooldown,
|
||||
)
|
||||
|
||||
self._commands[name_lower] = info
|
||||
|
||||
for trigger in all_triggers:
|
||||
self._aliases[trigger] = name_lower
|
||||
|
||||
module_logger = logging.getLogger(f"owlbot.modules.{module_name}.commands")
|
||||
module_logger.debug(
|
||||
f"Registered command '{name_lower}' with aliases {sorted(alias_set)}, "
|
||||
f"authenticated={requires_authenticated}, moderator={requires_moderator}, "
|
||||
f"cooldown={cooldown}."
|
||||
)
|
||||
|
||||
def unregister(self, name: str) -> bool:
|
||||
"""
|
||||
Unregister a command and all its aliases.
|
||||
|
||||
:param name: The primary command name or any alias.
|
||||
:return: True if command was found and removed, False otherwise.
|
||||
"""
|
||||
name_lower = name.lower()
|
||||
|
||||
primary = self._aliases.get(name_lower)
|
||||
if primary is None:
|
||||
return False
|
||||
|
||||
info = self._commands.get(primary)
|
||||
if info is None:
|
||||
return False
|
||||
|
||||
for trigger in info.all_triggers:
|
||||
self._aliases.pop(trigger, None)
|
||||
|
||||
del self._commands[primary]
|
||||
|
||||
module_logger = logging.getLogger(f"owlbot.modules.{info.module_name}.commands")
|
||||
module_logger.debug(f"Unregistered command '{primary}'.")
|
||||
return True
|
||||
|
||||
def get(self, trigger: str) -> CommandInfo | None:
|
||||
"""
|
||||
Look up a command by name or alias.
|
||||
|
||||
:param trigger: Command name or alias (case-insensitive).
|
||||
:return: CommandInfo if found, None otherwise.
|
||||
"""
|
||||
trigger_lower = trigger.lower()
|
||||
primary = self._aliases.get(trigger_lower)
|
||||
if primary is None:
|
||||
return None
|
||||
return self._commands.get(primary)
|
||||
|
||||
def exists(self, trigger: str) -> bool:
|
||||
"""
|
||||
Check if a command is registered.
|
||||
|
||||
:param trigger: Command name or alias (case-insensitive).
|
||||
:return: True if the command exists, False otherwise.
|
||||
"""
|
||||
return trigger.lower() in self._aliases
|
||||
|
||||
def get_all(self) -> dict[str, CommandInfo]:
|
||||
"""
|
||||
Get all registered commands.
|
||||
|
||||
:return: Dict mapping primary command names to CommandInfo.
|
||||
"""
|
||||
return self._commands.copy()
|
||||
|
||||
def unregister_by_module(self, module_name: str) -> int:
|
||||
"""
|
||||
Remove all commands registered by a specific module.
|
||||
|
||||
:param module_name: The module whose commands should be removed.
|
||||
:return: Number of commands removed.
|
||||
"""
|
||||
module_logger = logging.getLogger(f"owlbot.modules.{module_name}.commands")
|
||||
to_remove = [
|
||||
name
|
||||
for name, info in self._commands.items()
|
||||
if info.module_name == module_name
|
||||
]
|
||||
module_logger.debug(f"Unregistering all commands ({len(to_remove)} total).")
|
||||
for name in to_remove:
|
||||
self.unregister(name)
|
||||
return len(to_remove)
|
||||
|
||||
def register_from_module(self, module: ModuleType, module_name: str) -> None:
|
||||
"""
|
||||
Scan a Python module for @on_command-decorated functions and register them.
|
||||
|
||||
Looks for functions with the ``_owlbot_command`` attribute set by
|
||||
the ``@on_command`` decorator and registers each one.
|
||||
|
||||
:param module: The loaded Python module to scan.
|
||||
:param module_name: Name of the module (for ownership tracking).
|
||||
"""
|
||||
for obj in vars(module).values():
|
||||
if callable(obj):
|
||||
cmd_info = getattr(obj, "_owlbot_command", None)
|
||||
if cmd_info is not None:
|
||||
mark = cast("CommandMark", cmd_info)
|
||||
self.register(
|
||||
name=mark["name"],
|
||||
handler=obj,
|
||||
aliases=mark["aliases"],
|
||||
requires_authenticated=mark["requires_authenticated"],
|
||||
requires_moderator=mark["requires_moderator"],
|
||||
cooldown=mark["cooldown"],
|
||||
module_name=module_name,
|
||||
)
|
||||
|
||||
def parse(self, message: str) -> tuple[str, str] | None:
|
||||
"""
|
||||
Parse a message to extract command and arguments.
|
||||
|
||||
:param message: The chat message body.
|
||||
:return: Tuple of (command_name, args_string), or None if not a command.
|
||||
"""
|
||||
if not message.startswith(self.prefix):
|
||||
return None
|
||||
|
||||
content = message[len(self.prefix) :].strip()
|
||||
|
||||
if not content:
|
||||
return None
|
||||
|
||||
parts = content.split(maxsplit=1)
|
||||
command = parts[0].lower()
|
||||
args = parts[1] if len(parts) > 1 else ""
|
||||
|
||||
logger.debug(f"Parsed command: {command!r} with args: {args!r}")
|
||||
return command, args
|
||||
|
||||
|
||||
class CommandDispatcher:
|
||||
"""
|
||||
Dispatches chat events to registered command handlers.
|
||||
|
||||
Parses messages, checks authentication/moderator requirements,
|
||||
and calls the appropriate command handler.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
get_module_context: Callable[[str], ModuleContext],
|
||||
owncast_client: OwncastClient,
|
||||
handler_timeout: float,
|
||||
loaded_modules: set[str],
|
||||
command_prefix: str = "!",
|
||||
) -> None:
|
||||
"""
|
||||
Initialize the command dispatcher.
|
||||
|
||||
Creates and owns a :class:`CommandRegistry` internally.
|
||||
|
||||
:param get_module_context: Callable that looks up a
|
||||
ModuleContext by module name.
|
||||
:param owncast_client: Owncast API client for sending error messages.
|
||||
:param handler_timeout: Timeout for command handlers in seconds.
|
||||
:param loaded_modules: Reference to the set of currently loaded module names.
|
||||
:param command_prefix: Prefix character for commands (e.g., "!").
|
||||
"""
|
||||
self._command_registry = CommandRegistry(command_prefix)
|
||||
self._get_module_context = get_module_context
|
||||
self._owncast_client = owncast_client
|
||||
self._handler_timeout = handler_timeout
|
||||
self._loaded_modules = loaded_modules
|
||||
# Maps canonical command name -> monotonic timestamp of last invocation.
|
||||
self._cooldown_tracker: dict[str, float] = {}
|
||||
# Maps canonical command name -> built-in handler callable.
|
||||
self._builtin_handlers: dict[str, BuiltinCommandHandler] = {}
|
||||
|
||||
self._register_builtin_commands()
|
||||
|
||||
@property
|
||||
def prefix(self) -> str:
|
||||
"""The command prefix character (e.g., '!')."""
|
||||
return self._command_registry.prefix
|
||||
|
||||
def register_builtin(
|
||||
self,
|
||||
name: str,
|
||||
handler: BuiltinCommandHandler,
|
||||
*,
|
||||
aliases: list[str] | tuple[str, ...] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Register a built-in command handler.
|
||||
|
||||
Built-in commands use a simpler handler signature (event, owncast_client)
|
||||
and don't require module infrastructure.
|
||||
|
||||
:param name: Primary command name (case-insensitive).
|
||||
:param handler: Async function with signature (ChatEvent, OwncastClient).
|
||||
:param aliases: Optional list of alternative names.
|
||||
"""
|
||||
name_lower = name.lower()
|
||||
self._builtin_handlers[name_lower] = handler
|
||||
self._command_registry.register(
|
||||
name=name,
|
||||
handler=handler, # type: ignore[arg-type]
|
||||
aliases=aliases,
|
||||
module_name="__builtin__",
|
||||
cooldown=60,
|
||||
)
|
||||
logger.debug(f"Registered built-in command '{name_lower}'.")
|
||||
|
||||
def register(
|
||||
self,
|
||||
name: str,
|
||||
handler: CommandHandler,
|
||||
*,
|
||||
aliases: list[str] | tuple[str, ...] | None = None,
|
||||
requires_authenticated: bool = False,
|
||||
requires_moderator: bool = False,
|
||||
cooldown: int | float = 0,
|
||||
module_name: str,
|
||||
) -> None:
|
||||
"""
|
||||
Register a command handler.
|
||||
|
||||
Delegates to the internal CommandRegistry.
|
||||
|
||||
:param name: Primary command name (case-insensitive).
|
||||
:param handler: Async function to handle the command.
|
||||
:param aliases: Optional list of alternative names.
|
||||
:param requires_authenticated: If True, user must be logged in.
|
||||
:param requires_moderator: If True, user must have moderator privileges.
|
||||
:param cooldown: Minimum seconds between invocations (0 to disable).
|
||||
:param module_name: Name of the module registering this command.
|
||||
:raises ValueError: If command name or alias conflicts with existing command.
|
||||
"""
|
||||
self._command_registry.register(
|
||||
name=name,
|
||||
handler=handler,
|
||||
aliases=aliases,
|
||||
requires_authenticated=requires_authenticated,
|
||||
requires_moderator=requires_moderator,
|
||||
cooldown=cooldown,
|
||||
module_name=module_name,
|
||||
)
|
||||
# Clear any stale cooldown tracker entry on re-registration.
|
||||
self._cooldown_tracker.pop(name.lower(), None)
|
||||
|
||||
def unregister(self, name: str) -> bool:
|
||||
"""
|
||||
Unregister a command and all its aliases.
|
||||
|
||||
Delegates to the internal CommandRegistry.
|
||||
|
||||
:param name: The primary command name or any alias.
|
||||
:return: True if command was found and removed, False otherwise.
|
||||
"""
|
||||
# Resolve canonical name before unregistering so we can clean up the tracker.
|
||||
info = self._command_registry.get(name)
|
||||
result = self._command_registry.unregister(name)
|
||||
if result and info is not None:
|
||||
self._cooldown_tracker.pop(info.name, None)
|
||||
return result
|
||||
|
||||
def get(self, trigger: str) -> CommandInfo | None:
|
||||
"""
|
||||
Look up a command by name or alias.
|
||||
|
||||
Delegates to the internal CommandRegistry.
|
||||
|
||||
:param trigger: Command name or alias (case-insensitive).
|
||||
:return: CommandInfo if found, None otherwise.
|
||||
"""
|
||||
return self._command_registry.get(trigger)
|
||||
|
||||
def exists(self, trigger: str) -> bool:
|
||||
"""
|
||||
Check if a command is registered.
|
||||
|
||||
Delegates to the internal CommandRegistry.
|
||||
|
||||
:param trigger: Command name or alias (case-insensitive).
|
||||
:return: True if the command exists, False otherwise.
|
||||
"""
|
||||
return self._command_registry.exists(trigger)
|
||||
|
||||
def get_by_module(self, module_name: str) -> dict[str, CommandInfo]:
|
||||
"""
|
||||
Get all commands registered by a specific module.
|
||||
|
||||
:param module_name: The module whose commands to return.
|
||||
:return: Dict mapping primary command names to CommandInfo for that module.
|
||||
"""
|
||||
return {
|
||||
name: info
|
||||
for name, info in self._command_registry.get_all().items()
|
||||
if info.module_name == module_name
|
||||
}
|
||||
|
||||
def register_from_module(self, module: ModuleType, module_name: str) -> None:
|
||||
"""
|
||||
Scan a Python module for @on_command-decorated functions and register them.
|
||||
|
||||
Delegates to the internal CommandRegistry.
|
||||
|
||||
:param module: The loaded Python module to scan.
|
||||
:param module_name: Name of the module (for ownership tracking).
|
||||
"""
|
||||
self._command_registry.register_from_module(module, module_name)
|
||||
|
||||
def unregister_by_module(self, module_name: str) -> int:
|
||||
"""
|
||||
Remove all commands registered by a specific module.
|
||||
|
||||
Delegates to the internal CommandRegistry.
|
||||
|
||||
:param module_name: The module whose commands should be removed.
|
||||
:return: Number of commands removed.
|
||||
"""
|
||||
# Collect command names before unregistering so we can clean up the tracker.
|
||||
module_commands = self.get_by_module(module_name)
|
||||
for cmd_name in module_commands:
|
||||
self._cooldown_tracker.pop(cmd_name, None)
|
||||
return self._command_registry.unregister_by_module(module_name)
|
||||
|
||||
async def dispatch(self, event: ChatEvent) -> None:
|
||||
"""
|
||||
Dispatch a chat event to the appropriate command handler if it's a command.
|
||||
|
||||
:param event: The chat event to check for commands.
|
||||
"""
|
||||
from ..api.context import CommandContext, EventContext
|
||||
|
||||
parsed = self._command_registry.parse(event.body)
|
||||
|
||||
if parsed is None:
|
||||
return
|
||||
|
||||
command_name, args = parsed
|
||||
|
||||
command_info = self._command_registry.get(command_name)
|
||||
|
||||
if command_info is None:
|
||||
# Log for debugging but don't spam the chat with "unknown command" errors.
|
||||
logger.debug(f"Unknown command: {command_name}")
|
||||
return
|
||||
|
||||
user = event.user
|
||||
|
||||
logger.info(
|
||||
f"Command '{command_info.name}' invoked by {user.display_name}"
|
||||
f" with args: {args!r}"
|
||||
)
|
||||
|
||||
if command_info.requires_authenticated and not user.is_authenticated:
|
||||
logger.info(
|
||||
f"Command '{command_name}' denied for {user.display_name}: "
|
||||
"authentication required"
|
||||
)
|
||||
await self._owncast_client.send_system_message_to_client(
|
||||
event.client_id,
|
||||
f"You must be authenticated to use !{command_info.name}.",
|
||||
)
|
||||
return
|
||||
|
||||
if command_info.requires_moderator and not user.is_moderator:
|
||||
logger.info(
|
||||
f"Command '{command_name}' denied for {user.display_name}: "
|
||||
"moderator required"
|
||||
)
|
||||
await self._owncast_client.send_system_message_to_client(
|
||||
event.client_id,
|
||||
f"Only moderators can use !{command_info.name}.",
|
||||
)
|
||||
return
|
||||
|
||||
if command_info.cooldown > 0:
|
||||
now = time.monotonic()
|
||||
last = self._cooldown_tracker.get(command_info.name)
|
||||
if last is not None and now - last < command_info.cooldown:
|
||||
remaining = math.ceil(command_info.cooldown - (now - last))
|
||||
logger.info(
|
||||
f"Command '{command_name}' denied for {user.display_name}: "
|
||||
f"on cooldown ({remaining}s remaining)"
|
||||
)
|
||||
await self._owncast_client.send_system_message_to_client(
|
||||
event.client_id,
|
||||
f"!{command_info.name} can be used every "
|
||||
f"{command_info.cooldown:.0f}s. Try again in {remaining}s.",
|
||||
)
|
||||
return
|
||||
# Record immediately to prevent concurrent tasks from bypassing the
|
||||
# cooldown between this check and handler completion.
|
||||
self._cooldown_tracker[command_info.name] = now
|
||||
|
||||
# Built-in commands use a simpler dispatch path
|
||||
# without ModuleContext or storage.
|
||||
builtin_handler = self._builtin_handlers.get(command_info.name)
|
||||
if builtin_handler is not None:
|
||||
try:
|
||||
start = time.perf_counter()
|
||||
await asyncio.wait_for(
|
||||
builtin_handler(event, self._owncast_client),
|
||||
timeout=self._handler_timeout,
|
||||
)
|
||||
elapsed = (time.perf_counter() - start) * 1000
|
||||
logger.debug(
|
||||
f"Built-in command '{command_info.name}' "
|
||||
f"completed in {elapsed:.1f}ms."
|
||||
)
|
||||
except TimeoutError:
|
||||
logger.warning(
|
||||
f"Built-in command '{command_info.name}' "
|
||||
f"cancelled after {self._handler_timeout}s timeout."
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
f"Built-in command '{command_info.name}' raised exception: {e}"
|
||||
)
|
||||
return
|
||||
|
||||
cmd_event = CommandEvent(
|
||||
# Use the canonical name, not the alias the user typed.
|
||||
command=command_info.name,
|
||||
args=args,
|
||||
args_list=args.split() if args else [],
|
||||
prefix=self._command_registry.prefix,
|
||||
chat_event=event,
|
||||
)
|
||||
|
||||
module_ctx = self._get_module_context(command_info.module_name)
|
||||
|
||||
event_ctx: EventContext[ChatEvent] = EventContext(
|
||||
event=event,
|
||||
module=module_ctx,
|
||||
)
|
||||
|
||||
cmd_ctx = CommandContext(
|
||||
command_event=cmd_event,
|
||||
event_context=event_ctx,
|
||||
module=module_ctx,
|
||||
)
|
||||
|
||||
# The checkout acquires a pooled connection for the
|
||||
# duration of this command invocation.
|
||||
async with module_ctx.storage._checkout():
|
||||
try:
|
||||
start = time.perf_counter()
|
||||
await asyncio.wait_for(
|
||||
command_info.handler(cmd_ctx), timeout=self._handler_timeout
|
||||
)
|
||||
elapsed = (time.perf_counter() - start) * 1000
|
||||
|
||||
# Command succeeded, commit any database changes.
|
||||
await module_ctx.storage._commit()
|
||||
|
||||
logger.debug(
|
||||
f"Command '{command_info.name}' completed in {elapsed:.1f}ms."
|
||||
)
|
||||
except TimeoutError:
|
||||
# Command timed out. Rollback any partial changes.
|
||||
await module_ctx.storage._rollback()
|
||||
logger.warning(
|
||||
f"Command handler '{command_info.name}' "
|
||||
f"from module '{command_info.module_name}' "
|
||||
f"cancelled after "
|
||||
f"{self._handler_timeout}s timeout."
|
||||
)
|
||||
except Exception as e:
|
||||
# Command raised an exception. Rollback any partial changes.
|
||||
await module_ctx.storage._rollback()
|
||||
logger.exception(
|
||||
f"Command handler '{command_info.name}' "
|
||||
f"from module '{command_info.module_name}' "
|
||||
f"raised exception: {e}"
|
||||
)
|
||||
|
||||
def _register_builtin_commands(self) -> None:
|
||||
"""Register all built-in commands."""
|
||||
from .._version import __version__
|
||||
|
||||
loaded_modules = self._loaded_modules
|
||||
|
||||
async def about_with_modules(
|
||||
event: ChatEvent, owncast_client: OwncastClient
|
||||
) -> None:
|
||||
module_count = len(loaded_modules)
|
||||
module_list = (
|
||||
", ".join(sorted(loaded_modules)) if loaded_modules else "none"
|
||||
)
|
||||
await owncast_client.send_message(
|
||||
f"Owlbot v{__version__} - A logal.dev project | "
|
||||
f"Modules ({module_count}): {module_list}"
|
||||
)
|
||||
|
||||
self.register_builtin("about", about_with_modules)
|
||||
|
||||
|
||||
class ModuleCommands:
|
||||
"""
|
||||
Module-scoped wrapper around CommandDispatcher.
|
||||
|
||||
This wrapper auto-supplies the module name for registration operations,
|
||||
so modules don't need to pass their own name back into the API.
|
||||
Follows the same pattern as ModuleEvents and ModuleRoutes.
|
||||
"""
|
||||
|
||||
def __init__(self, dispatcher: CommandDispatcher, module_name: str) -> None:
|
||||
"""
|
||||
Initialize the module-scoped command wrapper.
|
||||
|
||||
:param dispatcher: The CommandDispatcher that owns the command registry.
|
||||
:param module_name: The name of the module using this wrapper.
|
||||
"""
|
||||
self._dispatcher = dispatcher
|
||||
self._module_name = module_name
|
||||
|
||||
@property
|
||||
def prefix(self) -> str:
|
||||
"""The command prefix character (e.g., '!')."""
|
||||
return self._dispatcher.prefix
|
||||
|
||||
@property
|
||||
def module_commands(self) -> dict[str, CommandInfo]:
|
||||
"""Commands registered by this module only."""
|
||||
return self._dispatcher.get_by_module(self._module_name)
|
||||
|
||||
def register(
|
||||
self,
|
||||
name: str,
|
||||
handler: CommandHandler,
|
||||
*,
|
||||
aliases: list[str] | tuple[str, ...] | None = None,
|
||||
requires_authenticated: bool = False,
|
||||
requires_moderator: bool = False,
|
||||
cooldown: int | float = 0,
|
||||
) -> None:
|
||||
"""
|
||||
Register a command handler for this module.
|
||||
|
||||
The module name is automatically supplied.
|
||||
|
||||
:param name: Primary command name (case-insensitive).
|
||||
:param handler: Async function to handle the command.
|
||||
:param aliases: Optional list of alternative names.
|
||||
:param requires_authenticated: If True, user must be logged in.
|
||||
:param requires_moderator: If True, user must have moderator privileges.
|
||||
:param cooldown: Minimum seconds between invocations (0 to disable).
|
||||
:raises ValueError: If command name or alias conflicts with existing command.
|
||||
"""
|
||||
self._dispatcher.register(
|
||||
name=name,
|
||||
handler=handler,
|
||||
aliases=aliases,
|
||||
requires_authenticated=requires_authenticated,
|
||||
requires_moderator=requires_moderator,
|
||||
cooldown=cooldown,
|
||||
module_name=self._module_name,
|
||||
)
|
||||
|
||||
def unregister(self, name: str) -> bool:
|
||||
"""
|
||||
Unregister a command and all its aliases.
|
||||
|
||||
Only commands registered by this module can be unregistered.
|
||||
|
||||
:param name: The primary command name or any alias.
|
||||
:return: True if command was found and removed, False if not found or not owned.
|
||||
"""
|
||||
# Only allow unregistering commands owned by this module.
|
||||
info = self._dispatcher.get(name)
|
||||
if info is None or info.module_name != self._module_name:
|
||||
return False
|
||||
return self._dispatcher.unregister(name)
|
||||
|
||||
def get(self, trigger: str) -> CommandInfo | None:
|
||||
"""
|
||||
Look up a command by name or alias within this module's registrations.
|
||||
|
||||
:param trigger: Command name or alias (case-insensitive).
|
||||
:return: CommandInfo if found and owned by this module, None otherwise.
|
||||
"""
|
||||
info = self._dispatcher.get(trigger)
|
||||
if info is None or info.module_name != self._module_name:
|
||||
return None
|
||||
return info
|
||||
|
||||
def exists(self, trigger: str) -> bool:
|
||||
"""
|
||||
Check if a command is registered across all modules.
|
||||
|
||||
:param trigger: Command name or alias (case-insensitive).
|
||||
:return: True if the command exists, False otherwise.
|
||||
"""
|
||||
return self._dispatcher.exists(trigger)
|
||||
@@ -0,0 +1,512 @@
|
||||
# Copyright 2026 Logan Fick
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Event handler registry, module-scoped wrapper, and dispatcher.
|
||||
|
||||
Internal infrastructure for managing event handler registration and dispatch.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from typing import TYPE_CHECKING, NamedTuple, cast
|
||||
|
||||
from ..api.context import PropagationState
|
||||
from ..api.event_types import ChatEvent, Event, EventType, log_event
|
||||
from ..api.events import EventHandler, EventMark, Priority
|
||||
|
||||
|
||||
class HandlerEntry(NamedTuple):
|
||||
"""A registered event handler with its module name and priority."""
|
||||
|
||||
handler: EventHandler
|
||||
module_name: str
|
||||
priority: int
|
||||
|
||||
|
||||
type EventHandlerMap = dict[str, list[HandlerEntry]]
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Awaitable, Callable
|
||||
from types import ModuleType
|
||||
|
||||
from ..api.context import EventContext, ModuleContext
|
||||
|
||||
logger = logging.getLogger("owlbot.events")
|
||||
|
||||
|
||||
class EventRegistry:
|
||||
"""
|
||||
Holds all registered event handlers for a bot instance.
|
||||
|
||||
Instance-scoped to enable proper dependency injection and allow multiple
|
||||
bot instances to coexist without sharing state.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Initialize an empty handler registry."""
|
||||
# Maps event type values (strings) to lists of
|
||||
# (handler, module_name, priority) tuples.
|
||||
self._handlers: EventHandlerMap = {}
|
||||
|
||||
def register(
|
||||
self,
|
||||
handler: EventHandler,
|
||||
event_types: tuple[EventType, ...],
|
||||
module_name: str,
|
||||
priority: int = Priority.NORMAL,
|
||||
) -> None:
|
||||
"""
|
||||
Register a handler for the given event types.
|
||||
|
||||
Called by the module loader after scanning for decorated functions.
|
||||
|
||||
:param handler: The handler function to register.
|
||||
:param event_types: Tuple of EventType values the handler responds to.
|
||||
:param module_name: Name of the module this handler belongs to.
|
||||
:param priority: Dispatch priority (higher runs first).
|
||||
Defaults to Priority.NORMAL.
|
||||
"""
|
||||
# A single handler can respond to multiple event types.
|
||||
for event_type in event_types:
|
||||
key = event_type.value
|
||||
|
||||
if key not in self._handlers:
|
||||
self._handlers[key] = []
|
||||
|
||||
# Add the handler to the list. Multiple handlers
|
||||
# for the same event are allowed.
|
||||
self._handlers[key].append(HandlerEntry(handler, module_name, priority))
|
||||
module_logger = logging.getLogger(f"owlbot.modules.{module_name}.events")
|
||||
module_logger.debug(
|
||||
f"Registered handler '{handler.__name__}' for {event_type.value} "
|
||||
f"(priority={priority})."
|
||||
)
|
||||
|
||||
def unregister(self, handler: EventHandler) -> bool:
|
||||
"""
|
||||
Unregister a handler from all event types it is registered for.
|
||||
|
||||
:param handler: The handler function to unregister.
|
||||
:return: True if handler was found and removed, False otherwise.
|
||||
"""
|
||||
module_name = None
|
||||
removed_from: list[str] = []
|
||||
for key in self._handlers:
|
||||
original = self._handlers[key]
|
||||
kept = []
|
||||
for entry in original:
|
||||
if entry.handler is handler:
|
||||
module_name = entry.module_name
|
||||
removed_from.append(key)
|
||||
else:
|
||||
kept.append(entry)
|
||||
self._handlers[key] = kept
|
||||
|
||||
if module_name and removed_from:
|
||||
module_logger = logging.getLogger(f"owlbot.modules.{module_name}.events")
|
||||
module_logger.debug(
|
||||
f"Unregistered handler '{handler.__name__}' "
|
||||
f"for {', '.join(removed_from)}."
|
||||
)
|
||||
return True
|
||||
return False
|
||||
|
||||
def get(self, event_type: EventType) -> list[HandlerEntry]:
|
||||
"""
|
||||
Get all handlers registered for a specific event type.
|
||||
|
||||
:param event_type: The event type to look up.
|
||||
:return: List of (handler, module_name, priority) tuples.
|
||||
"""
|
||||
return self._handlers.get(event_type.value, [])
|
||||
|
||||
def get_all(self) -> EventHandlerMap:
|
||||
"""
|
||||
Get a copy of the entire handler registry.
|
||||
|
||||
:return: Dict mapping event type values to handler lists.
|
||||
"""
|
||||
return self._handlers.copy()
|
||||
|
||||
def get_handler_module(self, handler: EventHandler) -> str | None:
|
||||
"""
|
||||
Look up which module registered a given handler.
|
||||
|
||||
:param handler: The handler function to look up.
|
||||
:return: The module name if found, None otherwise.
|
||||
"""
|
||||
for handler_list in self._handlers.values():
|
||||
for entry in handler_list:
|
||||
if entry.handler is handler:
|
||||
return entry.module_name
|
||||
return None
|
||||
|
||||
def unregister_by_module(self, module_name: str) -> int:
|
||||
"""
|
||||
Remove all handlers registered by a specific module.
|
||||
|
||||
:param module_name: The module whose handlers should be removed.
|
||||
:return: Number of handlers removed.
|
||||
"""
|
||||
module_logger = logging.getLogger(f"owlbot.modules.{module_name}.events")
|
||||
|
||||
seen: set[EventHandler] = set()
|
||||
for key in self._handlers:
|
||||
kept = []
|
||||
for entry in self._handlers[key]:
|
||||
if entry.module_name == module_name:
|
||||
seen.add(entry.handler)
|
||||
else:
|
||||
kept.append(entry)
|
||||
self._handlers[key] = kept
|
||||
|
||||
if seen:
|
||||
module_logger.debug(f"Unregistered all handlers ({len(seen)} total).")
|
||||
return len(seen)
|
||||
|
||||
def register_from_module(self, module: ModuleType, module_name: str) -> None:
|
||||
"""
|
||||
Scan a Python module for @on_event-decorated functions and register them.
|
||||
|
||||
Looks for functions with the ``_owlbot_event`` attribute set by
|
||||
the ``@on_event`` decorator and registers each one.
|
||||
|
||||
:param module: The loaded Python module to scan.
|
||||
:param module_name: Name of the module (for ownership tracking).
|
||||
"""
|
||||
for obj in vars(module).values():
|
||||
if callable(obj):
|
||||
event_info = getattr(obj, "_owlbot_event", None)
|
||||
if event_info is not None:
|
||||
mark = cast("EventMark", event_info)
|
||||
self.register(
|
||||
obj, mark["event_types"], module_name, mark["priority"]
|
||||
)
|
||||
|
||||
|
||||
class EventDispatcher:
|
||||
"""
|
||||
Dispatches events to registered handlers sequentially by priority.
|
||||
|
||||
After all event handlers complete, command dispatch is triggered for
|
||||
CHAT events (via the injected command_dispatch callback).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
command_dispatch: Callable[[ChatEvent], Awaitable[None]],
|
||||
get_module_context: Callable[[str], ModuleContext],
|
||||
handler_timeout: float,
|
||||
) -> None:
|
||||
"""
|
||||
Initialize the event dispatcher.
|
||||
|
||||
Creates and owns a :class:`EventRegistry` internally.
|
||||
|
||||
:param command_dispatch: Async callback to dispatch
|
||||
commands for CHAT events.
|
||||
:param get_module_context: Callable that looks up a
|
||||
ModuleContext by module name.
|
||||
:param handler_timeout: Timeout for individual handlers in seconds.
|
||||
"""
|
||||
self._handler_registry = EventRegistry()
|
||||
self._command_dispatch = command_dispatch
|
||||
self._get_module_context = get_module_context
|
||||
self._handler_timeout = handler_timeout
|
||||
|
||||
def register(
|
||||
self,
|
||||
handler: EventHandler,
|
||||
event_types: tuple[EventType, ...],
|
||||
module_name: str,
|
||||
priority: int = Priority.NORMAL,
|
||||
) -> None:
|
||||
"""
|
||||
Register a handler for the given event types.
|
||||
|
||||
A single handler can respond to multiple event types; the registry
|
||||
stores a separate entry per event type. This is the shared entry
|
||||
point for both decorator-based registration (via ``register_from_module``)
|
||||
and dynamic registration (via ``ModuleEvents.register``).
|
||||
|
||||
:param handler: The handler function to register.
|
||||
:param event_types: Tuple of EventType values the handler responds to.
|
||||
:param module_name: Name of the module this handler
|
||||
belongs to.
|
||||
:param priority: Dispatch priority (higher runs first).
|
||||
Defaults to Priority.NORMAL.
|
||||
"""
|
||||
self._handler_registry.register(handler, event_types, module_name, priority)
|
||||
|
||||
def unregister(self, handler: EventHandler) -> bool:
|
||||
"""
|
||||
Unregister a handler from all event types it is registered for.
|
||||
|
||||
Unlike commands (looked up by name string), event handlers are
|
||||
identified by object identity. A handler registered for multiple
|
||||
event types is removed from every one of them in a single call.
|
||||
|
||||
:param handler: The handler function to unregister.
|
||||
:return: True if handler was found and removed, False otherwise.
|
||||
"""
|
||||
return self._handler_registry.unregister(handler)
|
||||
|
||||
def get_by_module(self, module_name: str) -> EventHandlerMap:
|
||||
"""
|
||||
Get all handlers registered by a specific module, grouped by event type.
|
||||
|
||||
The registry stores handlers grouped by event type, not by module,
|
||||
so this filters across all event types to collect a single module's
|
||||
handlers.
|
||||
|
||||
:param module_name: The module whose handlers to return.
|
||||
:return: Dict mapping event type values to handler lists for that module.
|
||||
"""
|
||||
result: EventHandlerMap = {}
|
||||
for event_type_value, handler_list in self._handler_registry.get_all().items():
|
||||
filtered = [
|
||||
entry for entry in handler_list if entry.module_name == module_name
|
||||
]
|
||||
if filtered:
|
||||
result[event_type_value] = filtered
|
||||
return result
|
||||
|
||||
def get_handler_module(self, handler: EventHandler) -> str | None:
|
||||
"""
|
||||
Reverse-lookup which module registered a given handler.
|
||||
|
||||
Scans all event types since handlers are stored by event type,
|
||||
not by module.
|
||||
|
||||
:param handler: The handler function to look up.
|
||||
:return: The module name if found, None otherwise.
|
||||
"""
|
||||
return self._handler_registry.get_handler_module(handler)
|
||||
|
||||
def register_from_module(self, module: ModuleType, module_name: str) -> None:
|
||||
"""
|
||||
Scan a Python module for ``@on_event``-decorated functions and register them.
|
||||
|
||||
This is the import-phase entry point: the module loader calls it once
|
||||
per module. Decorator attributes are read here and passed as explicit
|
||||
parameters to ``register()``, so no decorator markers are used after
|
||||
this point.
|
||||
|
||||
:param module: The loaded Python module to scan.
|
||||
:param module_name: Name of the module (for ownership tracking).
|
||||
"""
|
||||
self._handler_registry.register_from_module(module, module_name)
|
||||
|
||||
def unregister_by_module(self, module_name: str) -> int:
|
||||
"""
|
||||
Remove all handlers registered by a specific module.
|
||||
|
||||
Used during module teardown to clean up all of a module's handlers
|
||||
in one call, regardless of which event types they were registered for.
|
||||
|
||||
:param module_name: The module whose handlers should be removed.
|
||||
:return: Number of handlers removed.
|
||||
"""
|
||||
return self._handler_registry.unregister_by_module(module_name)
|
||||
|
||||
async def dispatch(self, event_type: EventType, event: Event) -> None:
|
||||
"""
|
||||
Dispatch an event to handlers sequentially by priority, then to commands.
|
||||
|
||||
:param event_type: The type of event to dispatch.
|
||||
:param event: The parsed event instance.
|
||||
"""
|
||||
log_event(event_type, event)
|
||||
|
||||
handler_entries = self._handler_registry.get(event_type)
|
||||
|
||||
# Shared state for propagation control (all handlers see the same instance).
|
||||
propagation = PropagationState()
|
||||
|
||||
# Phase 1: Event handlers (sequential, sorted by priority descending).
|
||||
if handler_entries:
|
||||
# Sort handlers by priority (highest first).
|
||||
# Python's sort is stable, so handlers at the same priority
|
||||
# run in their original registration order.
|
||||
sorted_handlers = sorted(
|
||||
handler_entries,
|
||||
key=lambda entry: entry.priority,
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
f"Dispatching {event_type} to {len(sorted_handlers)} handler(s)."
|
||||
)
|
||||
|
||||
for handler, module_name, _priority in sorted_handlers:
|
||||
# Has propagation been stopped by a previous handler?
|
||||
if propagation.stopped:
|
||||
reason = propagation.reason
|
||||
logger.debug(
|
||||
f"Propagation stopped{': ' + reason if reason else '.'}"
|
||||
)
|
||||
break
|
||||
|
||||
await self._call_handler(
|
||||
handler, event, event_type, module_name, propagation
|
||||
)
|
||||
else:
|
||||
logger.debug(f"No handlers registered for event type: {event_type}")
|
||||
|
||||
# Phase 2: Command dispatch (CHAT events only, if not cancelled).
|
||||
if event_type == EventType.CHAT and isinstance(event, ChatEvent):
|
||||
# Has propagation been stopped?
|
||||
if propagation.stopped:
|
||||
reason = propagation.reason
|
||||
logger.debug(
|
||||
f"Command dispatch skipped{': ' + reason if reason else '.'}"
|
||||
)
|
||||
else:
|
||||
try:
|
||||
await self._command_dispatch(event)
|
||||
except Exception as e:
|
||||
logger.exception(f"Command dispatch failed: {e}")
|
||||
|
||||
async def _call_handler(
|
||||
self,
|
||||
handler: EventHandler,
|
||||
event: Event,
|
||||
event_type: EventType,
|
||||
module_name: str,
|
||||
propagation: PropagationState,
|
||||
) -> None:
|
||||
"""
|
||||
Call a single handler with timeout enforcement and transaction management.
|
||||
|
||||
:param handler: The handler function to call.
|
||||
:param event: The event to pass to the handler.
|
||||
:param event_type: The type of event being dispatched.
|
||||
:param module_name: The module that owns this handler.
|
||||
:param propagation: Shared propagation state for this dispatch cycle.
|
||||
"""
|
||||
from ..api.context import EventContext
|
||||
|
||||
handler_name = handler.__name__
|
||||
logger.debug(f"Calling handler: {handler_name} from module: {module_name}")
|
||||
|
||||
module_ctx = self._get_module_context(module_name)
|
||||
|
||||
ctx: EventContext[Event] = EventContext(
|
||||
event=event,
|
||||
module=module_ctx,
|
||||
_propagation=propagation,
|
||||
)
|
||||
|
||||
# Call the handler with timeout enforcement to prevent
|
||||
# runaway handlers from blocking everything.
|
||||
# The checkout acquires a pooled connection for the
|
||||
# duration of this handler invocation.
|
||||
async with module_ctx.storage._checkout():
|
||||
try:
|
||||
start = time.perf_counter()
|
||||
await asyncio.wait_for(handler(ctx), timeout=self._handler_timeout)
|
||||
elapsed = (time.perf_counter() - start) * 1000
|
||||
|
||||
# Handler succeeded, commit any database changes.
|
||||
await module_ctx.storage._commit()
|
||||
|
||||
logger.debug(f"Handler '{handler_name}' completed in {elapsed:.1f}ms.")
|
||||
except TimeoutError:
|
||||
# Handler took too long. Rollback any partial changes.
|
||||
await module_ctx.storage._rollback()
|
||||
logger.warning(
|
||||
f"Handler '{handler_name}' from module '{module_name}' "
|
||||
f"cancelled after {self._handler_timeout}s timeout."
|
||||
)
|
||||
except Exception as e:
|
||||
# Handler raised an exception. Rollback any partial changes.
|
||||
await module_ctx.storage._rollback()
|
||||
logger.exception(
|
||||
f"Handler '{handler_name}' from module "
|
||||
f"'{module_name}' raised exception: {e}"
|
||||
)
|
||||
|
||||
|
||||
class ModuleEvents:
|
||||
"""
|
||||
Module-scoped wrapper around EventDispatcher.
|
||||
|
||||
This wrapper auto-supplies the module name for registration operations,
|
||||
so modules don't need to pass their own name back into the API.
|
||||
Follows the same pattern as ModuleCommands and ModuleRoutes.
|
||||
"""
|
||||
|
||||
def __init__(self, dispatcher: EventDispatcher, module_name: str) -> None:
|
||||
"""
|
||||
Initialize the module-scoped handler wrapper.
|
||||
|
||||
:param dispatcher: The EventDispatcher that owns the handler registry.
|
||||
:param module_name: The name of the module using this wrapper.
|
||||
"""
|
||||
self._dispatcher = dispatcher
|
||||
self._module_name = module_name
|
||||
|
||||
@property
|
||||
def module_events(self) -> EventHandlerMap:
|
||||
"""Handlers registered by this module only, grouped by event type."""
|
||||
return self._dispatcher.get_by_module(self._module_name)
|
||||
|
||||
def register(
|
||||
self,
|
||||
handler: EventHandler,
|
||||
event_types: tuple[EventType, ...],
|
||||
priority: int = Priority.NORMAL,
|
||||
) -> None:
|
||||
"""
|
||||
Register an event handler for this module.
|
||||
|
||||
The module name is automatically supplied.
|
||||
|
||||
:param handler: The handler function to register.
|
||||
:param event_types: Tuple of EventType values the handler responds to.
|
||||
:param priority: Dispatch priority (higher runs first).
|
||||
Defaults to Priority.NORMAL.
|
||||
"""
|
||||
self._dispatcher.register(
|
||||
handler=handler,
|
||||
event_types=event_types,
|
||||
module_name=self._module_name,
|
||||
priority=priority,
|
||||
)
|
||||
|
||||
def unregister(self, handler: EventHandler) -> bool:
|
||||
"""
|
||||
Unregister a handler from all event types it is registered for.
|
||||
|
||||
Only handlers registered by this module can be unregistered.
|
||||
|
||||
:param handler: The handler function to unregister.
|
||||
:return: True if handler was found and removed, False if not found or not owned.
|
||||
"""
|
||||
# Only allow unregistering handlers owned by this module.
|
||||
if self._dispatcher.get_handler_module(handler) != self._module_name:
|
||||
return False
|
||||
return self._dispatcher.unregister(handler)
|
||||
|
||||
def get(self, event_type: EventType) -> list[HandlerEntry]:
|
||||
"""
|
||||
Get handlers registered by this module for a specific event type.
|
||||
|
||||
:param event_type: The event type to look up.
|
||||
:return: List of (handler, module_name, priority) tuples for this module only.
|
||||
"""
|
||||
return self._dispatcher.get_by_module(self._module_name).get(
|
||||
event_type.value, []
|
||||
)
|
||||
@@ -0,0 +1,545 @@
|
||||
# Copyright 2026 Logan Fick
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Route registry, module-scoped wrapper, and dispatcher.
|
||||
|
||||
Internal infrastructure for managing HTTP route registration and dispatch.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from typing import TYPE_CHECKING, cast
|
||||
|
||||
from aiohttp import web
|
||||
from aiohttp.web import DynamicResource
|
||||
|
||||
from ..api.routes import RouteHandler, RouteInfo, RouteMark
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from types import ModuleType
|
||||
|
||||
from ..api.context import ModuleContext
|
||||
|
||||
logger = logging.getLogger("owlbot.web")
|
||||
|
||||
|
||||
class RouteRegistry:
|
||||
"""
|
||||
Holds all registered routes for a bot instance.
|
||||
|
||||
Routes are namespaced by module to prevent conflicts. Supports path
|
||||
patterns using aiohttp's ``{name}`` and ``{name:regex}`` syntax via
|
||||
``DynamicResource`` for pattern compilation and matching.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Initialize an empty route registry."""
|
||||
# Ordered list of (DynamicResource, RouteInfo) for pattern matching.
|
||||
# DynamicResource handles both plain and parameterized paths uniformly.
|
||||
self._routes: list[tuple[DynamicResource, RouteInfo]] = []
|
||||
# Maps module_name -> list of full_paths (for cleanup).
|
||||
self._module_routes: dict[str, list[str]] = {}
|
||||
logger.debug("RouteRegistry initialized.")
|
||||
|
||||
def register(
|
||||
self,
|
||||
path: str,
|
||||
handler: RouteHandler,
|
||||
*,
|
||||
methods: list[str] | None = None,
|
||||
module_name: str,
|
||||
) -> RouteInfo:
|
||||
"""
|
||||
Register a route handler.
|
||||
|
||||
:param path: URL path relative to module namespace. Supports
|
||||
``{name}`` and ``{name:regex}`` patterns.
|
||||
:param handler: Async function to handle the route.
|
||||
:param methods: List of HTTP methods. Default: ["GET"].
|
||||
:param module_name: Name of the module registering this route.
|
||||
:return: RouteInfo for the registered route.
|
||||
:raises ValueError: If route conflicts with existing route.
|
||||
"""
|
||||
if methods is None:
|
||||
methods = ["GET"]
|
||||
|
||||
if not path.startswith("/"):
|
||||
path = "/" + path
|
||||
|
||||
full_path = f"/owlbot/{module_name}{path}"
|
||||
|
||||
if any(info.full_path == full_path for _, info in self._routes):
|
||||
raise ValueError(f"Route '{full_path}' is already registered")
|
||||
|
||||
info = RouteInfo(
|
||||
path=path,
|
||||
full_path=full_path,
|
||||
methods=frozenset(m.upper() for m in methods),
|
||||
handler=handler,
|
||||
module_name=module_name,
|
||||
)
|
||||
|
||||
resource = DynamicResource(full_path)
|
||||
self._routes.append((resource, info))
|
||||
|
||||
if module_name not in self._module_routes:
|
||||
self._module_routes[module_name] = []
|
||||
self._module_routes[module_name].append(full_path)
|
||||
|
||||
module_logger = logging.getLogger(f"owlbot.modules.{module_name}.routes")
|
||||
module_logger.debug(
|
||||
f"Registered route '{full_path}' [{', '.join(info.methods)}]."
|
||||
)
|
||||
return info
|
||||
|
||||
def unregister(self, full_path: str) -> bool:
|
||||
"""
|
||||
Unregister a route by its full path.
|
||||
|
||||
:param full_path: The full route path including namespace.
|
||||
:return: True if route was found and removed, False otherwise.
|
||||
"""
|
||||
for i, (_, info) in enumerate(self._routes):
|
||||
if info.full_path == full_path:
|
||||
self._routes.pop(i)
|
||||
|
||||
if info.module_name in self._module_routes:
|
||||
self._module_routes[info.module_name] = [
|
||||
p
|
||||
for p in self._module_routes[info.module_name]
|
||||
if p != full_path
|
||||
]
|
||||
|
||||
module_logger = logging.getLogger(
|
||||
f"owlbot.modules.{info.module_name}.routes"
|
||||
)
|
||||
module_logger.debug(f"Unregistered route '{full_path}'.")
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def get(self, full_path: str) -> RouteInfo | None:
|
||||
"""
|
||||
Look up a route by its full path (exact match on registered pattern).
|
||||
|
||||
:param full_path: The full route path including namespace.
|
||||
:return: RouteInfo if found, None otherwise.
|
||||
"""
|
||||
for _, info in self._routes:
|
||||
if info.full_path == full_path:
|
||||
return info
|
||||
return None
|
||||
|
||||
def match(self, full_path: str) -> tuple[RouteInfo, dict[str, str]] | None:
|
||||
"""
|
||||
Match a request path against registered routes.
|
||||
|
||||
Scans routes in registration order (first match wins). Uses
|
||||
``DynamicResource._match()`` for both plain and parameterized paths.
|
||||
|
||||
:param full_path: The request path to match.
|
||||
:return: Tuple of (RouteInfo, match_info dict) if matched, None otherwise.
|
||||
"""
|
||||
for resource, info in self._routes:
|
||||
match_dict = resource._match(full_path) # no public API alternative
|
||||
if match_dict is not None:
|
||||
return info, match_dict
|
||||
return None
|
||||
|
||||
def get_all(self) -> dict[str, RouteInfo]:
|
||||
"""
|
||||
Get all registered routes.
|
||||
|
||||
:return: Dict mapping full paths to RouteInfo.
|
||||
"""
|
||||
return {info.full_path: info for _, info in self._routes}
|
||||
|
||||
def get_by_module(self, module_name: str) -> list[RouteInfo]:
|
||||
"""
|
||||
Get all routes registered by a specific module.
|
||||
|
||||
:param module_name: The module name.
|
||||
:return: List of RouteInfo for that module.
|
||||
"""
|
||||
paths = set(self._module_routes.get(module_name, []))
|
||||
return [info for _, info in self._routes if info.full_path in paths]
|
||||
|
||||
def unregister_by_module(self, module_name: str) -> int:
|
||||
"""
|
||||
Remove all routes registered by a specific module.
|
||||
|
||||
:param module_name: The module whose routes should be removed.
|
||||
:return: Number of routes removed.
|
||||
"""
|
||||
module_logger = logging.getLogger(f"owlbot.modules.{module_name}.routes")
|
||||
paths = list(self._module_routes.get(module_name, []))
|
||||
|
||||
if not paths:
|
||||
return 0
|
||||
|
||||
module_logger.debug(f"Unregistering all routes ({len(paths)} total).")
|
||||
count = 0
|
||||
for path in paths:
|
||||
if self.unregister(path):
|
||||
count += 1
|
||||
|
||||
self._module_routes.pop(module_name, None)
|
||||
return count
|
||||
|
||||
def register_from_module(self, module: ModuleType, module_name: str) -> None:
|
||||
"""
|
||||
Scan a Python module for @on_route-decorated functions and register them.
|
||||
|
||||
Looks for functions with the ``_owlbot_route`` attribute set by
|
||||
the ``@on_route`` decorator and registers each one.
|
||||
|
||||
:param module: The loaded Python module to scan.
|
||||
:param module_name: Name of the module (for ownership tracking).
|
||||
"""
|
||||
for obj in vars(module).values():
|
||||
if callable(obj):
|
||||
route_info = getattr(obj, "_owlbot_route", None)
|
||||
if route_info is not None:
|
||||
mark = cast("RouteMark", route_info)
|
||||
self.register(
|
||||
path=mark["path"],
|
||||
handler=obj,
|
||||
methods=mark["methods"],
|
||||
module_name=module_name,
|
||||
)
|
||||
|
||||
|
||||
class RouteDispatcher:
|
||||
"""
|
||||
Dispatches HTTP requests to registered module route handlers.
|
||||
|
||||
Looks up routes in the RouteRegistry, validates methods, creates
|
||||
RouteContext, and calls the handler with timeout and transaction management.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
get_module_context: Callable[[str], ModuleContext],
|
||||
handler_timeout: float,
|
||||
) -> None:
|
||||
"""
|
||||
Initialize the route dispatcher.
|
||||
|
||||
Creates and owns a :class:`RouteRegistry` internally.
|
||||
|
||||
:param get_module_context: Callable that looks up a
|
||||
ModuleContext by module name.
|
||||
:param handler_timeout: Timeout for route handlers in seconds.
|
||||
"""
|
||||
self._route_registry = RouteRegistry()
|
||||
self._get_module_context = get_module_context
|
||||
self._handler_timeout = handler_timeout
|
||||
|
||||
def register(
|
||||
self,
|
||||
path: str,
|
||||
handler: RouteHandler,
|
||||
*,
|
||||
methods: list[str] | None = None,
|
||||
module_name: str,
|
||||
) -> RouteInfo:
|
||||
"""
|
||||
Register a route handler.
|
||||
|
||||
Delegates to the internal RouteRegistry.
|
||||
|
||||
:param path: URL path relative to module namespace.
|
||||
:param handler: Async function to handle the route.
|
||||
:param methods: List of HTTP methods. Default: ["GET"].
|
||||
:param module_name: Name of the module registering this route.
|
||||
:return: RouteInfo for the registered route.
|
||||
:raises ValueError: If route conflicts with existing route.
|
||||
"""
|
||||
return self._route_registry.register(
|
||||
path=path,
|
||||
handler=handler,
|
||||
methods=methods,
|
||||
module_name=module_name,
|
||||
)
|
||||
|
||||
def unregister(self, full_path: str) -> bool:
|
||||
"""
|
||||
Unregister a route by its full path.
|
||||
|
||||
Delegates to the internal RouteRegistry.
|
||||
|
||||
:param full_path: The full route path including namespace.
|
||||
:return: True if route was found and removed, False otherwise.
|
||||
"""
|
||||
return self._route_registry.unregister(full_path)
|
||||
|
||||
def get(self, full_path: str) -> RouteInfo | None:
|
||||
"""
|
||||
Look up a route by its full path.
|
||||
|
||||
Delegates to the internal RouteRegistry.
|
||||
|
||||
:param full_path: The full route path including namespace.
|
||||
:return: RouteInfo if found, None otherwise.
|
||||
"""
|
||||
return self._route_registry.get(full_path)
|
||||
|
||||
def get_by_module(self, module_name: str) -> list[RouteInfo]:
|
||||
"""
|
||||
Get all routes registered by a specific module.
|
||||
|
||||
Delegates to the internal RouteRegistry.
|
||||
|
||||
:param module_name: The module name.
|
||||
:return: List of RouteInfo for that module.
|
||||
"""
|
||||
return self._route_registry.get_by_module(module_name)
|
||||
|
||||
def register_from_module(self, module: ModuleType, module_name: str) -> None:
|
||||
"""
|
||||
Scan a Python module for @on_route-decorated functions and register them.
|
||||
|
||||
Delegates to the internal RouteRegistry.
|
||||
|
||||
:param module: The loaded Python module to scan.
|
||||
:param module_name: Name of the module (for ownership tracking).
|
||||
"""
|
||||
self._route_registry.register_from_module(module, module_name)
|
||||
|
||||
def unregister_by_module(self, module_name: str) -> int:
|
||||
"""
|
||||
Remove all routes registered by a specific module.
|
||||
|
||||
Delegates to the internal RouteRegistry.
|
||||
|
||||
:param module_name: The module whose routes should be removed.
|
||||
:return: Number of routes removed.
|
||||
"""
|
||||
return self._route_registry.unregister_by_module(module_name)
|
||||
|
||||
async def dispatch(self, request: web.Request) -> web.Response:
|
||||
"""
|
||||
Dispatch an HTTP request to the appropriate module route handler.
|
||||
|
||||
Extracts module_name and path from the URL, matches it against
|
||||
registered routes (supporting path patterns), validates the HTTP
|
||||
method, and calls the handler.
|
||||
|
||||
:param request: The aiohttp request object.
|
||||
:return: HTTP response.
|
||||
"""
|
||||
module_name = request.match_info["module_name"]
|
||||
path = request.match_info.get("path", "")
|
||||
|
||||
relative_path = f"/{path}" if path else "/"
|
||||
|
||||
full_path = f"/owlbot/{module_name}{relative_path}"
|
||||
|
||||
result = self._route_registry.match(full_path)
|
||||
mod_logger = logging.getLogger(f"owlbot.modules.{module_name}.routes")
|
||||
if result is None:
|
||||
mod_logger.debug(f"No route registered for '{full_path}'.")
|
||||
return web.Response(status=404)
|
||||
|
||||
route_info, match_info = result
|
||||
|
||||
if request.method not in route_info.methods:
|
||||
allowed = ", ".join(sorted(route_info.methods))
|
||||
mod_logger.debug(
|
||||
f"Method {request.method} not allowed for '{full_path}' "
|
||||
f"(allowed: {allowed})"
|
||||
)
|
||||
return web.Response(status=405, headers={"Allow": allowed})
|
||||
|
||||
return await self._handle_module_route(request, route_info, match_info)
|
||||
|
||||
async def _handle_module_route(
|
||||
self,
|
||||
request: web.Request,
|
||||
route_info: RouteInfo,
|
||||
match_info: dict[str, str] | None = None,
|
||||
) -> web.Response:
|
||||
"""
|
||||
Handle an HTTP request to a module-registered route.
|
||||
|
||||
:param request: The aiohttp request object.
|
||||
:param route_info: Information about the registered route.
|
||||
:param match_info: Captured path parameters from pattern matching.
|
||||
:return: HTTP response.
|
||||
"""
|
||||
# Import here to avoid circular imports at module load time.
|
||||
from ..api.context import RouteContext
|
||||
|
||||
module_name = route_info.module_name
|
||||
mod_logger = logging.getLogger(f"owlbot.modules.{module_name}.routes")
|
||||
|
||||
module_ctx = self._get_module_context(module_name)
|
||||
|
||||
ctx = RouteContext(
|
||||
request=request,
|
||||
module=module_ctx,
|
||||
match_info=match_info if match_info is not None else {},
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
f"Calling route handler: {route_info.full_path} from module: {module_name}"
|
||||
)
|
||||
|
||||
# The checkout acquires a pooled connection for the
|
||||
# duration of this route invocation.
|
||||
async with module_ctx.storage._checkout():
|
||||
try:
|
||||
start = time.perf_counter()
|
||||
result = await asyncio.wait_for(
|
||||
route_info.handler(ctx), timeout=self._handler_timeout
|
||||
)
|
||||
elapsed = (time.perf_counter() - start) * 1000
|
||||
|
||||
# Handler succeeded, commit any database changes.
|
||||
await module_ctx.storage._commit()
|
||||
|
||||
mod_logger.debug(
|
||||
f"Route handler '{route_info.full_path}' "
|
||||
f"completed in {elapsed:.1f}ms."
|
||||
)
|
||||
|
||||
if result is None:
|
||||
return web.Response(status=204) # No Content.
|
||||
elif isinstance(result, web.Response):
|
||||
return result
|
||||
elif isinstance(result, dict):
|
||||
return web.json_response(result)
|
||||
else: # pragma: no branch — defensive against untyped handlers
|
||||
mod_logger.error( # type: ignore[unreachable]
|
||||
f"Route handler '{route_info.full_path}' returned "
|
||||
f"unsupported type: {type(result).__name__}"
|
||||
)
|
||||
return web.Response(status=500)
|
||||
|
||||
except TimeoutError:
|
||||
await module_ctx.storage._rollback()
|
||||
mod_logger.warning(
|
||||
f"Route handler '{route_info.full_path}' timed out "
|
||||
f"after {self._handler_timeout}s."
|
||||
)
|
||||
return web.Response(status=500)
|
||||
except Exception as e:
|
||||
await module_ctx.storage._rollback()
|
||||
mod_logger.exception(
|
||||
f"Route handler '{route_info.full_path}' raised exception: {e}"
|
||||
)
|
||||
return web.Response(status=500)
|
||||
|
||||
|
||||
class ModuleRoutes:
|
||||
"""
|
||||
Module-scoped wrapper around RouteDispatcher.
|
||||
|
||||
This wrapper auto-supplies the module name for route operations,
|
||||
so modules don't need to know the internal routing namespace.
|
||||
Follows the same pattern as ModuleCommands.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, dispatcher: RouteDispatcher, module_name: str, public_base_url: str
|
||||
) -> None:
|
||||
"""
|
||||
Initialize the module-scoped routes wrapper.
|
||||
|
||||
:param dispatcher: The RouteDispatcher that owns the route registry.
|
||||
:param module_name: The name of the module using this wrapper.
|
||||
:param public_base_url: The public base URL for building route URLs.
|
||||
"""
|
||||
self._dispatcher = dispatcher
|
||||
self._module_name = module_name
|
||||
self._public_base_url = public_base_url
|
||||
|
||||
@property
|
||||
def module_routes(self) -> list[RouteInfo]:
|
||||
"""Routes registered by this module."""
|
||||
return self._dispatcher.get_by_module(self._module_name)
|
||||
|
||||
def url_for(self, path: str) -> str:
|
||||
"""
|
||||
Build a public URL for a route registered by this module.
|
||||
|
||||
:param path: The route path (e.g., "/list").
|
||||
:return: Full public URL (e.g., "http://host/owlbot/quotes/list").
|
||||
"""
|
||||
return f"{self._public_base_url}{self._full_path(path)}"
|
||||
|
||||
def register(
|
||||
self,
|
||||
path: str,
|
||||
handler: RouteHandler,
|
||||
*,
|
||||
methods: list[str] | None = None,
|
||||
) -> RouteInfo:
|
||||
"""
|
||||
Register a route handler for this module.
|
||||
|
||||
The module name is automatically supplied.
|
||||
|
||||
:param path: URL path relative to module namespace (e.g., "/stats").
|
||||
:param handler: Async function to handle the route.
|
||||
:param methods: List of HTTP methods (e.g., ["GET"]). Default: ["GET"].
|
||||
:return: RouteInfo for the registered route.
|
||||
:raises ValueError: If route conflicts with existing route.
|
||||
"""
|
||||
return self._dispatcher.register(
|
||||
path=path,
|
||||
handler=handler,
|
||||
methods=methods,
|
||||
module_name=self._module_name,
|
||||
)
|
||||
|
||||
def unregister(self, path: str) -> bool:
|
||||
"""
|
||||
Unregister a route by its relative path.
|
||||
|
||||
:param path: Relative route path (e.g., "/stats").
|
||||
:return: True if route was found and removed, False otherwise.
|
||||
"""
|
||||
return self._dispatcher.unregister(self._full_path(path))
|
||||
|
||||
def get(self, path: str) -> RouteInfo | None:
|
||||
"""
|
||||
Look up a route by its relative path.
|
||||
|
||||
:param path: Relative route path (e.g., "/stats").
|
||||
:return: RouteInfo if found, None otherwise.
|
||||
"""
|
||||
return self._dispatcher.get(self._full_path(path))
|
||||
|
||||
def exists(self, path: str) -> bool:
|
||||
"""
|
||||
Check if a route is registered at the given relative path.
|
||||
|
||||
:param path: Relative route path (e.g., "/stats").
|
||||
:return: True if the route exists, False otherwise.
|
||||
"""
|
||||
return self.get(path) is not None
|
||||
|
||||
def _full_path(self, path: str) -> str:
|
||||
"""
|
||||
Normalize a relative path into the full namespaced path.
|
||||
|
||||
:param path: Relative route path (e.g., "/list" or "list").
|
||||
:return: Full path (e.g., "/owlbot/quotes/list").
|
||||
"""
|
||||
if not path.startswith("/"):
|
||||
path = "/" + path
|
||||
return f"/owlbot/{self._module_name}{path}"
|
||||
Reference in New Issue
Block a user