跳转至

运行时(Master)

生命周期入口:加载配置、注册 Worker、启动调度、优雅停机。

from zoo_framework.core import Master

Master

zoo_framework.core.master.Master

Master - the zoo keeper (lifecycle manager).

P2 optimized version: - removed the redundant loop_interval parameter - manages Workers with WorkerRegistry - simplified config - integrated SVM monitoring

属性:

名称 类型 描述
config

the Master configuration

worker_registry

the Worker registry

svm_worker

the SVM monitoring Worker

waiter

the Waiter scheduler

源代码位于: zoo_framework/core/master.py
class Master:
    """Master - the zoo keeper (lifecycle manager).

    P2 optimized version:
    - removed the redundant ``loop_interval`` parameter
    - manages Workers with WorkerRegistry
    - simplified config
    - integrated SVM monitoring

    Attributes:
        config: the Master configuration
        worker_registry: the Worker registry
        svm_worker: the SVM monitoring Worker
        waiter: the Waiter scheduler
    """

    def __init__(self, config: MasterConfig | None = None):
        """Initialize the Master.

        P2 optimization: simplified parameters via a config object.

        Args:
            config: the Master configuration; defaults when None
        """
        # P2 optimization: use a config object
        self.config = config or MasterConfig()

        # P2 optimization: use the new WorkerRegistry
        self.worker_registry = get_worker_registry()

        # Runtime handles of the scheduling main loop
        self._loop: asyncio.AbstractEventLoop | None = None
        self._task: asyncio.Task | None = None
        self._shutdown_done = False

        # Load config
        ParamsFactory(self.config.config_path)

        # Sequential check (change aop-determinism / #51): the config has just
        # been read, but if any params class was first imported and resolved in
        # a generation that "never saw the config", its values are frozen at the
        # defaults - fail loudly and name them, rather than let the runtime run
        # with a config that looks normal but is all defaults.
        if ParamsFactory.generation() > 0:
            from .aop.params import stale_param_classes

            stale = stale_param_classes()
            if stale:
                raise RuntimeError(
                    f"these params classes were imported and resolved before the config was loaded; their values are frozen at the defaults:"
                    f"{stale}. Move the params modules' first import to where the config file is visible"
                    f"(the same working directory as Master), or load the config before resolving; note that"
                    f"the package root imports the built-in params modules immediately, so starting from a different directory is the likeliest way to hit this check."
                )

        self._load_config()

        # P2 优化:简化 Worker 注册
        self._register_default_workers()

        # SVM Worker 集成
        # svm_check_interval 此前是声明了但从未被读取的配置项,此处真正生效
        self.svm_worker = (
            SVMWorker(self.config.svm_check_interval) if self.config.enable_svm else None
        )
        if self.svm_worker:
            self._setup_svm()

        # 创建 Waiter
        self._create_waiter()

    def _load_config(self) -> None:
        """Load config: iterate and call the import-time @configure functions **without arguments**.

        Sealed once consumed (change aop-determinism / #51): after sealing, an
        ``@configure`` registration fails loudly because that registration
        would never be consumed here again - turning the historical silent
        no-op into an error.
        """
        from .aop.configure import seal_config_funcs

        for value in config_funcs.values():
            value()
        seal_config_funcs()

    def _register_default_workers(self) -> None:
        """Register the default Workers.

        P2 optimization: registered via WorkerRegistry.
        """
        # Lazily instantiate
        self.worker_registry.register_class(
            "StateMachineWorker",
            StateMachineWorker,
            metadata={"priority": 100, "tags": ["system", "persistence"]},
        )
        self.worker_registry.register_class(
            "EventWorker", EventWorker, metadata={"priority": 50, "tags": ["system", "event"]}
        )

    def _setup_svm(self) -> None:
        """Set up SVM monitoring."""
        # Null-check first - the other four uses of svm_worker in this file all
        # guard (226/306/381/399); only this one missed; with SVM disabled
        # svm_worker is None and this used to raise AttributeError directly.
        if not self.svm_worker:
            return

        # Register all Workers to SVM
        for name, worker in self.worker_registry.get_all_workers().items():
            self.svm_worker.register_worker(name, worker)

        # Start monitoring
        self.svm_worker.start_monitoring()
        LogUtils.debug(
            "SVM worker setup done (metrics input not wired; get_health_report() returns zeros)"
        )

    def _create_waiter(self) -> None:
        """Create the Waiter.

        The scheduler is assembled by the **scheduling model name** (the name
        comes from ``worker:mode``, derived from ``worker:pool:enable`` when
        unset); an unrecognized model name is rejected explicitly.
        """
        from zoo_framework.core.waiter import WaiterFactory

        self.waiter = WaiterFactory.get_waiter()

        # Hand the Workers to the Waiter
        self.waiter.call_workers(list(self.worker_registry.get_all_workers().values()))

    def change_waiter(self, waiter) -> None:
        """Change the Waiter.

        Args:
            waiter: the new Waiter instance
        """
        if self.waiter is not None:
            raise Exception("Waiter already exists, cannot change")
        # [Known defect] The next line is **unreachable**: __init__ always sets
        # self.waiter, so the guard above is always true and the assignment
        # never executes - change_waiter can never fulfill its job (and it has
        # zero call sites repo-wide, no documented promise). Whether to allow
        # replacement or keep the guard is an unresolved semantics question,
        # so we deliberately do not guess a fix (recorded in
        # openspec/changes/establish-type-gate/tasks.md 3.1); an anchored ignore
        # keeps the defect visible instead of silently fixing it away.
        self.waiter = waiter  # type: ignore[unreachable]

    def register_worker(self, name: str, worker_class: type, metadata: dict | None = None) -> None:
        """Register a Worker.

        P2 optimization: a concise registration interface.

        Args:
            name: the Worker name
            worker_class: the Worker class
            metadata: metadata
        """
        self.worker_registry.register_class(name, worker_class, metadata)

        # The scheduling list is held by the Waiter: registering in the registry
        # alone does not get the Worker dispatched - it must be added to
        # scheduling too, or a runtime-registered Worker would never execute.
        worker = self.worker_registry.get_worker(name)
        if worker is None:
            return

        self.waiter.add_worker(worker)

        # Register to SVM when SVM is enabled
        if self.svm_worker:
            self.svm_worker.register_worker(name, worker)

    async def perform(self) -> None:
        """The task main loop."""
        while True:
            self.waiter.execute_service()
            # P2 optimization: use the configured interval
            await asyncio.sleep(1)

    def run(self) -> None:
        """Run the Master."""
        try:
            LogUtils.info("🎪 Master started, zoo is open!")
            # Create the event loop explicitly: asyncio.get_event_loop() is
            # deprecated when no loop is running, and it would reuse the last
            # loop, making repeated Master starts interfere with each other.
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            self._loop = loop

            self._task = loop.create_task(self.perform())
            # An exception out of the scheduling task must be visible and stop
            # the main loop; otherwise run_forever() would keep spinning while
            # scheduling has long stopped - the process is alive but does
            # nothing.
            self._task.add_done_callback(self._on_schedule_task_done)

            loop.run_forever()
        except KeyboardInterrupt:
            LogUtils.info("🛑 Master stopping...")
        finally:
            self.shutdown()

    def _on_schedule_task_done(self, task: asyncio.Task) -> None:
        """The close-out when the scheduling main loop ends: exceptions visible, event loop stopped.

        Args:
            task: the scheduling task
        """
        if task.cancelled():
            return

        error = task.exception()
        if error is not None:
            LogUtils.error(f"scheduling main loop terminated with an exception: {error!r}")

        # call_soon_threadsafe so this callback can stop the loop safely no
        # matter which thread triggers it
        loop = self._loop
        if loop is not None and loop.is_running():
            loop.call_soon_threadsafe(loop.stop)

    def shutdown(self) -> None:
        """Shut the Master down gracefully.

        Order: stop scheduling first (no more dispatches) -> cancel the
        scheduling task -> stop the event loop -> stop monitoring ->
        unregister Workers (firing their destroy hooks; the state machine
        persists here). MUST be repeatable.
        """
        if self._shutdown_done:
            return
        self._shutdown_done = True

        LogUtils.info("🧹 Shutting down Master...")

        # Stop the scheduler first: no new Worker MUST be dispatched during
        # shutdown
        if getattr(self, "waiter", None) is not None:
            self.waiter.shutdown()

        task = self._task
        self._task = None
        if task is not None and not task.done():
            task.cancel()

        loop = self._loop
        if loop is not None and loop.is_running():
            loop.call_soon_threadsafe(loop.stop)

        # Stop SVM monitoring
        if self.svm_worker:
            self.svm_worker.stop_monitoring()

        # Unregister the registered Workers: WorkerRegistry.unregister fires
        # their destroy hooks; the state machine Worker's last persistence
        # happens here.
        registry = getattr(self, "worker_registry", None)
        if registry is not None:
            for name in list(registry.get_all_workers().keys()):
                registry.unregister(name)

        LogUtils.info("👋 Master stopped")

    def get_health_report(self) -> dict[str, dict]:
        """Get the health report.

        Returns:
            The health status of all Workers
        """
        if self.svm_worker:
            return self.svm_worker.get_all_workers_health()
        return {}

    def get_worker_stats(self, worker_name: str) -> dict | None:
        """Get a Worker's statistics.

        Args:
            worker_name: the Worker name

        Returns:
            A statistics dict
        """
        worker = self.worker_registry.get_worker(worker_name)
        if worker is None:
            return None

        metadata = self.worker_registry.get_metadata(worker_name) or {}
        health = self.svm_worker.get_worker_health(worker_name) if self.svm_worker else {}

        return {
            "name": worker_name,
            "type": type(worker).__name__,
            "metadata": metadata,
            "health": health,
        }

