Source code for fleetmesh_node.compartment.worker

"""WORKERS: background worker threads declared on a compartment."""
from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Callable, Optional, Union

from .problem import Problem, Problems, ReferenceProblem, TypeMismatchProblem

WhenType = Optional[Union[str, Callable[[Any], bool]]]


[docs]@dataclass(frozen=True) class Worker: """A background worker thread declared on a compartment class. The base Compartment starts declared workers during `start()` and signals them to stop and joins them during `stop()`. Attributes: run: The method name on the compartment to run in a thread. name: A unique name for the worker/thread (defaults to `run`). timeout: How long in seconds to wait for the thread to join on stop(). daemon: Whether the thread is a daemon thread (defaults to True). when: Optional condition to run: attribute name (checked for truthiness) or callable receiving the compartment instance. """ run: str name: str = '' timeout: float = 1.0 daemon: bool = True when: WhenType = None def __post_init__(self) -> None: if not self.name: object.__setattr__(self, 'name', self.run)
[docs] def should_run(self, instance: Any) -> bool: """True if any `when` condition holds.""" if self.when is None: return True if callable(self.when): return bool(self.when(instance)) val = getattr(instance, self.when, None) if callable(val): return bool(val()) return bool(val)
[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('WORKERS', 'non-empty str', type(self.run).__name__, message=f"Worker {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('WORKERS', f"Worker {self.name!r}", self.run, message=f"Worker {self.name!r}: method {self.run!r} does not exist on {cls.__name__}")) if self.timeout < 0: out.append(Problem(f"Worker {self.name!r}: timeout must be non-negative, got {self.timeout!r}", surface='WORKERS', code='negative_timeout', target=self.name)) return out