Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion custom_components/pyscript/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,12 @@ async def _call(self, data: DispatchData) -> None:
accepted = {a.arg for a in func_args.args + func_args.kwonlyargs}
call_kwargs = {k: v for k, v in data.func_args.items() if k in accepted}
result = await data.call_ast_ctx.call_func(self.eval_func, None, **call_kwargs)
except asyncio.CancelledError:
# the call was killed while running; let result handlers answer their callers
self.logger.debug("Call cancelled for %s", self.name)
for result_handler_dec in result_handlers:
await self.safe_await(result_handler_dec.handle_call_canceled(data))
raise
except Exception as e:
for result_handler_dec in result_handlers:
await self.safe_await(result_handler_dec.handle_call_exception(data, e))
Expand All @@ -308,7 +314,7 @@ async def _call(self, data: DispatchData) -> None:
await self.safe_await(result_handler_dec.handle_call_result(data, result))

async def dispatch(self, data: DispatchData) -> None:
"""Handle a trigger dispatch: run guards, create a context, and invoke the function."""
"""Handle a trigger dispatch: run the trigger handlers, then start the call."""
_LOGGER.debug("Dispatching for %s: %s", self.name, data)

decorators = self.get_decorators(TriggerHandlerDecorator)
Expand All @@ -319,6 +325,10 @@ async def dispatch(self, data: DispatchData) -> None:
await self.safe_await(result_handler_dec.handle_call_canceled(data))
return

await self.start_call(data)

async def start_call(self, data: DispatchData) -> None:
"""Create a context and invoke the function; an explicit call starts here, without the trigger handlers."""
action_ast_ctx = AstEval(
f"{self.eval_func.global_ctx_name}.{self.eval_func.name}", self.eval_func.global_ctx
)
Expand All @@ -339,4 +349,5 @@ async def dispatch(self, data: DispatchData) -> None:
)

task = Function.create_task(self._call(data), ast_ctx=action_ast_ctx)
data.call_task = task
Function.task_done_callback_ctx(task, action_ast_ctx)
6 changes: 5 additions & 1 deletion custom_components/pyscript/decorator_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

from abc import ABC, abstractmethod
import asyncio
from collections.abc import Awaitable
from dataclasses import dataclass, field
from enum import StrEnum
Expand Down Expand Up @@ -41,11 +42,14 @@ class DispatchData:
"""Data for a dispatch event."""

func_args: dict[str, Any]
trigger: TriggerDecorator | None = field(default=None, kw_only=True)
# the decorator that started the call: a trigger, or one making an explicit call
trigger: Decorator | None = field(default=None, kw_only=True)
trigger_context: dict[str, Any] = field(default_factory=dict, kw_only=True)

call_ast_ctx: AstEval | None = field(default=None, kw_only=True)
hass_context: Context | None = field(default=None, kw_only=True)
# the task running the function, set by the manager once the call is started
call_task: asyncio.Task | None = field(default=None, kw_only=True)


class Decorator(ABC):
Expand Down
78 changes: 76 additions & 2 deletions custom_components/pyscript/decorators/base.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
"""Base mixins for pyscript decorators."""

from abc import ABC
from abc import ABC, abstractmethod
import asyncio
from contextlib import suppress
import functools
import logging
from typing import Any, ClassVar

import voluptuous as vol

from ..decorator import FunctionDecoratorManager
from ..decorator_abc import Decorator
from ..decorator_abc import CallResultHandlerDecorator, Decorator, DispatchData
from ..eval import AstEval, Function

_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -69,3 +72,74 @@ async def check_expression_vars(self, state_vars: dict[str, Any]) -> bool:
except Exception as exc:
await self.dm.handle_exception(exc)
return False


_RESPONSE_FUTURE = "response_future"


class RequestResponseDecorator(CallResultHandlerDecorator, ABC):
"""
Base for a decorator that answers a request with the result of the call it starts.

Exceptions and cancelled calls give None by default; override handle_call_exception and
handle_call_canceled to map them to the response.
"""

@abstractmethod
async def dispatch_request(self, data: DispatchData) -> None:
"""Start the call for a request: through the trigger handlers, or directly."""