__init__

__init__(config: MasterConfig | None = None)

Initialize the Master.

P2 optimization: simplified parameters via a config object.

参数:

名称 类型 描述 默认
config MasterConfig | None

the Master configuration; defaults when None

None
源代码位于: zoo_framework/core/master.py
def __init__(self, config: MasterConfig | None = None):
    """Initialize the Master.

    P2 optimization: simplified parameters via a config object.

    Args:
        config: the Master configuration; defaults when None
    """
    # P2 optimization: use a config object
    self.config = config or MasterConfig()

    # P2 optimization: use the new WorkerRegistry
    self.worker_registry = get_worker_registry()

    # Runtime handles of the scheduling main loop
    self._loop: asyncio.AbstractEventLoop | None = None
    self._task: asyncio.Task | None = None
    self._shutdown_done = False

    # Load config
    ParamsFactory(self.config.config_path)

    # Sequential check (change aop-determinism / #51): the config has just
    # been read, but if any params class was first imported and resolved in
    # a generation that "never saw the config", its values are frozen at the
    # defaults - fail loudly and name them, rather than let the runtime run
    # with a config that looks normal but is all defaults.
    if ParamsFactory.generation() > 0:
        from .aop.params import stale_param_classes

        stale = stale_param_classes()
        if stale:
            raise RuntimeError(
                f"these params classes were imported and resolved before the config was loaded; their values are frozen at the defaults:"
                f"{stale}. Move the params modules' first import to where the config file is visible"
                f"(the same working directory as Master), or load the config before resolving; note that"
                f"the package root imports the built-in params modules immediately, so starting from a different directory is the likeliest way to hit this check."
            )

    self._load_config()

    # P2 优化:简化 Worker 注册
    self._register_default_workers()

    # SVM Worker 集成
    # svm_check_interval 此前是声明了但从未被读取的配置项,此处真正生效
    self.svm_worker = (
        SVMWorker(self.config.svm_check_interval) if self.config.enable_svm else None
    )
    if self.svm_worker:
        self._setup_svm()

    # 创建 Waiter
    self._create_waiter()

