Eliminate direct app.state access from routers
This commit is contained in:
@@ -15,10 +15,11 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
from starlette.datastructures import State
|
||||
|
||||
from app.models.config import PendingRecovery
|
||||
from app.models.server import ServerStatus
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
from app.models.config import PendingRecovery
|
||||
from app.config import Settings
|
||||
|
||||
ActivationRecord = dict[str, datetime.datetime]
|
||||
|
||||
@@ -83,3 +84,53 @@ def get_runtime_state(app: Any) -> RuntimeState:
|
||||
if state is None or not hasattr(state, "runtime_state"):
|
||||
raise AttributeError("Runtime state has not been initialised on the application.")
|
||||
return state.runtime_state
|
||||
|
||||
|
||||
def get_app_settings(app: Any) -> Settings:
|
||||
"""Return the current immutable settings from application state."""
|
||||
settings = getattr(app.state, "settings", None)
|
||||
if settings is None:
|
||||
raise AttributeError("Application settings are not available on the app state.")
|
||||
return settings
|
||||
|
||||
|
||||
def update_app_settings(app: Any, **overrides: Any) -> None:
|
||||
"""Update the current application settings immutably."""
|
||||
settings = get_app_settings(app)
|
||||
app.state.settings = settings.model_copy(update=overrides)
|
||||
|
||||
|
||||
def record_activation(app: Any, jail_name: str, at: datetime.datetime | None = None) -> datetime.datetime:
|
||||
"""Record a jail activation timestamp in runtime state."""
|
||||
now = at if at is not None else datetime.datetime.now(tz=datetime.UTC)
|
||||
runtime_state = get_runtime_state(app)
|
||||
runtime_state.last_activation = {
|
||||
"jail_name": jail_name,
|
||||
"at": now,
|
||||
}
|
||||
return now
|
||||
|
||||
|
||||
def create_pending_recovery(
|
||||
app: Any,
|
||||
jail_name: str,
|
||||
activated_at: datetime.datetime,
|
||||
detected_at: datetime.datetime | None = None,
|
||||
) -> None:
|
||||
"""Create a pending recovery record in runtime state."""
|
||||
runtime_state = get_runtime_state(app)
|
||||
runtime_state.pending_recovery = PendingRecovery(
|
||||
jail_name=jail_name,
|
||||
activated_at=activated_at,
|
||||
detected_at=detected_at if detected_at is not None else datetime.datetime.now(tz=datetime.UTC),
|
||||
)
|
||||
|
||||
|
||||
def clear_pending_recovery(app: Any) -> None:
|
||||
"""Clear the current pending recovery record."""
|
||||
get_runtime_state(app).pending_recovery = None
|
||||
|
||||
|
||||
def clear_activation_record(app: Any) -> None:
|
||||
"""Clear the current activation tracking record."""
|
||||
get_runtime_state(app).last_activation = None
|
||||
|
||||
Reference in New Issue
Block a user