"""
**File:** ``resolve.py``
**Region:** ``ds-common-placeholder-py-lib``
Description
-----------
Walks a JSON value and resolves every placeholder (contract §8.1, §8.2).
"""
from __future__ import annotations
import copy
import json
import math
from collections.abc import Iterable, Iterator, Mapping, Sequence
from collections.abc import Set as AbstractSet
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any
from .context import _step, secret_forms
from .errors import ErrorCode, MissingValue, PlaceholderError, _Absent, _Blank
from .functions.tables import _is_frame, frame_rows, json_value
from .grammar import (
BLANK,
TYPES,
Call,
Expr,
Literal,
Placeholder,
Reference,
Segment,
Text,
calls,
namespaces,
parse,
parse_path,
reference_text,
to_type,
write,
)
if TYPE_CHECKING:
from collections.abc import Callable
from .context import Context
from .functions import FunctionSpec
[docs]
def pointer(path: str, key: str | int) -> str:
"""Append *key* to a JSON Pointer."""
return f"{path}/{str(key).replace('~', '~0').replace('/', '~1')}"
[docs]
def context_pointer(namespace: str, path: tuple[str, ...]) -> str:
"""The JSON Pointer of a value in the context: ``/<namespace>/<path…>``."""
at = pointer("", namespace)
for key in path:
at = pointer(at, key)
return at
[docs]
def is_verbatim(at: str, verbatim: frozenset[str]) -> bool:
"""Whether the value at the pointer *at* is, or is inside, a verbatim path."""
return any(at == path or at.startswith(path + "/") for path in verbatim)
READ_DEPTH_MAX = 64
"""How many context values can be read inside one another, each through a
placeholder the one before it holds."""
Paths = Iterable[str | Sequence[str | int]] | None
"""The ``verbatim`` argument: paths, each a dotted string
(``tasks.0.settings.'a.b'``) or a list of keys (``["tasks", 0, "a.b"]``)."""
[docs]
def verbatim_pointers(paths: Paths) -> frozenset[str]:
"""The JSON Pointers of the *verbatim* paths a caller passed.
Raises:
TypeError: If *paths* is a single string, or a path is neither a
string nor a list of keys.
ValueError: If a string path is not a path, or a list of keys is empty.
"""
if paths is None:
return frozenset()
if isinstance(paths, str | bytes):
raise TypeError("verbatim takes a list of paths, not a single string")
pointers = set()
for path in paths:
target = ""
for key in path_keys(path):
target = pointer(target, key)
pointers.add(target)
return frozenset(pointers)
Path = str | Sequence[str | int]
"""A path to a value: a dotted string (``tasks.0.settings.'a.b'``) or a list
of keys (``["tasks", 0, "a.b"]``)."""
[docs]
def path_keys(path: Path) -> tuple[str, ...]:
"""The keys of *path*, array indexes as strings.
Raises:
TypeError: If *path* is neither a string nor a list of keys.
ValueError: If a string is not a path, or a list of keys is empty.
"""
if isinstance(path, str):
return parse_path(path)
if isinstance(path, Sequence) and not isinstance(path, bytes | bytearray):
keys = tuple(str(_path_key(key)) for key in path)
if not keys:
raise ValueError(f"not a path: {path!r}")
return keys
raise TypeError(f"a path is a string or a list of keys, not {type(path).__name__}")
def _path_key(key: object) -> str | int:
"""A key of a path given as a list: a string (a ``str`` enum by its
value), or an array index."""
if isinstance(key, str):
return str.__str__(key)
if isinstance(key, int) and not isinstance(key, bool):
if key < 0:
raise ValueError(f"an array index is not negative: {key}")
return int(key)
raise TypeError("a path given as a list holds keys (strings) and array indexes (ints)")
[docs]
def as_written(value: Any) -> Any:
"""A verbatim value: a copy, with plain ``dict`` and ``list`` containers
as the rest of a resolved value has."""
if isinstance(value, Mapping):
return {key: as_written(item) for key, item in value.items()}
if isinstance(value, list):
return [as_written(item) for item in value]
return value
[docs]
def parse_at(text: str, path: str) -> list[Segment]:
""":func:`parse` with *path* set on any error."""
try:
return parse(text)
except PlaceholderError as err:
err.path = path
raise
[docs]
def check_key(key: Any, path: str) -> Any:
"""Reject a placeholder in an object key (contract §3).
Returns:
The key.
Raises:
PlaceholderError: ``syntax``.
"""
if not isinstance(key, str):
return key
segments = parse_at(key, path)
for segment in segments:
if isinstance(segment, Placeholder):
raise PlaceholderError(ErrorCode.SYNTAX, "placeholder in an object key", path=path, placeholder=segment.raw)
return "".join(segment.value for segment in segments if isinstance(segment, Text))
[docs]
def is_missing(value: Any) -> bool:
"""``None`` and empty or blank strings are missing (contract §8.2)."""
return value is None or (isinstance(value, str) and not value.strip(BLANK))
def _holds_secret(text: str, secrets: AbstractSet[str]) -> bool:
return any(form in text for secret in secrets for form in secret_forms(secret))
[docs]
def as_text(value: Any) -> str:
"""Render a value inside a longer string (contract §8.1).
Raises:
PlaceholderError: ``type`` for an object, array, or non-JSON value.
"""
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, str):
return value
if isinstance(value, int):
return str(value)
if isinstance(value, float):
return json.dumps(value)
raise PlaceholderError(ErrorCode.TYPE, f"{_with_article(_type_name(value))} cannot be embedded in text")
[docs]
def json_text(value: Any) -> str:
"""*value* as compact JSON text, non-ASCII escaped: ``lookup``'s ``json``
format. A DataFrame, at any depth, is its rows, as
``dataframe_to_json_array`` gives them.
Raises:
PlaceholderError: ``type`` if the value, or a value in it, is not JSON.
"""
value = json_value(_frames_as_rows(value))
_check_json(value)
return json.dumps(value, separators=(",", ":"))
def _frames_as_rows(value: Any) -> Any:
if _is_frame(value):
return frame_rows(value)
if isinstance(value, Mapping):
return {key: _frames_as_rows(item) for key, item in value.items()}
if isinstance(value, list | tuple):
return [_frames_as_rows(item) for item in value]
return value
def _with_article(noun: str) -> str:
return ("an " if noun[:1] in "aeiou" else "a ") + noun
def _type_name(value: Any) -> str:
if isinstance(value, Mapping):
return "object"
if isinstance(value, list):
return "array"
return type(value).__name__
def _check_json(value: Any) -> None:
if value is None or isinstance(value, str | bool | int):
return
if isinstance(value, float):
if not math.isfinite(value):
raise PlaceholderError(ErrorCode.TYPE, "value is not a finite number")
return
if isinstance(value, list):
for item in value:
_check_json(item)
return
if isinstance(value, Mapping):
for key, item in value.items():
if not isinstance(key, str):
raise PlaceholderError(ErrorCode.TYPE, "object key is not a string")
_check_json(item)
return
raise PlaceholderError(ErrorCode.TYPE, f"a {_type_name(value)} is not a JSON value")
SECRET_PART_MIN = 6
"""The shortest string in a function's result over a secret that is
recorded as a secret."""
def _missing(exc: MissingValue) -> PlaceholderError:
if not isinstance(exc, _Absent):
return PlaceholderError(ErrorCode.MISSING_VALUE, _Absent.message)
err = PlaceholderError(ErrorCode.MISSING_VALUE, exc.message, reference=exc.reference)
if exc.namespaces is not None:
_scope(err, exc.namespaces)
return err
def _scope(err: PlaceholderError, found: frozenset[str]) -> None:
"""Set the namespaces of the part that failed, once: the innermost part
sets them, and the placeholders around it keep them."""
if not err._scoped:
err.namespaces = found
err._scoped = True
def _read(expr: Expr, err: PlaceholderError) -> frozenset[str]:
"""The namespaces *expr* reads, with the one of the reference at fault."""
found = namespaces(expr)
return found | {err.reference.partition(".")[0]} if err.reference else found
def _attribute(err: PlaceholderError, node: object) -> None:
"""Name *node* as the reference at fault, unless one already is."""
if err.reference is None and isinstance(node, Reference):
err.reference = reference_text(node)
_NOT_YET = frozenset({ErrorCode.UNKNOWN_NAMESPACE, ErrorCode.MISSING_VALUE})
"""What a context cannot resolve yet: a later one may have the value."""
def _written(text: str, secrets: AbstractSet[str]) -> str:
"""*text*, a resolved value, as template text a later resolve reads back
exactly: as it is when it holds no ``@`` or ``{`` (nothing in it, or at
its edges next to other text, can start a placeholder), else as one
self-contained placeholder, ``@{'…'}``, or ``@{secret, '…'}`` when it
holds a secret this context read, so the later context records it (its
``scrub`` masks it, SQL refuses it)."""
quoted = "'" + text.replace("'", "''") + "'"
if any(secret in text for secret in secrets):
return "@{secret, " + quoted + "}"
if "@" in text or "{" in text:
return "@{" + quoted + "}"
return text
def _written_value(value: Any, secrets: AbstractSet[str]) -> Any:
"""*value* with every string in it (keys aside) :func:`_written`."""
if isinstance(value, str):
return _written(value, secrets)
if isinstance(value, Mapping):
return {key: _written_value(item, secrets) for key, item in value.items()}
if isinstance(value, list):
return [_written_value(item, secrets) for item in value]
return value
_SECRET_CALLS = ("get_secret", "secret")
def _nests_secret(expr: Expr) -> bool:
"""Whether *expr* is a call with a ``get_secret`` or ``secret`` call in
its arguments."""
return isinstance(expr, Call) and any(call is not expr and call.name in _SECRET_CALLS for call in calls(expr))
class _Resolver:
"""Resolves placeholders against one context. Every path is a JSON
Pointer into the context (``/<namespace>/<key…>``)."""
def __init__(self, ctx: Context) -> None:
self.ctx = ctx
# The context values being read, outermost first: reading one again
# inside itself is a cycle.
self.reading: list[tuple[str, tuple[str, ...]]] = []
def whole(self, *, strict: bool = True) -> dict[str, Any]:
"""The whole context, resolved: every namespace, ``tenant_id`` first."""
out: dict[str, Any] = {}
for ns in self.ctx.providers:
out[ns] = self.at((ns,), strict=strict)
return out
def at(self, keys: tuple[str, ...], *, strict: bool = True) -> Any:
"""The value at *keys* in the context, resolved: its placeholders
replaced, as written if it is verbatim, as SQL where it is SQL. Not
*strict*, a template: see :meth:`template`.
Raises:
PlaceholderError: ``unknown_namespace``, ``missing_value`` when
there is no value at *keys*, or any error inside the value
(not *strict*: any but those two).
"""
ns, path = keys[0], keys[1:]
here = context_pointer(ns, path)
reference = reference_text(Reference(ns, path))
provider = self.ctx.providers.get(ns)
if provider is None:
raise PlaceholderError(
ErrorCode.UNKNOWN_NAMESPACE, f"namespace {ns!r} is not available here", path=here, reference=reference
)
with self.reading_value(ns, path):
try:
try:
raw = _provider_value(provider, path)
except MissingValue:
return self.through_placeholder(provider, ns, path)
except MissingValue as exc:
absent = exc if isinstance(exc, _Absent) else _Absent(reference=reference)
if absent.namespaces is None:
absent.namespaces = frozenset({ns})
err = _missing(absent)
err.path = err.path or here
raise err from None
if is_verbatim(here, self.ctx._verbatim):
return as_written(raw)
return self.walk(raw, here) if strict else self.template(raw, here)
def template(self, value: Any, path: str) -> Any:
"""*value* with every placeholder this context can resolve replaced,
and every one it cannot yet (``unknown_namespace``,
``missing_value``) kept as written: a template for a later resolve
with a context that has the rest. Every string a resolved value
brings is written so that resolve reads it back exactly
(:func:`_written`). A SQL path
is kept as written (a SQL literal cannot be escaped); a verbatim path
too. A failing provider raises: it is the service's fault, not a
value the later context may have.
Raises:
PlaceholderError: Any other error (``syntax``, ``argument``, the
secret errors, ``cycle``, …): resolving again would not fix it.
"""
if path in self.ctx._verbatim or path in self.ctx._sql:
return as_written(value)
if isinstance(value, str):
return self.template_string(value, path)
if isinstance(value, Mapping):
out: dict[Any, Any] = {}
for key, item in value.items():
child = pointer(path, key)
out[check_key(key, child)] = self.template(item, child)
return out
if isinstance(value, list):
return [self.template(item, pointer(path, i)) for i, item in enumerate(value)]
return value
def template_string(self, text: str, path: str) -> Any:
segments = parse_at(text, path)
whole = len(segments) == 1 and isinstance(segments[0], Placeholder)
parts: list[str] = []
for segment in segments:
if isinstance(segment, Text):
parts.append(segment.value) # never holds @{: it would be a placeholder
continue
try:
if _nests_secret(segment.expr):
# Written in place, each secret as @{secret, '…'}, the rest
# left to the later resolve: it then records every secret,
# not only the text this call would make of them.
parts.append(write(self._rewritten(segment.expr, segment, path)))
continue
reads = self.ctx._secret_reads
value = self.placeholder(segment, path)
if self.ctx._secret_reads != reads and isinstance(segment.expr, Call) and segment.expr.name not in _SECRET_CALLS:
# A secret reached through a reference: written in place too.
parts.append(write(self._rewritten(segment.expr, segment, path)))
continue
except PlaceholderError as err:
if err.code not in _NOT_YET or err.message.startswith("provider failed"):
raise # a later resolve would not fix it; a failing provider is the service's
parts.append(segment.raw) # resolved later
continue
if whole:
return _written_value(value, self.ctx._secrets)
try:
parts.append(_written(_locate(as_text, value, path, segment.raw), self.ctx._secrets))
except PlaceholderError as err:
_attribute(err, segment.expr)
_scope(err, _read(segment.expr, err))
raise
return "".join(parts)
def _rewritten(self, expr: Expr, segment: Placeholder, path: str) -> Expr:
"""*expr* with each ``get_secret`` call read here and replaced by
``secret`` of its value; nothing else is resolved."""
if isinstance(expr, Reference):
reads = self.ctx._secret_reads
try:
value = self.expression(expr, segment.raw, path)
except PlaceholderError as err:
if err.code in _NOT_YET and not err.message.startswith("provider failed"):
return expr # not here yet: the later resolve reads it
raise
if self.ctx._secret_reads != reads and isinstance(value, str):
return Call("secret", (Literal(value),)) # it holds a secret
return expr
if not isinstance(expr, Call):
return expr
if expr.name == "get_secret":
return Call("secret", (Literal(self.expression(expr, segment.raw, path)),))
return Call(expr.name, tuple(self._rewritten(arg, segment, path) for arg in expr.args))
def raw_at(self, keys: tuple[str, ...]) -> Any:
"""The value at *keys* as the context holds it, not resolved.
Raises:
PlaceholderError: ``unknown_namespace`` or ``missing_value``.
"""
ns, path = keys[0], keys[1:]
here = context_pointer(ns, path)
reference = reference_text(Reference(ns, path))
provider = self.ctx.providers.get(ns)
if provider is None:
raise PlaceholderError(
ErrorCode.UNKNOWN_NAMESPACE, f"namespace {ns!r} is not available here", path=here, reference=reference
)
try:
return _provider_value(provider, path)
except MissingValue:
raise PlaceholderError(
ErrorCode.MISSING_VALUE, _Absent.message, path=here, reference=reference, namespaces=frozenset({ns})
) from None
def walk(self, value: Any, path: str) -> Any:
if path in self.ctx._verbatim:
return as_written(value) # not parsed
if path in self.ctx._sql:
return self.sql(value, path)
if isinstance(value, str):
return self.string(value, path)
if isinstance(value, Mapping):
out: dict[Any, Any] = {}
for key, item in value.items():
child = pointer(path, key)
out[check_key(key, child)] = self.walk(item, child)
return out
if isinstance(value, list):
return [self.walk(item, pointer(path, i)) for i, item in enumerate(value)]
return value
def sql(self, value: Any, path: str) -> str:
"""The SQL text at *path*, each placeholder a SQL literal.
Raises:
PlaceholderError: ``type`` if the value is not a string, and the
SQL errors (``sql_position``, ``sql_secret``).
"""
from .sql import _resolve_sql # noqa: PLC0415
if not isinstance(value, str):
raise PlaceholderError(ErrorCode.TYPE, f"SQL must be a string, not {_with_article(_type_name(value))}", path=path)
return _resolve_sql(value, self, path)
def string(self, text: str, path: str) -> Any:
segments = parse_at(text, path)
if len(segments) == 1 and isinstance(segments[0], Placeholder):
return self.placeholder(segments[0], path)
parts: list[str] = []
for segment in segments:
if isinstance(segment, Text):
parts.append(segment.value)
else:
value = self.placeholder(segment, path)
try:
parts.append(_locate(as_text, value, path, segment.raw))
except PlaceholderError as err:
_attribute(err, segment.expr)
_scope(err, _read(segment.expr, err))
raise
return "".join(parts)
def placeholder(self, placeholder: Placeholder, path: str) -> Any:
"""Resolve one placeholder to a present JSON value."""
return self.expression(placeholder.expr, placeholder.raw, path)
def expression(self, expr: Expr, raw: str, path: str) -> Any:
"""Resolve *expr*, written as *raw* at *path*, to a present JSON
value. A missing value becomes ``missing_value`` here."""
try:
try:
if isinstance(expr, Literal):
if is_missing(expr.value):
raise _Blank
return expr.value
return self.value(expr)
except MissingValue as exc:
raise _missing(exc) from None
except PlaceholderError as err:
if err.placeholder is None:
err.placeholder = raw
if not err.path:
err.path = path
_scope(err, _read(expr, err))
raise
def value(self, node: Reference | Call, *, json_only: bool = True) -> Any:
"""The value of a reference or a call, nested or not. Raises
``MissingValue`` (an ``_Absent``) when there is none, so ``coalesce``
can skip it; every other failure is a ``PlaceholderError``. A
failure of a reference names it (``reference``)."""
if isinstance(node, Call):
return self.call(node)
try:
value = self.present(node, json_only=json_only and node.format != "json")
if node.format == "str":
return as_text(value)
if node.format == "json":
return json_text(value)
if node.format in TYPES:
return self.typed(value, node.format)
return value
except _Absent as exc:
if node.default is not None:
return self.default(node)
if exc.reference is None:
exc.reference = reference_text(node)
if exc.namespaces is None:
exc.namespaces = frozenset({node.namespace})
raise
except MissingValue:
if node.default is not None:
return self.default(node)
raise _Absent(reference=reference_text(node), namespaces=frozenset({node.namespace})) from None
except PlaceholderError as err:
_attribute(err, node)
_scope(err, _read(node, err))
raise
def typed(self, value: Any, fmt: str) -> Any:
"""*value* as the type *fmt* names (``int``, ``float``, ``bool``).
Raises:
PlaceholderError: ``type`` if it is a secret (a number or boolean
is not masked or refused as text is), or not that type.
"""
if isinstance(value, str) and _holds_secret(value, self.ctx._secrets):
raise PlaceholderError(ErrorCode.TYPE, f"a secret cannot be read as {fmt}")
try:
return to_type(value, fmt)
except ValueError as exc:
raise PlaceholderError(ErrorCode.TYPE, f"{exc}: it holds {_with_article(_type_name(value))}") from None
def default(self, node: Reference) -> Any:
"""*node*'s default: its text, or that text as the format's type."""
if node.format not in TYPES:
return node.default
try:
return to_type(node.default, node.format)
except ValueError:
raise PlaceholderError(ErrorCode.ARGUMENT, f"lookup's default {node.default!r} is not a valid {node.format}") from None
def present(self, ref: Reference, *, json_only: bool = True) -> Any:
"""The value at *ref*. Raises ``MissingValue`` only when there is no
value (no such path, ``null``, blank); every other failure is a
``PlaceholderError``, so ``coalesce`` never skips it. Without
*json_only*, a value that is not JSON (a DataFrame) is returned too."""
ns = ref.namespace
provider = self.ctx.providers.get(ns)
if provider is None:
raise PlaceholderError(ErrorCode.UNKNOWN_NAMESPACE, f"namespace {ns!r} is not available here")
value = self.read(provider, ns, ref.path, json_only=json_only)
if is_missing(value):
raise _Blank
if json_only:
_check_json(value)
return value
def read(self, provider: Any, ns: str, path: tuple[str, ...], *, json_only: bool) -> Any:
"""The value at *path* in namespace *ns*, its placeholders resolved.
Raises:
MissingValue: There is no value at *path*.
PlaceholderError: ``cycle`` when the value is read again while it
is being resolved, or values are read inside one another more
than ``READ_DEPTH_MAX`` deep.
"""
with self.reading_value(ns, path):
try:
value = _provider_value(provider, path)
except MissingValue:
return self.through_placeholder(provider, ns, path)
return self.held(value, ns, path, json_only=json_only)
@contextmanager
def reading_value(self, ns: str, path: tuple[str, ...]) -> Iterator[None]:
"""Mark the value at *path* in *ns* as being read while the block runs.
Raises:
PlaceholderError: ``cycle`` if it is already being read, or
values are read inside one another ``READ_DEPTH_MAX`` deep.
"""
key = (ns, path)
if key in self.reading:
raise PlaceholderError(
ErrorCode.CYCLE, "the value refers back to itself", reference=reference_text(Reference(ns, path))
)
if len(self.reading) >= READ_DEPTH_MAX:
raise PlaceholderError(
ErrorCode.CYCLE,
f"values refer to one another more than {READ_DEPTH_MAX} deep",
reference=reference_text(Reference(ns, path)),
)
self.reading.append(key)
try:
yield
finally:
self.reading.pop()
def held(self, value: Any, ns: str, path: tuple[str, ...], *, json_only: bool) -> Any:
"""*value*, as the context holds it at *path* in *ns*, with its
placeholders resolved; as written if it is verbatim. A string that is
one placeholder is that placeholder's value, so ``coalesce`` skips it
when it has none; an error inside the value is reported where the
value is in the context (``/<namespace>/<path…>``)."""
at = context_pointer(ns, path)
if is_verbatim(at, self.ctx._verbatim):
return value
if at in self.ctx._sql:
return self.walk(value, at)
if isinstance(value, str):
segments = parse_at(value, at)
if len(segments) == 1 and isinstance(segments[0], Placeholder):
expr = segments[0].expr
try:
if isinstance(expr, Literal):
if is_missing(expr.value):
raise _Blank
return expr.value
return self.value(expr, json_only=json_only)
except PlaceholderError as err:
if err.placeholder is None:
err.placeholder = segments[0].raw
if not err.path:
err.path = at
raise
if isinstance(value, str | Mapping | list):
return self.walk(value, at)
return value
def through_placeholder(self, provider: Any, ns: str, path: tuple[str, ...]) -> Any:
"""The value at *path* when the provider has none there because a
value on the way is a placeholder (``cfg.x`` with ``cfg`` holding
``@{lookup, owner.settings}``): resolve that value, then follow the
rest of *path* into it.
Raises:
MissingValue: No value on the way is a placeholder, or the
resolved one has nothing at the rest of *path*.
"""
for i in range(len(path) - 1, -1, -1): # down to the namespace itself
head = path[:i]
try:
held = _provider_value(provider, head)
except MissingValue:
continue
if not isinstance(held, str) or is_verbatim(context_pointer(ns, head), self.ctx._verbatim):
break # the deepest value on the way is there and is not a placeholder
with self.reading_value(ns, head): # already read: not asked again
value = self.held(held, ns, head, json_only=False)
for segment in path[i:]:
value = _step(value, segment)
return value
raise MissingValue
def call(self, call: Call) -> Any:
"""A call's present value. Its arguments are read first, a nested
placeholder's value as it is (never scanned again), so a value
holding ``,`` ``}`` or ``@{`` is still one argument. A failure is
scoped to this call (``namespaces``) unless a part inside it failed.
Raises:
_Absent: An argument has no value (``coalesce`` skips it), or
the function returned none (``_Blank``).
"""
try:
return self.invoke(call)
except _Absent as exc:
if exc.namespaces is None:
exc.namespaces = namespaces(call)
raise
except PlaceholderError as err:
_scope(err, _read(call, err))
raise
def invoke(self, call: Call) -> Any:
spec = self.ctx._functions.get(call.name)
if spec is None:
raise PlaceholderError(ErrorCode.UNKNOWN_FUNCTION, f"unknown function {call.name!r}")
check_arity(call, spec)
if spec.raw:
return self.raw_call(spec, call)
if spec.lazy:
check_lazy_literals(call)
try:
return spec.call(self.ctx, [self.thunk(arg) for arg in call.args])
except MissingValue:
raise _Blank("every argument is missing") from None
args: list[Any] = []
for arg in call.args:
try:
value = arg.value if isinstance(arg, Literal) else self.value(arg)
except _Blank as exc:
# Not this call's result: its argument is missing.
raise _Absent(exc.message, reference=exc.reference, namespaces=exc.namespaces) from None
try:
if spec.variadic:
value = as_text(value)
elif not isinstance(value, str):
raise PlaceholderError(ErrorCode.ARGUMENT, "argument must be a string")
except PlaceholderError as err:
_attribute(err, arg)
_scope(err, _read(arg, err))
raise
args.append(value)
if not spec.variadic:
check_params(call, spec, args)
args.extend(p.default for p in spec.params[len(args) :])
result = spec.call(self.ctx, args)
if is_missing(result):
raise _Blank("function returned no value")
return result
def raw_call(self, spec: FunctionSpec, call: Call) -> Any:
"""A ``raw`` function: each argument's value as it is (``None`` for
``null`` or blank, literal or not, or for a nested call whose own
result is none), and the result as plain JSON. Any failure is a
``PlaceholderError`` naming only its type: the function sees values a
JSON check never looked at."""
reads = self.ctx._secret_reads
args: list[Any] = []
for arg in call.args:
if isinstance(arg, Literal):
args.append(None if is_missing(arg.value) else arg.value)
continue
try:
args.append(self.value(arg, json_only=False))
except _Blank:
args.append(None)
from_secret = self.ctx._secret_reads != reads
try:
result = json_value(spec.call(self.ctx, args))
except (PlaceholderError, _Absent):
raise
except MissingValue:
raise _Blank("function returned no value") from None
except Exception as exc:
raise PlaceholderError(ErrorCode.ARGUMENT, f"{spec.name} failed ({type(exc).__name__})") from None
if is_missing(result):
raise _Blank("function returned no value")
_check_json(result)
if from_secret:
# A secret was read for an argument: part of it (a field of a
# JSON secret) is a secret too.
self.record_strings(result)
return result
def record_strings(self, value: Any) -> None:
"""Record each string in *value* of at least ``SECRET_PART_MIN``
characters (not blank): a shorter one, such as a host ``db``, would
mask every word containing it and fail unrelated SQL."""
if isinstance(value, str):
if len(value.strip(BLANK)) >= SECRET_PART_MIN:
self.ctx._record_secret(value)
elif isinstance(value, Mapping):
for item in value.values():
self.record_strings(item)
elif isinstance(value, list):
for item in value:
self.record_strings(item)
def thunk(self, arg: Reference | Literal | Call) -> Callable[[], Any]:
"""An argument of a lazy function: read only when called, and
``MissingValue`` when there is no value."""
if isinstance(arg, Literal):
return lambda: arg.value # never blank: check_lazy_literals
return lambda: self.value(arg)
def _provider_value(provider: Any, path: tuple[str, ...]) -> Any:
"""Ask a provider for a value. ``MissingValue`` passes through, without
the provider's text. A provider is service code (it may read a store), so
any other failure becomes ``missing_value`` naming only the exception
type, with no chain that could carry its text. Containers are copied so a
caller cannot change what the provider holds."""
try:
value = provider.get(path)
except MissingValue:
raise MissingValue from None
except PlaceholderError:
raise
except Exception as exc:
raise PlaceholderError(ErrorCode.MISSING_VALUE, f"provider failed ({type(exc).__name__})") from None
return copy.deepcopy(value) if isinstance(value, Mapping | list) else value
[docs]
def check_arity(call: Call, spec: FunctionSpec) -> None:
"""Check the argument count of a registered function.
Raises:
PlaceholderError: ``arity``.
"""
n = len(call.args)
if n < spec.min_args or (spec.max_args is not None and n > spec.max_args):
expected = f"at least {spec.min_args}" if spec.max_args is None else f"{spec.min_args} to {spec.max_args}"
raise PlaceholderError(ErrorCode.ARITY, f"{call.name} takes {expected} arguments, got {n}")
[docs]
def check_params(call: Call, spec: FunctionSpec, values: list[Any]) -> None:
"""Run each parameter's own check on its argument's value, a reference's
value too, so a failure names the reference.
Raises:
PlaceholderError: ``argument``.
"""
for arg, param, value in zip(call.args, spec.params, values, strict=False):
if param.check is None:
continue
try:
param.check(value)
except PlaceholderError as err:
if not isinstance(arg, Literal): # a literal's failure is the call's
_attribute(err, arg)
_scope(err, _read(arg, err))
raise
[docs]
def check_lazy_literals(call: Call) -> None:
"""For ``coalesce``: a literal must be last and not blank. A blank one is
never a value, and nothing after a literal is ever read.
Raises:
PlaceholderError: ``argument``.
"""
last = len(call.args) - 1
for i, arg in enumerate(call.args):
if not isinstance(arg, Literal):
continue
if is_missing(arg.value):
raise PlaceholderError(ErrorCode.ARGUMENT, "a blank literal is never a value")
if i < last:
raise PlaceholderError(ErrorCode.ARGUMENT, "only the last argument can be a literal; later ones are never read")
def _locate(fn: Any, value: Any, path: str, raw: str) -> Any:
try:
return fn(value)
except PlaceholderError as err:
err.path, err.placeholder = path, raw
raise