register_worker

register_worker(name: str, worker_class: type, metadata: dict | None = None) -> None

Register a Worker.

P2 optimization: a concise registration interface.

参数:

名称 类型 描述 默认
name str

the Worker name

必需
worker_class type

the Worker class

必需
metadata dict | None

metadata

None
源代码位于: zoo_framework/core/master.py
def register_worker(self, name: str, worker_class: type, metadata: dict | None = None) -> None:
    """Register a Worker.

    P2 optimization: a concise registration interface.

    Args:
        name: the Worker name
        worker_class: the Worker class
        metadata: metadata
    """
    self.worker_registry.register_class(name, worker_class, metadata)

    # The scheduling list is held by the Waiter: registering in the registry
    # alone does not get the Worker dispatched - it must be added to
    # scheduling too, or a runtime-registered Worker would never execute.
    worker = self.worker_registry.get_worker(name)
    if worker is None:
        return

    self.waiter.add_worker(worker)

    # Register to SVM when SVM is enabled
    if self.svm_worker:
        self.svm_worker.register_worker(name, worker)

run

run() -> None

Run the Master.

源代码位于: zoo_framework/core/master.py
def run(self) -> None:
    """Run the Master."""
    try:
        LogUtils.info("🎪 Master started, zoo is open!")
        # Create the event loop explicitly: asyncio.get_event_loop() is
        # deprecated when no loop is running, and it would reuse the last
        # loop, making repeated Master starts interfere with each other.
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        self._loop = loop

        self._task = loop.create_task(self.perform())
        # An exception out of the scheduling task must be visible and stop
        # the main loop; otherwise run_forever() would keep spinning while
        # scheduling has long stopped - the process is alive but does
        # nothing.
        self._task.add_done_callback(self._on_schedule_task_done)

        loop.run_forever()
    except KeyboardInterrupt:
        LogUtils.info("🛑 Master stopping...")
    finally:
        self.shutdown()

