Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

2.5 KB
Raw Blame
"""App-level settings (status checker interval, etc.)."""
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field

from app.api.deps import get_current_user
from app.core.config import settings
from app.core.scheduler import (
    reschedule_service_checks,
    reschedule_status_checks,
    set_service_checks_enabled,
)

router = APIRouter()


class AppSettings(BaseModel):
    # Mirrors the floor enforced by reschedule_status_checks(): rejecting here
    # returns 422 instead of persisting the value and then failing with a 500.
    interval_seconds: int = Field(ge=10)
    service_check_enabled: bool = False
    service_check_interval: int = Field(default=300, ge=30)


class AppSettingsOut(AppSettings):
    # Read-only: STATUS_CHECKER_ENABLED is env-only, so the UI can show that
    # checks are switched off server-side instead of offering controls that do
    # nothing. Not accepted on POST (AppSettings ignores unknown fields).
    status_checker_enabled: bool = True


def _out(payload: AppSettings) -> AppSettingsOut:
    return AppSettingsOut(**payload.model_dump(), status_checker_enabled=settings.status_checker_enabled)


@router.get("", response_model=AppSettingsOut)
async def get_settings(_: str = Depends(get_current_user)) -> AppSettingsOut:
    return _out(AppSettings(
        interval_seconds=settings.status_checker_interval,
        service_check_enabled=settings.service_check_enabled,
        service_check_interval=settings.service_check_interval,
    ))


@router.post("", response_model=AppSettingsOut)
async def update_settings(
    payload: AppSettings, _: str = Depends(get_current_user)
) -> AppSettingsOut:
    try:
        settings.status_checker_interval = payload.interval_seconds
        settings.service_check_enabled = payload.service_check_enabled
        settings.service_check_interval = payload.service_check_interval
        settings.save_overrides()
        # Apply the status-check schedule live. Without this the new interval is
        # persisted and shown in the UI, but the running job keeps the old one
        # until the backend restarts.
        reschedule_status_checks(payload.interval_seconds)
        # Apply the service-check schedule live.
        set_service_checks_enabled(payload.service_check_enabled)
        if payload.service_check_enabled:
            reschedule_service_checks(payload.service_check_interval)
        return _out(payload)
    except Exception as exc:
        raise HTTPException(status_code=500, detail=str(exc)) from exc