system_state.py 1.91 KB
"""Runtime registry for system startup and shutdown state."""

from __future__ import annotations

from typing import Dict


class SystemStateRegistry:
    """Explicit wrapper around system runtime state."""

    def __init__(self) -> None:
        self._state = {
            "started": False,
            "starting": False,
            "shutdown_requested": False,
        }

    def snapshot(self) -> Dict[str, bool]:
        return dict(self._state)

    def set_state(self, *, started: bool | None = None, starting: bool | None = None) -> None:
        if started is not None:
            self._state["started"] = bool(started)
        if starting is not None:
            self._state["starting"] = bool(starting)
        if started:
            self._state["shutdown_requested"] = False

    def prepare_start(self) -> tuple[bool, str]:
        state = self.snapshot()
        if state["starting"]:
            return False, "系统正在启动,请稍候"
        self.set_state(starting=True)
        self._state["shutdown_requested"] = False
        return True, "系统启动中"

    def request_shutdown(self) -> bool:
        if self._state["shutdown_requested"]:
            return False
        self._state["shutdown_requested"] = True
        return True

    def clear_shutdown_request(self) -> None:
        self._state["shutdown_requested"] = False


SYSTEM_STATE_REGISTRY = SystemStateRegistry()


def get_system_state() -> Dict[str, bool]:
    return SYSTEM_STATE_REGISTRY.snapshot()


def set_system_state(*, started: bool | None = None, starting: bool | None = None) -> None:
    SYSTEM_STATE_REGISTRY.set_state(started=started, starting=starting)


def prepare_system_start() -> tuple[bool, str]:
    return SYSTEM_STATE_REGISTRY.prepare_start()


def mark_shutdown_requested() -> bool:
    return SYSTEM_STATE_REGISTRY.request_shutdown()


def clear_shutdown_request() -> None:
    SYSTEM_STATE_REGISTRY.clear_shutdown_request()