shutdown

shutdown() -> None

Shut the Master down gracefully.

Order: stop scheduling first (no more dispatches) -> cancel the scheduling task -> stop the event loop -> stop monitoring -> unregister Workers (firing their destroy hooks; the state machine persists here). MUST be repeatable.

源代码位于: zoo_framework/core/master.py
def shutdown(self) -> None:
    """Shut the Master down gracefully.

    Order: stop scheduling first (no more dispatches) -> cancel the
    scheduling task -> stop the event loop -> stop monitoring ->
    unregister Workers (firing their destroy hooks; the state machine
    persists here). MUST be repeatable.
    """
    if self._shutdown_done:
        return
    self._shutdown_done = True

    LogUtils.info("🧹 Shutting down Master...")

    # Stop the scheduler first: no new Worker MUST be dispatched during
    # shutdown
    if getattr(self, "waiter", None) is not None:
        self.waiter.shutdown()

    task = self._task
    self._task = None
    if task is not None and not task.done():
        task.cancel()

    loop = self._loop
    if loop is not None and loop.is_running():
        loop.call_soon_threadsafe(loop.stop)

    # Stop SVM monitoring
    if self.svm_worker:
        self.svm_worker.stop_monitoring()

    # Unregister the registered Workers: WorkerRegistry.unregister fires
    # their destroy hooks; the state machine Worker's last persistence
    # happens here.
    registry = getattr(self, "worker_registry", None)
    if registry is not None:
        for name in list(registry.get_all_workers().keys()):
            registry.unregister(name)

    LogUtils.info("👋 Master stopped")

get_health_report

get_health_report() -> dict[str, dict]

Get the health report.

返回:

类型 描述
dict[str, dict]

The health status of all Workers

源代码位于: zoo_framework/core/master.py
def get_health_report(self) -> dict[str, dict]:
    """Get the health report.

    Returns:
        The health status of all Workers
    """
    if self.svm_worker:
        return self.svm_worker.get_all_workers_health()
    return {}

get_worker_stats

get_worker_stats(worker_name: str) -> dict | None

Get a Worker's statistics.

参数:

名称 类型 描述 默认
worker_name str

the Worker name

必需

返回:

类型 描述
dict | None

A statistics dict

源代码位于: zoo_framework/core/master.py
def get_worker_stats(self, worker_name: str) -> dict | None:
    """Get a Worker's statistics.

    Args:
        worker_name: the Worker name

    Returns:
        A statistics dict
    """
    worker = self.worker_registry.get_worker(worker_name)
    if worker is None:
        return None

    metadata = self.worker_registry.get_metadata(worker_name) or {}
    health = self.svm_worker.get_worker_health(worker_name) if self.svm_worker else {}

    return {
        "name": worker_name,
        "type": type(worker).__name__,
        "metadata": metadata,
        "health": health,
    }

MasterConfig

zoo_framework.core.master.MasterConfig

Master configuration.

P2 optimization: config centralized here.

源代码位于: zoo_framework/core/master.py
class MasterConfig:
    """Master configuration.

    P2 optimization: config centralized here.
    """

    def __init__(
        self,
        config_path: str = "./config.json",
        enable_svm: bool = True,
        svm_check_interval: int = 10,
        auto_save_interval: int = 60,
    ):
        self.config_path = config_path
        self.enable_svm = enable_svm
        self.svm_check_interval = svm_check_interval
        self.auto_save_interval = auto_save_interval

参数与路径解析

zoo_framework.core.params_factory.ParamsFactory

