"""
**File:** ``functions/__init__.py``
**Region:** ``ds-common-placeholder-py-lib``
Description
-----------
The function registry (contract ยง5). Adding a function is a contract change:
registry, vectors, and version bump together.
"""
from __future__ import annotations
import inspect
from dataclasses import dataclass
from types import MappingProxyType
from typing import TYPE_CHECKING, Any
from ..grammar import _NAME, LOOKUP
from . import secrets, strings, tables, time, values
if TYPE_CHECKING:
from collections.abc import Callable, Mapping
from ..context import Context
[docs]
@dataclass(frozen=True)
class Param:
"""A function parameter. ``default`` is ``None`` for a required one;
``check`` validates a string value and raises ``argument``."""
name: str
default: Any = None
check: Callable[[str], object] | None = None
[docs]
@dataclass(frozen=True)
class FunctionSpec:
"""One registry entry."""
name: str
impl: Callable[..., Any]
"""Called with the argument list; a ``secret`` function, which needs the
context's tenant and records what it reads, with the context first."""
params: tuple[Param, ...] = ()
variadic: bool = False
secret: bool = False
lazy: bool = False
"""``impl`` gets one zero-argument callable per argument instead of its
value; calling it reads the value, or raises ``MissingValue``."""
min_variadic: int = 1
raw: bool = False
"""``impl`` gets each argument's value as it is: any JSON value, or what
a provider returned (a DataFrame), ``None`` for ``null`` or blank. Its
result is converted to plain JSON."""
[docs]
def call(self, ctx: Context, args: list[Any]) -> Any:
"""Run the function: built-ins depend only on *args*; the secret
functions also get *ctx*."""
return self.impl(ctx, args) if self.secret else self.impl(args)
@property
def min_args(self) -> int:
"""Smallest accepted argument count."""
if self.variadic:
return self.min_variadic
return sum(1 for p in self.params if p.default is None)
@property
def max_args(self) -> int | None:
"""Largest accepted argument count, ``None`` for no limit."""
return None if self.variadic else len(self.params)
_TZ = Param("timezone", "UTC", time.check_timezone)
_LANGUAGE = Param("language", "EN", time.check_language)
_AT = Param("at", time.NOT_GIVEN, time.check_at)
"""The time a date function computes from; not given, the current time."""
def _dated(name: str, impl: Callable[[list[Any]], Any], *params: Param) -> FunctionSpec:
return FunctionSpec(name, impl, (*(params or (_TZ,)), _AT))
def _raw(name: str, impl: Callable[[list[Any]], Any], *params: str) -> FunctionSpec:
return FunctionSpec(name, impl, tuple(Param(param) for param in params), raw=True)
FUNCTIONS: Mapping[str, FunctionSpec] = MappingProxyType(
{
spec.name: spec
for spec in (
FunctionSpec("get_secret", secrets.get_secret, (Param("key"),), secret=True),
FunctionSpec("secret", secrets.secret, (Param("value"),), secret=True),
_dated("get_start_last_month", time.get_start_last_month),
_dated("get_end_last_month", time.get_end_last_month),
_dated("get_start_date_last_month", time.get_start_date_last_month),
_dated("get_end_date_last_month", time.get_end_date_last_month),
_dated("get_last_month_period", time.get_last_month_period, _LANGUAGE, _TZ),
_dated("get_current_date", time.get_current_date),
_dated("get_day_of_month", time.get_day_of_month),
_dated("get_previous_day_of_month", time.get_previous_day_of_month),
_dated("get_hour", time.get_hour),
_dated("get_previous_hour", time.get_previous_hour),
FunctionSpec("get_iso_timestamp_now", time.get_iso_timestamp_now, (_TZ,)),
FunctionSpec("get_unix_timestamp_now", time.get_unix_timestamp_now, (_TZ,)),
FunctionSpec("str_join", strings.str_join, variadic=True),
FunctionSpec("coalesce", values.coalesce, variadic=True, lazy=True, min_variadic=2),
_raw("get_column_as_list", tables.get_column_as_list, "column", "table"),
_raw("get_value_from_dataframe", tables.get_value_from_dataframe, "index", "column", "table"),
_raw("dataframe_to_json_array", tables.dataframe_to_json_array, "table"),
_raw("json_parse", tables.json_parse, "text"),
_raw("is_empty", tables.is_empty, "value"),
_raw("is_string_empty", tables.is_string_empty, "value"),
_raw("is_list_empty", tables.is_list_empty, "value"),
_raw("is_dict_empty", tables.is_dict_empty, "value"),
_raw("is_dataframe_empty", tables.is_dataframe_empty, "table"),
)
}
)
"""Function name to spec: ``secret`` marks the functions that read secrets."""
[docs]
def service_function(name: str, fn: Callable[..., Any]) -> FunctionSpec:
"""A function a service adds to its context: called with each
argument's value, positionally, as a ``raw`` function. Its signature
gives the argument counts it accepts.
Raises:
ValueError: If *name* is not a function name, is a built-in one, or
*fn* has a required keyword-only parameter.
TypeError: If *fn* is not callable.
"""
if not isinstance(name, str) or not _NAME.fullmatch(name):
raise ValueError(f"not a function name: {name!r}")
if name in FUNCTIONS or name == LOOKUP:
raise ValueError(f"{name} is a built-in function")
if not callable(fn):
raise TypeError(f"function {name} is not callable")
if inspect.iscoroutinefunction(fn):
raise TypeError(f"function {name} is async: resolve calls functions synchronously")
params: list[Param] = []
variadic = False
try:
signature: inspect.Signature | None = inspect.signature(fn)
except (TypeError, ValueError):
signature = None
if signature is None:
variadic = True
else:
for param in signature.parameters.values():
if param.kind is param.VAR_POSITIONAL:
variadic = True
elif param.kind is param.KEYWORD_ONLY and param.default is param.empty:
raise ValueError(f"function {name} has a required keyword-only parameter")
elif param.kind in (param.POSITIONAL_ONLY, param.POSITIONAL_OR_KEYWORD):
# The default is only a marker that the parameter is optional.
params.append(Param(param.name, None if param.default is param.empty else ""))
def impl(args: list[Any]) -> Any:
return fn(*args) # the resolver reduces any failure to its type
if variadic:
required = sum(1 for param in params if param.default is None)
return FunctionSpec(name, impl, variadic=True, min_variadic=required, raw=True)
return FunctionSpec(name, impl, tuple(params), raw=True)
__all__ = ["FUNCTIONS", "FunctionSpec", "Param", "service_function"]