async def handle_request(self, func_args: dict[str, Any], timeout: float | None = None) -> Any:
"""
Start a call for a request and wait for the response.

If the wait is cancelled (the caller went away), the running function is cancelled too,
and the cancellation is passed on once it has finished.
On timeout, TimeoutError is raised and the function keeps running.
"""
future = self.dm.hass.loop.create_future()
data = DispatchData(func_args, trigger=self, trigger_context={_RESPONSE_FUTURE: future})
await self.dispatch_request(data)
if data.call_task is not None:
data.call_task.add_done_callback(functools.partial(self._call_done, data))
try:
return await asyncio.wait_for(future, timeout)
except asyncio.CancelledError:
if data.call_task is not None:
data.call_task.cancel()
# like awaiting a task, or a script stopping the script it called: wait for the
# function's except/finally, so the caller (eg: a restarted automation) doesn't go
# on while the function is still cleaning up
with suppress(asyncio.CancelledError):
await data.call_task
# the caller's own cancellation, not the function's
raise

def _call_done(self, data: DispatchData, task: asyncio.Task) -> None:
"""Respond if the call ended without the result handlers doing it, so the caller can't hang."""
future = data.trigger_context[_RESPONSE_FUTURE]
if future.done():
return
if task.cancelled():
# cancelled before it started
answer = self.handle_call_canceled(data)
else:
# the call failed outside the function (eg: a call handler raised); the error is already logged
answer = self.handle_call_exception(
data, RuntimeError("call failed before the function ran, see the log for details")
)
self.dm.hass.async_create_task(answer)

def respond(self, data: DispatchData, result: Any = None, exc: BaseException | None = None) -> None:
"""Respond to the waiting caller with a result or an exception; only to this decorator's own requests."""
future = data.trigger_context.get(_RESPONSE_FUTURE)
if data.trigger is not self or future is None or future.done():
return
if exc is not None:
future.set_exception(exc)
else:
future.set_result(result)

async def handle_call_result(self, data: DispatchData, result: Any) -> None:
"""Respond with the function result."""
self.respond(data, result)
139 changes: 114 additions & 25 deletions custom_components/pyscript/decorators/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,70 @@

import ast
from collections import OrderedDict
import copy
import io
import logging
import typing

import voluptuous as vol
import yaml

from homeassistant.const import SERVICE_RELOAD
from homeassistant.core import ServiceCall, SupportsResponse
from homeassistant.core import ServiceCall, ServiceResponse, SupportsResponse
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.service import async_set_service_schema

from .. import DOMAIN, SERVICE_JUPYTER_KERNEL_START, AstEval, Function, State
from .. import DOMAIN, SERVICE_JUPYTER_KERNEL_START, Function, State
from ..decorator import FunctionDecoratorManager
from ..decorator_abc import Decorator
from ..decorator_abc import DispatchData
from .base import RequestResponseDecorator

_LOGGER = logging.getLogger(__name__)

# the UI input for a parameter annotated with a simple type
_ANNOTATION_SELECTORS = {
"bool": {"boolean": {}},
"int": {"number": {}},
"float": {"number": {"mode": "box", "step": "any"}},
"str": {"text": {}},
"dict": {"object": {}},
"list": {"object": {}},
}


def _annotation_selector(annotation: ast.expr | None) -> dict | None:
"""Return the selector for a parameter's type annotation, or None if there's no fitting one."""
match annotation:
case (
ast.BinOp(op=ast.BitOr(), left=inner, right=ast.Constant(value=None))
| ast.BinOp(op=ast.BitOr(), left=ast.Constant(value=None), right=inner)
):
return _annotation_selector(inner)
case ast.Subscript(value=ast.Name(id="Optional") | ast.Attribute(attr="Optional"), slice=inner):
return _annotation_selector(inner)
case ast.Subscript(value=inner):
# a parameterized type, eg: list[int]
return _annotation_selector(inner)
case ast.Name(id=name) if name in _ANNOTATION_SELECTORS:
return copy.deepcopy(_ANNOTATION_SELECTORS[name])
return None


def _constant_default(default: ast.expr) -> bool | int | float | str | None:
"""
Return a default value written as a constant in the signature, or None.

The description is published to every client, so a computed default (eg: a secret from
the config) must not end up in it.
"""
match default:
case ast.Constant(value=bool() | int() | float() | str() as value):
return value
case ast.UnaryOp(op=ast.USub(), operand=ast.Constant(value=int() | float() as value)) if (
not isinstance(value, bool)
):
return -value
return None


def service_validator(args: list[str]) -> list[str]:
"""Validate and normalize service name."""
Expand All @@ -37,16 +84,24 @@ def service_validator(args: list[str]) -> list[str]:
return [domain, name]


class ServiceDecorator(Decorator):
"""Implementation for @service."""
class ServiceDecorator(RequestResponseDecorator):
"""
Implementation for @service.

A service call is an explicit call, not a trigger: it starts the call directly, so trigger
handlers (@state_active, @time_active) don't apply, while call handlers (@task_unique) do.
"""

