Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
from datetime import datetime
from typing import Any, Literal
from pydantic import BaseModel, field_validator
from app.services.doc_template import TEMPLATE_IDS
from app.services.doc_tree import DOCUMENT_KINDS
# Kept in sync with DocKind in frontend/src/documentation/types.ts.
# "page" and "folder" live in the Library tree and carry a parent; "device",
# "node" and "design" each point at exactly one thing elsewhere in the app and
# are placed by that link instead, so the frontend can pivot them however the
# user asks (by zone, subnet, type…) without the server storing a tree.
DOC_KINDS = set(DOCUMENT_KINDS)
# The reasons a caller may put its own name to. Everything else a revision can
# say — "restore", "regenerate", "scaffold", "migrate" — belongs to the action
# that takes it, so no client can dress a plain edit up as one of those.
CLIENT_REVISION_REASONS = frozenset({"edit", "mcp", "import"})
class DocumentCreate(BaseModel):
kind: str = "page"
title: str
icon: str | None = None
parent_id: str | None = None
device_id: str | None = None
node_id: str | None = None
design_id: str | None = None
# Scaffolds the body when no body is supplied. "device" is implied for a
# device document and is the only template that reads the live facts.
template_id: str | None = None
body: str | None = None
@field_validator("kind")
@classmethod
def _known_kind(cls, v: str) -> str:
if v not in DOC_KINDS:
raise ValueError(f"kind must be one of {sorted(DOC_KINDS)}")
return v
@field_validator("template_id")
@classmethod
def _known_template(cls, v: str | None) -> str | None:
if v is not None and v not in TEMPLATE_IDS:
raise ValueError(f"template_id must be one of {sorted(TEMPLATE_IDS)}")
return v
class DocumentUpdate(BaseModel):
title: str | None = None
icon: str | None = None
body: str | None = None
parent_id: str | None = None
sort_order: int | None = None
starred: bool | None = None
# Explicit: "I have re-read this and it is still true." Sent as a bare true
# rather than a timestamp so the server owns the clock.
reviewed: bool | None = None
# Accept the device's current facts as documented, clearing the drift
# banner without touching the body.
resync_facts: bool | None = None
# What the history should say caused this edit. Only read when the body
# actually changes — a starred flag or a rename snapshots nothing, so there
# is no revision to attribute. Defaults to "edit", the human in the editor.
revision_reason: str | None = None
@field_validator("revision_reason")
@classmethod
def _known_reason(cls, v: str | None) -> str | None:
if v is not None and v not in CLIENT_REVISION_REASONS:
raise ValueError(f"revision_reason must be one of {sorted(CLIENT_REVISION_REASONS)}")
return v
class DocumentSummary(BaseModel):
"""Everything the tree needs. Never carries a body — listings stay small."""
id: str
kind: str
title: str
slug: str
icon: str | None = None
parent_id: str | None = None
sort_order: int = 0
device_id: str | None = None
node_id: str | None = None
design_id: str | None = None
tags: list[str] = []
# The parsed frontmatter travels with the summary so the tree can badge a
# document as due for review without fetching every body.
frontmatter: dict[str, Any] = {}
starred: bool = False
template_id: str | None = None
# Whether the device has moved on since the snapshot was taken. Computed by
# the server because only the server knows the snapshot's shape: it holds
# `label` and `type` through their fallbacks and `properties` as a flat
# map, none of which the inventory wire shape can be compared against
# field by field.
drifted: bool = False
reviewed_at: datetime | None = None
edited_at: datetime | None = None
facts_synced_at: datetime | None = None
created_at: datetime
updated_at: datetime
model_config = {"from_attributes": True}
class DocumentResponse(DocumentSummary):
body: str = ""
facts_snapshot: dict[str, Any] | None = None
class RevisionSummary(BaseModel):
id: str
document_id: str
title: str
reason: str
saved_at: datetime
# Character count, so the history list can show how much changed without
# shipping every body.
size: int = 0
model_config = {"from_attributes": True}
class RevisionResponse(RevisionSummary):
body: str = ""
# ── Public (documentation view) ─────────────────────────────────────────────
# What DOCS_VIEW_KEY opens to anyone holding the URL.
#
# Written out field by field rather than subclassed from the models above, and
# that is the whole point: inheriting would enrol every field added to
# `DocumentSummary` later into the public payload by default. What is missing
# here is missing on purpose — `device_id`, `node_id`, `design_id`,
# `facts_snapshot`, `facts_synced_at`, `drifted` and `template_id` are handles
# onto inventory and canvas rows this key grants nothing of.
class PublicDocumentSummary(BaseModel):
"""What the public tree needs: placement, naming, badges. Never a body."""
id: str
kind: str
title: str
slug: str
icon: str | None = None
parent_id: str | None = None
sort_order: int = 0
tags: list[str] = []
# Parsed out of a body this key already serves, and what the tree badges
# "due for review" from — so it carries nothing the reader cannot see.
frontmatter: dict[str, Any] = {}
starred: bool = False
reviewed_at: datetime | None = None
edited_at: datetime | None = None
created_at: datetime
updated_at: datetime
model_config = {"from_attributes": True}
class PublicDocumentResponse(PublicDocumentSummary):
body: str = ""
class PublicRevisionSummary(BaseModel):
"""One earlier version, listed. Reading history is a read; restoring is not,
and the public router offers no way to take one."""
id: str
document_id: str
title: str
reason: str
saved_at: datetime
size: int = 0
model_config = {"from_attributes": True}
class PublicRevisionResponse(PublicRevisionSummary):
body: str = ""
class SearchHit(BaseModel):
doc_id: str
title: str
kind: str
snippet: str
device_id: str | None = None
class SearchResponse(BaseModel):
# "fts5" or "like" — the UI drops snippet highlighting on the fallback.
engine: str
hits: list[SearchHit]
class BacklinkHit(BaseModel):
"""A document that links here, and the line it does it on."""
doc_id: str
title: str
kind: str
device_id: str | None = None
# What the link was written as, so a `[[…|label]]` reads back as the author
# meant it rather than as the target's own title.
label: str
context: str
count: int = 1
class ScaffoldRequest(BaseModel):
"""Create the missing device documents.
Omitting `device_ids` means every approved device that has none, which is
the one-click migration off the old notes field.
"""
device_ids: list[str] | None = None
template_id: str = "device"
# Only devices whose notes are not empty. What the migration banner sends.
only_with_notes: bool = False
class ScaffoldResponse(BaseModel):
created: list[DocumentSummary]
skipped: int
class DriftField(BaseModel):
field: str
documented: Any = None
current: Any = None
class ResolutionItem(BaseModel):
"""What the user wants for one conflicting fact or section.
``choice`` is one of ``keep`` (keep the document's text), ``device`` (take
the device's value) or ``custom`` (the user's own replacement, in
``custom``). Sent for every conflict the user has decided on; conflicts the
modal still shows are simply absent.
"""
id: str
choice: Literal["keep", "device", "custom"] = "keep"
custom: str | None = None
class ReconcileChange(BaseModel):
"""One fact or section the update preview surfaced, and its disposition.
``status`` is ``same``, ``auto`` or ``conflict``. A conflict carries its
resolution here once the user has decided, so a preview rendered back can
show exactly where the merge landed.
"""
id: str
name: str
kind: str # "field" | "section"
status: str
documented: str
device: str
previous: str = ""
resolution: str | None = None # keep | device | custom
custom: str | None = None
model_config = {"from_attributes": True}
class UpdatePreviewRequest(BaseModel):
"""Optional resolutions to fold into the preview.
Sent with none to open the modal; the modal then re-previews with each
decision as the user makes it, so the merged body is always the server's
merge — never a local approximation.
"""
resolutions: list[ResolutionItem] = []
class UpdatePreviewResponse(BaseModel):
preview_id: str
changes: list[ReconcileChange]
proposed_body: str
summary: list[str] = []
# The conflict ids still waiting on a decision (drives the review step).
unresolved: list[str] = []
class UpdateApplyRequest(BaseModel):
"""Settle a preview, then save the merge.
``preview_id`` is echoed back so the server can reject a save made against
a preview the document has moved on from.
"""
preview_id: str
resolutions: list[ResolutionItem] = []
class CoverageResponse(BaseModel):
devices: int
documented: int
# A document whose body is still only what the template generated.
header_only: int
missing: int
drifted: int
overdue: int
notes_unmigrated: int
library_pages: int