源代码位于: zoo_framework/core/params_factory.py
class ParamsFactory:
    # [Known debt] the class attribute is process-level shared state (the
    # config dict actually read by `get_params`), to be replaced separately
    # by tests (see the fixture in tests/test_config_resolution.py). A
    # carrier outside the container, not yet absorbed; rationale and
    # criteria in specs/scoped-container's "process-level sharing created by
    # the framework itself MUST be explicitly classified".
    config_params: dict = {}

    # The config-loading generation (aop-determinism / issue #51): +1 per
    # successful config load.
    # @params resolution happens at import time (the package root's
    # `from . import params` prevents it from being later than any explicit
    # load), so "the config had not been read at resolution time" cannot be
    # caught on the spot - the check happens at Master construction instead:
    # resolved in an older generation while this Master just read a non-empty
    # config => those classes were frozen at defaults, fail loudly. Without a
    # config file the generation stays 0 forever and the check never fires -
    # "all defaults" is a legitimate run shape.
    _generation = 0

    def __init__(self, config_path="./config.json"):
        if not os.path.exists(config_path):
            return

        # Reads and writes of the config MUST use an explicit encoding: the
        # default varies by platform (GBK on Windows in a Chinese locale),
        # which would parse the same config differently per platform, with
        # no exception raised.
        ParamsFactory.config_params = json.loads(FileUtils.read_text(config_path))
        ParamsFactory._generation += 1

        # Process the _exports
        self.load_exports()

    def load_exports(self):
        export_files = self.config_params.get("_exports")
        # Use `isinstance` rather than `type(x) != type([])`: the latter is
        # not a type narrowing the checker recognizes (so the baseline kept
        # reporting union-attr here) and would additionally **reject list
        # subclasses**. Config comes from JSON, producing an exact list;
        # both forms are equivalent in this scenario.
        if not isinstance(export_files, list):
            return

        for export_file in export_files:
            self.load_export_file(export_file)

    def load_export_file(self, export_name):
        file_name = "./" + export_name + ".json"

        if not FileUtils.file_exists(file_name):
            return
        content = self.get_export_file(file_name)
        ParamsFactory.config_params[export_name] = content

    def get_export_file(self, file_name):
        """Read an exported config file; return an empty dict on missing or broken parse."""
        content = {}
        # Both unreadable and unparseable count as "empty config"; callers
        # only care whether content is obtainable
        with contextlib.suppress(Exception):
            content = json.loads(FileUtils.read_text(file_name))

        return content

    @classmethod
    def generation(cls) -> int:
        """The current config-loading generation (recorded when @params
        resolves, checked at Master construction, #51).
        """
        return cls._generation

    @classmethod
    def get_params(cls, path, default_value=""):
        if path is None or path == "":
            return default_value
        path_split = path.split(":")
        value = cls.config_params
        for item in path_split:
            if value.get(item) is None:
                return default_value
            value = value[item]
        return value

get_export_file

get_export_file(file_name)

Read an exported config file; return an empty dict on missing or broken parse.

源代码位于: zoo_framework/core/params_factory.py
def get_export_file(self, file_name):
    """Read an exported config file; return an empty dict on missing or broken parse."""
    content = {}
    # Both unreadable and unparseable count as "empty config"; callers
    # only care whether content is obtainable
    with contextlib.suppress(Exception):
        content = json.loads(FileUtils.read_text(file_name))

    return content

generation classmethod

generation() -> int

The current config-loading generation (recorded when @params resolves, checked at Master construction, #51).

源代码位于: zoo_framework/core/params_factory.py
@classmethod
def generation(cls) -> int:
    """The current config-loading generation (recorded when @params
    resolves, checked at Master construction, #51).
    """
    return cls._generation

zoo_framework.core.params_path.ParamsPath

Configuration item path.

Supports declaring several candidate paths for the same configuration item: resolved in the order value first, then aliases in turn, for compatibility with historical key names. When a candidate is missing, the caller decides whether to fall back to the default.

参数:

名称 类型 描述 默认
value str

the preferred configuration path, like worker:pool:size

必需
default Any

the default used when all candidates are missing

''
aliases list[str] | None

fallback configuration paths, in order

None
源代码位于: zoo_framework/core/params_path.py
class ParamsPath:
    """Configuration item path.

    Supports declaring several candidate paths for the same configuration
    item: resolved in the order ``value`` first, then ``aliases`` in turn,
    for compatibility with historical key names. When a candidate is
    missing, the caller decides whether to fall back to the default.

    Args:
        value: the preferred configuration path, like ``worker:pool:size``
        default: the default used when all candidates are missing
        aliases: fallback configuration paths, in order
    """

    def __init__(self, value: str, default: Any = "", aliases: list[str] | None = None) -> None:
        self.value = value
        self.default = default
        self.aliases = list(aliases or [])

    def get_default(self) -> Any:
        return self.default

    def get_value(self) -> str:
        return self.value

    def get_aliases(self) -> list[str]:
        return list(self.aliases)