Source code for passengersim.config.callbacks

"""Serializable declarations for callbacks selected by configuration."""

from __future__ import annotations

import json
import warnings
from typing import Any

from pydantic import BaseModel, Field, JsonValue, field_validator, model_serializer, model_validator


[docs] class CallbackConfig(BaseModel, extra="forbid", validate_assignment=True): """Select a registered callback and its explicit options. Parameters ---------- type : str or None, optional Registered callback or tracer to use. Defaults to the declaration's mapping key. parameters : dict, optional JSON-compatible factory options. Runtime defaults are not stored here. enabled : bool, optional Whether to attach this declaration. Defaults to True. version : str or None, optional Required registered implementation version, if specified. """ type: str | None = None """Registry name, or the declaration key when omitted.""" parameters: dict[str, JsonValue] = Field(default_factory=dict) """Explicit factory options, without resolved defaults.""" enabled: bool = True """Whether this declaration participates in execution.""" version: str | None = None """Optional required implementation version.""" @model_validator(mode="before") @classmethod def _legacy_name_key(cls, data: Any) -> Any: # Earlier releases spelled the selector ``name``. Accept that spelling, # with a warning, so existing YAML files and saved configs still load. if isinstance(data, dict) and "name" in data: if "type" in data: raise ValueError("a callback declaration cannot give both 'type' and its old spelling 'name'") warnings.warn( "the 'name' key of a callback declaration is deprecated; use 'type' instead", DeprecationWarning, stacklevel=2, ) data = {("type" if key == "name" else key): value for key, value in data.items()} return data @field_validator("parameters") @classmethod def _finite_json(cls, value: dict[str, JsonValue]) -> dict[str, JsonValue]: json.dumps(value, allow_nan=False) return value @model_serializer(mode="wrap") def _explicit_options(self, handler: Any) -> dict[str, Any]: # Preserve omission through worker and saved-config round trips. Defaults # belong to execution, never the explicit configuration's cache identity. # A caller can insert a plain dictionary into Config.callbacks after # construction. Normalize it locally without mutating the live mapping. model = CallbackConfig.model_validate(self) if isinstance(self, dict) else self return { key: value for key, value in handler(model).items() if key in model.model_fields_set or (key == "parameters" and model.parameters) }