name = "service"
args_schema = vol.Schema(vol.All(vol.Length(max=1), service_validator))
kwargs_schema = vol.Schema(
{vol.Optional("supports_response", default=SupportsResponse.NONE): vol.Coerce(SupportsResponse)}
)

# @service is only applied to functions
dm: FunctionDecoratorManager
description: dict
data_schema: vol.Schema

async def validate(self) -> None:
"""Validate the arguments."""
Expand All @@ -65,7 +120,25 @@ async def validate(self) -> None:
f"@service conflicts with builtin service"
)

ast_funcdef = typing.cast(FunctionDecoratorManager, self.dm).eval_func.func_def
ast_funcdef = self.dm.eval_func.func_def
args = ast_funcdef.args
# the default value expressions; they belong to the last positional parameters,
# positional-only ones included
positional = args.posonlyargs + args.args
with_default = positional[len(positional) - len(args.defaults) :]
defaults = {arg.arg: default for arg, default in zip(with_default, args.defaults, strict=True)}
defaults |= {
arg.arg: default
for arg, default in zip(args.kwonlyargs, args.kw_defaults, strict=True)
if default is not None
}
# the arguments a service call passes to the function besides the service data
call_added = ("trigger_type", "context")
# the parameters the caller fills: positional-only ones can't be passed by name,
# and the ones a service call adds itself are set even when not passed
params = [arg.arg for arg in args.args + args.kwonlyargs if arg.arg not in call_added]
required = {name for name in params if name not in defaults}

desc = ast.get_docstring(ast_funcdef)
if desc is None or desc == "":
desc = f"pyscript function {ast_funcdef.name}()"
Expand All @@ -84,36 +157,51 @@ async def validate(self) -> None:
)
raise exc
else:
annotations = {arg.arg: arg.annotation for arg in args.args + args.kwonlyargs}
fields = OrderedDict()
for arg in ast_funcdef.args.posonlyargs + ast_funcdef.args.args:
fields[arg.arg] = OrderedDict(description=f"argument {arg.arg}")
for name in params:
field = fields[name] = OrderedDict()
if name in required:
field["required"] = True
elif (default := _constant_default(defaults[name])) is not None:
field["default"] = default
if selector := _annotation_selector(annotations[name]):
field["selector"] = selector
self.description = {"description": desc, "fields": fields}

async def _service_callback(self, call: ServiceCall) -> None:
# Like other integrations' services, Home Assistant checks the service data against this
# schema before the call, so a typo in a field name or a missing argument fails the call
self.data_schema = vol.Schema(
{(vol.Required if name in required else vol.Optional)(name): object for name in params},
extra=vol.ALLOW_EXTRA if args.kwarg else vol.PREVENT_EXTRA,
)

async def _service_callback(self, call: ServiceCall) -> ServiceResponse:
_LOGGER.info("Service callback: %s", call.service)

# use a new AstEval context so it can run fully independently
# of other instances (except for global_ctx which is common)
global_ctx = self.dm.eval_func.global_ctx
ast_ctx = AstEval(self.dm.name, global_ctx)
Function.install_ast_funcs(ast_ctx)
func_args = {
"trigger_type": "service",
"context": call.context,
}
func_args.update(call.data)

async def do_service_call(func, ast_ctx, data):
try:
_LOGGER.debug("Service call start: %s", func.name)
return await func.call(ast_ctx, **data)
except Exception as exc:
await self.dm.handle_exception(exc)
return None
result = await self.handle_request(func_args)
if call.return_response and result is None:
# like HA scripts: a call that was skipped or returned nothing gives an empty response
return {}
return result

async def dispatch_request(self, data: DispatchData) -> None:
"""Start the call directly: a service call is an explicit call, not a trigger."""
await self.dm.start_call(data)

task = Function.create_task(do_service_call(self.dm.eval_func, ast_ctx, func_args))
await task
return task.result()
async def handle_call_exception(self, data: DispatchData, exc: Exception) -> None:
"""Fail the service call when the function raised; the manager still logs the exception."""
if not isinstance(exc, HomeAssistantError):
error = HomeAssistantError(f"{self.dm.name}() raised {type(exc).__name__}: {exc}")
error.__cause__ = exc
exc = error
self.respond(data, exc=exc)

async def start(self) -> None:
"""Register the service."""
Expand All @@ -126,6 +214,7 @@ async def start(self) -> None:
name,
self._service_callback,
self.kwargs.get("supports_response"),
self.data_schema,
)
async_set_service_schema(Function.hass, domain, name, self.description)

Expand Down
Loading
Loading