Source code for ds_common_placeholder_py_lib.validate

"""
**File:** ``validate.py``
**Region:** ``ds-common-placeholder-py-lib``

Description
-----------
Static checks without runtime data (contract §3, §4, §5).
"""

from __future__ import annotations

from collections.abc import Callable, Collection, Iterator, Mapping
from typing import TYPE_CHECKING, Any

from .context import mask_written_secrets
from .errors import ErrorCode, PlaceholderError
from .functions import FUNCTIONS, FunctionSpec, service_function
from .grammar import Call, Literal, Placeholder, Reference, parse
from .resolve import check_arity, check_key, check_lazy_literals, pointer, verbatim_pointers
from .sql import sql_errors

if TYPE_CHECKING:
    from .resolve import Paths

PROTECTED = frozenset({"id", "name", "type", "version"})
"""The keys :func:`validate` protects by default: read by the engine before
anything is resolved, so a placeholder there would stay as text. Only outside
a ``settings`` key: under one, whatever its value, these are ordinary keys."""


[docs] def validate( value: Any, *, verbatim: Paths = (), sql: Paths = (), protected: Collection[str] = PROTECTED, functions: Mapping[str, Callable[..., Any]] | Collection[str] = (), ) -> list[PlaceholderError]: """Check every placeholder in a JSON value: syntax, known functions, argument counts, and literal arguments (contract §3, §5). Namespaces are not checked: which ones exist depends on the context a service builds. Call it only on ``standard`` definitions: ``legacy`` ones are not valid ``standard``. Whether a definition is ``standard`` is the service's call (``settings.placeholder_dialect``, or always for pipelines). Pass the whole definition, in one call: the protected keys (by default ``id``, ``name``, ``type``, and ``version``) outside a ``settings`` key must not contain ``@{`` at all (``protected_field``), and only the whole definition shows which keys those are. Everything that depends on runtime data (missing values, secrets, SQL literal positions) is checked when it is resolved. Args: value: Any JSON value. verbatim: Paths to values taken as written, such as a script's code: not parsed, so ``@{`` there is text. Each is a dotted string written like a reference, ``tasks.0.settings.'a.b'``, or a list of keys, ``["tasks", 0, "settings", "a.b"]`` (use that for keys that come from data), from the root of *value*. A path that is not in *value* is ignored, so a wrong path means the value is parsed as usual. Protected fields are still checked inside them. sql: Paths to SQL text, as for a context's ``sql``: written like *verbatim*. The text must be a string, a placeholder in it must stand where a SQL literal can (``sql_position``), and none may call ``get_secret`` or ``secret`` (``sql_secret``). protected: The protected keys, :data:`PROTECTED` by default. Extend it (``PROTECTED | {"slug"}``) or replace it; ``()`` turns the check off, for definitions without such keys. Every validator of the same definitions must use the same keys. functions: A service's own functions, as given to its :class:`~ds_common_placeholder_py_lib.context.Context`: their argument counts are checked too. Or just their names, where the functions are not at hand: then any argument count passes. Returns: Every error found, in document order. Empty if the value is valid. Raises: TypeError: If *verbatim* is a single string or holds something that is not a path, or *protected* is not a collection of strings (``None``, a single string, or an iterator are refused). ValueError: If a *verbatim* path is not a path, *protected* includes ``settings``, or a function name is not one or is a built-in one. """ checker = _Checker( verbatim_pointers(verbatim), verbatim_pointers(sql), _protected_keys(protected), _known_functions(functions) ) checker.walk(value, "") return checker.errors
def _protected_keys(keys: Collection[str]) -> frozenset[str]: if keys is None or isinstance(keys, str | bytes | Iterator): # None is ambiguous (default, or none?), and an iterator would be # empty on the next call, silently turning the check off. raise TypeError("protected takes a collection of keys, such as a set or a list") if not all(isinstance(key, str) for key in keys): raise TypeError("protected keys are strings") if "settings" in keys: raise ValueError("settings cannot be protected: it is where placeholders go") return frozenset(keys) def _by_name(*_args: Any) -> None: """Stands in for a function known by name only.""" def _known_functions( functions: Mapping[str, Callable[..., Any]] | Collection[str], ) -> dict[str, FunctionSpec | None]: """The built-in functions and the service's: a spec where the argument counts are known, ``None`` where only the name is.""" if functions is None or isinstance(functions, str | bytes | Iterator): raise TypeError("functions takes a mapping of name to function, or a collection of names") known: dict[str, FunctionSpec | None] = dict(FUNCTIONS) if isinstance(functions, Mapping): known.update({name: service_function(name, fn) for name, fn in functions.items()}) return known for name in functions: service_function(name, _by_name) # checks the name known[name] = None return known class _Checker: def __init__( self, verbatim: frozenset[str], sql: frozenset[str], protected: frozenset[str], functions: dict[str, FunctionSpec | None], ) -> None: self.errors: list[PlaceholderError] = [] self.verbatim = verbatim self.sql = sql self.protected_keys = protected self.functions = functions def add(self, err: PlaceholderError, path: str, raw: str | None = None) -> None: err.path = path if raw is not None: err.placeholder = raw if err._placeholder is not None: # A job from resolve(strict=False) holds secrets as @{secret, '…'}, # also nested in another call: never show one. err.placeholder = mask_written_secrets(err._placeholder) self.errors.append(err) def walk(self, value: Any, path: str, in_settings: bool = False, verbatim: bool = False) -> None: # A verbatim value is not parsed, but protected fields in it are # still checked: the engine reads them as written either way. verbatim = verbatim or path in self.verbatim if path in self.sql and not verbatim: self.sql_text(value, path) elif isinstance(value, str): if not verbatim: self.string(value, path) elif isinstance(value, Mapping): for key, item in value.items(): child = pointer(path, key) if not verbatim: try: check_key(key, child) except PlaceholderError as err: self.add(err, child) if not in_settings and key in self.protected_keys: self.protected(item, child) else: self.walk(item, child, in_settings or key == "settings", verbatim) elif isinstance(value, list): for i, item in enumerate(value): self.walk(item, pointer(path, i), in_settings, verbatim) def sql_text(self, value: Any, path: str) -> None: """A SQL path: the placeholder checks of any string, then those of SQL.""" if not isinstance(value, str): self.add(PlaceholderError(ErrorCode.TYPE, "SQL must be a string"), path) return self.string(value, path) try: errors = sql_errors(value) except PlaceholderError: return # a syntax error, already reported for err in errors: self.add(err, path, err._placeholder) def protected(self, value: Any, path: str) -> None: """Not parsed: any ``@{``, even inside quotes, in a value or key is an error.""" if isinstance(value, str): if "@{" in value: message = "placeholders are not allowed here; the value is read as written" self.add(PlaceholderError(ErrorCode.PROTECTED_FIELD, message), path) elif isinstance(value, Mapping): for key, item in value.items(): child = pointer(path, key) if isinstance(key, str) and "@{" in key: self.add(PlaceholderError(ErrorCode.PROTECTED_FIELD, "placeholders are not allowed in this key"), child) self.protected(item, child) elif isinstance(value, list): for i, item in enumerate(value): self.protected(item, pointer(path, i)) def string(self, text: str, path: str) -> None: try: segments = parse(text) except PlaceholderError as err: self.add(err, path) return for segment in segments: if isinstance(segment, Placeholder): for expr_error in self.expression(segment): self.add(expr_error, path, segment.raw) def expression(self, placeholder: Placeholder) -> list[PlaceholderError]: expr = placeholder.expr if isinstance(expr, Reference | Literal): return [] return self.call(expr) def call(self, call: Call) -> list[PlaceholderError]: """The errors of *call*, then of each call nested in it: a nested placeholder is checked whatever is wrong with, or unknown about, the call around it.""" errors = self.own(call) for arg in call.args: if isinstance(arg, Call): errors.extend(self.call(arg)) return errors def own(self, call: Call) -> list[PlaceholderError]: if call.name not in self.functions: return [PlaceholderError(ErrorCode.UNKNOWN_FUNCTION, f"unknown function {call.name!r}")] spec = self.functions[call.name] if spec is None: return [] # known by name only try: check_arity(call, spec) except PlaceholderError as err: return [err] errors: list[PlaceholderError] = [] if spec.lazy: try: check_lazy_literals(call) except PlaceholderError as err: errors.append(err) for i, arg in enumerate(call.args): check = None if spec.variadic else spec.params[i].check if check is not None and isinstance(arg, Literal): try: check(arg.value) except PlaceholderError as err: errors.append(err) return errors