Source code for fleetmesh_node.compartment.every

"""EVERY: periodic work declared on a compartment."""
from __future__ import annotations

import inspect
import math
from dataclasses import dataclass, field
from typing import Any, Callable, Optional, Union

from .problem import Problem, Problems, ReferenceProblem, TypeMismatchProblem

SecondsType = Union[int, float, Callable[[Any], Union[int, float]], Any]
ReportType = Optional[Union[str, Callable[..., Any]]]


[docs]@dataclass(frozen=True) class Every: """A periodic job declared on a compartment class. Attributes: seconds: How often to run the job, in seconds. Can be an int, float, a callable receiving the compartment instance, or a Parameter. A callable that resolves to zero or less turns the job off (see `is_off`): that is how a setting like `check_every: 0` says "only on command". run: The method name on the compartment to call when due. name: A unique name for the job within the compartment (defaults to `run`). report: Optional method name or callable to convert the method's return value into a list of `[(what, ...)]` tuples for the tick log. """ seconds: SecondsType run: str name: str = '' report: ReportType = None # Whether `run` takes `now`, per class. inspect.signature ran for every # due job on every tick (audit 2026-10-15, E6); a method's arity does not # change between ticks. _takes_now: dict = field(default_factory=dict, init=False, repr=False, compare=False, hash=False) def __post_init__(self) -> None: if not self.name: object.__setattr__(self, 'name', self.run)
[docs] def get_seconds(self, instance: Any) -> float: """Resolve the interval in seconds against a compartment instance.""" sec = self.seconds if callable(sec): return float(sec(instance)) if hasattr(sec, 'value') and callable(sec.value): return float(sec.value()) if hasattr(sec, 'default'): def_val = sec.default() if callable(sec.default) else sec.default return float(def_val) return float(sec)
[docs] def is_off(self, instance: Any) -> bool: """Whether the interval says this job does not run on a schedule. Zero, a negative number, or anything not finite. Updates used to spell "off" as infinity, and `report()` died on `int(inf)` - which took the whole health report with it, every tick (audit 2026-10-15, B1). Off is now one rule, read here, and never a number anyone does arithmetic on. """ sec = self.get_seconds(instance) return not math.isfinite(sec) or sec <= 0
[docs] def due(self, instance: Any, now: int) -> bool: """True if this job has never run or if at least `seconds` have passed since last run. Never true for a job that is off, including on its first tick.""" if self.is_off(instance): return False every_last = getattr(instance, '_every_last', None) if every_last is None: return True last = every_last.get(self.name) if last is None: return True return (now - last) >= self.get_seconds(instance)
[docs] def execute(self, instance: Any, now: int) -> Any: """Call the target method on instance, passing `now` if accepted.""" method = getattr(instance, self.run, None) if method is None: raise AttributeError(f"{type(instance).__name__} has no method {self.run!r}") cls = type(instance) takes = self._takes_now.get(cls) if takes is None: takes = self._takes_now[cls] = len(inspect.signature(method).parameters) > 0 if takes: return method(now) return method()
[docs] def problems(self, cls: type[Any]) -> list[str]: """Lint this declaration against the target class.""" out = Problems() if not isinstance(self.run, str) or not self.run: out.append(TypeMismatchProblem('EVERY', 'non-empty str', type(self.run).__name__, message=f"Every job {self.name!r}: run must be a non-empty string method name")) elif not getattr(cls, 'abstract', False) and not hasattr(cls, self.run): out.append(ReferenceProblem('EVERY', f"Every job {self.name!r}", self.run, message=f"Every job {self.name!r}: method {self.run!r} does not exist on {cls.__name__}")) if isinstance(self.report, str) and not getattr(cls, 'abstract', False) and not hasattr(cls, self.report): out.append(ReferenceProblem('EVERY', f"Every job {self.name!r}", self.report, message=f"Every job {self.name!r}: report method {self.report!r} does not exist on {cls.__name__}")) if isinstance(self.seconds, (int, float)) and self.seconds <= 0: out.append(Problem(f"Every job {self.name!r}: seconds must be positive, got {self.seconds!r}", surface='EVERY', code='invalid_interval', target=self.name)) return out