"""Named factories for config-selected callbacks, separate from global attachment."""
from __future__ import annotations
import copy
import inspect
import json
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Literal
from pydantic import BaseModel
from passengersim.tracers.generic import GenericTracer
Hook = Literal["initialize_sample", "begin_sample", "daily", "end_sample", "finalize_sample"]
_HOOKS = {"initialize_sample", "begin_sample", "daily", "end_sample", "finalize_sample"}
[docs]
@dataclass(frozen=True)
class CallbackDefinition:
"""Factory metadata used to validate and construct one callback per simulation."""
factory: Callable[[BaseModel], Any]
"""Construct a fresh callable from one validated options model."""
when: Hook
"""Lifecycle hook for the constructed callback."""
parameters_model: type[BaseModel]
"""Schema used for runtime validation without changing explicit config."""
version: str
"""Implementation version checked against an explicit config requirement."""
output_name: str | None = None
"""Canonical tracer result key, or None for an ordinary callback."""
_DEFINITIONS: dict[str, CallbackDefinition] = {}
[docs]
def register_callback_factory(
name: str,
*,
factory: Callable[[BaseModel], Any],
when: Hook,
parameters_model: type[BaseModel],
version: str,
output_name: str | None = None,
) -> None:
"""Make a factory available to YAML declarations without attaching it.
Parameters
----------
name : str
Unique registry name. Duplicate registration is always an error.
factory : callable
Receives one validated parameter-model instance and returns a fresh
callback. Sample hooks receive a simulation; daily hooks also receive
days prior to departure.
when : {"initialize_sample", "begin_sample", "daily", "end_sample", "finalize_sample"}
Lifecycle hook at which the returned callback runs.
parameters_model : type[pydantic.BaseModel]
Schema for factory options; preferably configured with extra="forbid".
version : str
Implementation version checked only when explicitly required in YAML.
output_name : str or None, optional
Required canonical result name for a factory returning a GenericTracer.
Raises
------
ValueError
If the name is duplicated, the hook is invalid, or the output is reserved.
TypeError
If the factory or parameter model is invalid.
"""
if not isinstance(name, str) or not name or name in _DEFINITIONS:
raise ValueError(f"Callback registry name {name!r} is empty or already registered")
if when not in _HOOKS:
raise ValueError(f"Invalid callback hook: {when!r}")
if output_name is not None and (not isinstance(output_name, str) or not output_name or output_name in _HOOKS):
raise ValueError(f"Reserved or empty callback output name: {output_name!r}")
if not callable(factory) or not isinstance(parameters_model, type) or not issubclass(parameters_model, BaseModel):
raise TypeError("A callable factory and BaseModel parameter class are required")
if not isinstance(version, str) or not version:
raise ValueError("Callback version must be a nonempty string")
_DEFINITIONS[name] = CallbackDefinition(factory, when, parameters_model, version, output_name)
@dataclass(frozen=True)
class _TracerFactory:
cls: type[GenericTracer]
def __call__(self, options: BaseModel) -> GenericTracer:
return self.cls(**options.model_dump())
[docs]
def register_tracer_factory(
cls: type[GenericTracer],
*,
parameters_model: type[BaseModel] | None = None,
version: str | None = None,
name: str | None = None,
) -> None:
"""Register a tracer using the configuration it declares on its class.
The hook, output name, options model, and version are read from the class
attributes ``hook``, ``name``, ``options_model``, and ``options_version``
(see :class:`~passengersim.tracers.generic.GenericTracer`), so they are
defined once, beside the tracer's constructor.
Parameters
----------
cls : type[GenericTracer]
Tracer class declaring a ``hook`` and a canonical ``name``.
parameters_model : type[pydantic.BaseModel] or None, optional
Overrides ``cls.options_model``. Fields map to constructor keyword
arguments. Required if the class declares no options model.
version : str or None, optional
Overrides ``cls.options_version``, the implementation version checked
against explicit YAML requirements.
name : str or None, optional
Registry name or alias; defaults to ``cls.name``. Does not rename the
tracer's output.
Raises
------
TypeError
If cls is not a GenericTracer subclass, or no options model is
declared or given.
ValueError
If registration duplicates a name or declares an invalid hook/output.
"""
if not isinstance(cls, type) or not issubclass(cls, GenericTracer):
raise TypeError("Expected a GenericTracer subclass")
parameters_model = parameters_model or getattr(cls, "options_model", None)
if parameters_model is None:
raise TypeError(f"{cls.__name__} declares no options_model; set it on the class or pass parameters_model")
hook = getattr(cls, "hook", None)
if hook is None:
raise ValueError(f"{cls.__name__} declares no hook; set the class attribute 'hook'")
register_callback_factory(
name or cls.name,
factory=_TracerFactory(cls),
when=hook,
parameters_model=parameters_model,
version=version or getattr(cls, "options_version", "1"),
output_name=cls.name,
)
def _resolve(owner: Any) -> list[tuple[str, CallbackDefinition, BaseModel]]:
"""Validate changed explicit declarations without injecting runtime defaults."""
from passengersim.config.callbacks import CallbackConfig
raw = {}
for key, value in owner.config.callbacks.items():
raw[key] = value.model_dump() if isinstance(value, CallbackConfig) else value
try:
signature = json.dumps(list(raw.items()), sort_keys=True, allow_nan=False)
except (TypeError, ValueError) as error:
raise ValueError(f"callbacks: parameters must be finite JSON values: {error}") from error
definitions = getattr(owner, "_configured_definitions", _DEFINITIONS)
cached = getattr(owner, "_configured_validation", None)
if cached is not None and cached[0] == signature and cached[1] is definitions:
return cached[2]
resolved = []
for key, value in raw.items():
name = key
try:
declaration = CallbackConfig.model_validate(value)
if not declaration.enabled:
continue
name = declaration.name or key
if name not in definitions:
raise ValueError(f"unknown callback registry name {name!r}")
definition = definitions[name]
if declaration.version is not None and declaration.version != definition.version:
raise ValueError(f"version {declaration.version!r} does not match registered {definition.version!r}")
options = definition.parameters_model.model_validate(copy.deepcopy(declaration.parameters))
except (ValueError, TypeError) as error:
raise ValueError(f"callbacks.{key} ({name}): parameters or declaration invalid: {error}") from error
resolved.append((key, definition, options))
owner._configured_validation = signature, definitions, resolved
return resolved
[docs]
def preflight(owner: Any) -> dict[str, CallbackDefinition]:
"""Check current declarations and manual tracer collisions without factories."""
resolved = _resolve(owner)
outputs = {}
for key, definition, _options in resolved:
output = definition.output_name
if output is not None:
if output in outputs:
raise ValueError(f"callbacks.{key}: duplicate tracer output {output!r} (also {outputs[output]})")
outputs[output] = key
# callback_functions() already excludes callbacks built by a prior prepare().
for callbacks in owner.callback_functions().values():
for callback in callbacks:
if isinstance(callback, GenericTracer) and callback.name in outputs:
raise ValueError(
f"callbacks.{outputs[callback.name]}: tracer output {callback.name!r} conflicts with manual tracer"
)
# Copy only definitions referenced by this run, never the global registry.
declarations = owner.config.callbacks
return {
(
getattr(declarations[key], "name", None)
or (declarations[key].get("name") if isinstance(declarations[key], dict) else None)
or key
): definition
for key, definition, _ in resolved
}
[docs]
def prepare(owner: Any) -> None:
"""Build fresh callbacks and replace only prior configured attachments."""
from .base import CallbackMixin
preflight(owner)
attached = []
temporary = CallbackMixin()
for key, definition, options in _resolve(owner):
try:
callback = definition.factory(options.model_copy(deep=True))
if not callable(callback):
raise TypeError("factory must return a callable")
if isinstance(callback, GenericTracer):
if definition.output_name != callback.name:
raise ValueError("declared output_name must match the tracer's canonical name")
elif definition.output_name is not None:
raise TypeError("output_name requires a GenericTracer result")
callback = getattr(temporary, f"{definition.when}_callback")(callback)
if not callable(callback):
raise TypeError("fresh() must return a callable tracer")
if definition.output_name is not None and (
not isinstance(callback, GenericTracer) or callback.name != definition.output_name
):
raise ValueError("fresh() changed the tracer's canonical output name")
# Diagnose incompatible hook signatures before any simulation events.
try:
signature = inspect.signature(callback)
except (TypeError, ValueError):
signature = None # Some extension callables expose no signature.
if signature is not None:
signature.bind(owner, *([0] if definition.when == "daily" else []))
except Exception as error:
raise ValueError(f"callbacks.{key}: could not construct callback: {error}") from error
attached.append((definition.when, callback))
# Publish only after all factories succeed. Manual callbacks and RM callbacks
# retain their identities and ordering; no stale configured state is reused.
manual = owner.callback_functions()
for hook in ("initialize_sample", "begin_sample", "daily", "end_sample", "finalize_sample"):
configured = [cb for when, cb in attached if when == hook]
setattr(owner, f"{hook}_callbacks", configured + manual.get(f"{hook}_callbacks", []))
owner._configured_attached = attached