Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(canvas): store a zone's size in the width/height columns
Pouzor851141951d28
diff --git a/backend/app/db/database.py b/backend/app/db/database.pyindex e4ce929..df2b2e8 100644--- a/backend/app/db/database.py+++ b/backend/app/db/database.py@@ -494,6 +494,7 @@ async def init_db() -> None:await _backfill_node_devices()await _drop_legacy_node_columns()await _seed_node_views()+ await _backfill_zone_size()@@ -752,6 +753,66 @@ async def _seed_node_views() -> None:logger.warning("Seeding the node service/property views failed: %s", exc)+async def _backfill_zone_size() -> None:+ """Move a zone's size out of the custom_colors blob into the real columns.++ Every node type stored its size in `nodes.width` / `nodes.height` except+ `groupRect`, which stashed it inside the `custom_colors` JSON alongside its+ colours. The serializer writes the columns for zones too now, so a canvas+ saved before this upgrade would come back at the default 360x240 without+ this backfill.++ Only fills a column that is still NULL, so it cannot overwrite a size the+ user has set since, and re-running it is a no-op. Parsed in Python rather+ than with `json_extract`, so it does not depend on the SQLite build being+ compiled with JSON1.++ Never fatal: the reader falls back to the blob, so the worst case of a+ failure here is that the geometry keeps coming from where it always did.+ """+ try:+ async with engine.begin() as conn:+ rows = (+ await conn.exec_driver_sql(+ "SELECT id, custom_colors FROM nodes "+ "WHERE type = 'groupRect' AND custom_colors IS NOT NULL "+ "AND (width IS NULL OR height IS NULL)"+ )+ ).fetchall()++ moved = 0+ for node_id, blob in rows:+ if isinstance(blob, str):+ try:+ blob = _json.loads(blob)+ except ValueError:+ continue+ if not isinstance(blob, dict):+ continue++ width, height = blob.get("width"), blob.get("height")+ # A bool is an int in Python; a size that is not a real number+ # is left alone rather than written as garbage.+ if not isinstance(width, int | float) or isinstance(width, bool):+ width = None+ if not isinstance(height, int | float) or isinstance(height, bool):+ height = None+ if width is None and height is None:+ continue++ await conn.exec_driver_sql(+ "UPDATE nodes SET width = COALESCE(width, ?), height = COALESCE(height, ?) "+ "WHERE id = ?",+ (width, height, node_id),+ )+ moved += 1++ if moved:+ logger.info("Moved the size of %d zone(s) to the width/height columns", moved)+ except Exception as exc: # pragma: no cover - defensive, boot must not die+ logger.warning("Backfilling zone width/height failed: %s", exc)++async def get_db() -> AsyncGenerator[AsyncSession, None]:async with AsyncSessionLocal() as session:yield sessiondiff --git a/backend/tests/test_zone_size_migration.py b/backend/tests/test_zone_size_migration.pynew file mode 100644index 0000000..9d2af3c--- /dev/null+++ b/backend/tests/test_zone_size_migration.py@@ -0,0 +1,139 @@+"""Moving a zone's size out of the custom_colors blob into the real columns.++Every node type stored its size in `nodes.width` / `nodes.height` except+`groupRect`, which kept it inside the style JSON. Get this backfill wrong and+every zone a user ever drew comes back at the default 360x240, losing a layout+they arranged by hand.+"""+import json++import pytest+from sqlalchemy.ext.asyncio import create_async_engine++import app.db.database as database++pytestmark = pytest.mark.asyncio++_DDL = (+ "CREATE TABLE nodes ("+ "id VARCHAR PRIMARY KEY, type VARCHAR, label VARCHAR, "+ "custom_colors JSON, width FLOAT, height FLOAT)"+)+++async def _engine(tmp_path, rows):+ engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'zones.db'}")+ async with engine.begin() as conn:+ await conn.exec_driver_sql(_DDL)+ for node_id, node_type, colors, width, height in rows:+ await conn.exec_driver_sql(+ "INSERT INTO nodes (id, type, label, custom_colors, width, height) "+ "VALUES (?, ?, ?, ?, ?, ?)",+ (node_id, node_type, node_id, json.dumps(colors) if colors else None, width, height),+ )+ return engine+++async def _sizes(engine) -> dict[str, tuple]:+ async with engine.begin() as conn:+ rows = (await conn.exec_driver_sql("SELECT id, width, height FROM nodes")).fetchall()+ return {r[0]: (r[1], r[2]) for r in rows}+++async def _run(engine, monkeypatch) -> None:+ monkeypatch.setattr(database, "engine", engine)+ await database._backfill_zone_size()+++async def test_moves_the_size_from_the_blob_to_the_columns(tmp_path, monkeypatch):+ engine = await _engine(+ tmp_path,+ [("z1", "groupRect", {"width": 640, "height": 480, "border": "#0ff"}, None, None)],+ )++ await _run(engine, monkeypatch)++ assert (await _sizes(engine))["z1"] == (640, 480)+ # The style the blob actually owns is untouched.+ async with engine.begin() as conn:+ blob = (await conn.exec_driver_sql("SELECT custom_colors FROM nodes")).scalar()+ assert json.loads(blob)["border"] == "#0ff"+ await engine.dispose()+++async def test_never_overwrites_a_size_already_in_the_columns(tmp_path, monkeypatch):+ # A zone resized since the upgrade: the column is the truth, and a stale+ # blob left over from before must not win.+ engine = await _engine(+ tmp_path,+ [("z1", "groupRect", {"width": 111, "height": 222}, 800, None)],+ )++ await _run(engine, monkeypatch)++ assert (await _sizes(engine))["z1"] == (800, 222)+ await engine.dispose()+++async def test_leaves_other_node_types_alone(tmp_path, monkeypatch):+ # Only zones ever stashed their size in the blob. A width key on any other+ # type is not geometry we should be moving.+ engine = await _engine(tmp_path, [("s1", "server", {"width": 999}, None, None)])++ await _run(engine, monkeypatch)++ assert (await _sizes(engine))["s1"] == (None, None)+ await engine.dispose()+++async def test_skips_a_blob_with_no_usable_size(tmp_path, monkeypatch):+ engine = await _engine(+ tmp_path,+ [+ ("colors_only", "groupRect", {"border": "#0ff"}, None, None),+ ("not_a_number", "groupRect", {"width": "wide", "height": True}, None, None),+ ("no_blob", "groupRect", None, None, None),+ ],+ )++ await _run(engine, monkeypatch)++ sizes = await _sizes(engine)+ assert sizes["colors_only"] == (None, None)+ assert sizes["not_a_number"] == (None, None)+ assert sizes["no_blob"] == (None, None)+ await engine.dispose()+++async def test_survives_a_corrupt_blob_without_killing_boot(tmp_path, monkeypatch):+ engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'zones.db'}")+ async with engine.begin() as conn:+ await conn.exec_driver_sql(_DDL)+ await conn.exec_driver_sql(+ "INSERT INTO nodes (id, type, label, custom_colors) VALUES ('bad', 'groupRect', 'b', '{oops')"+ )+ await conn.exec_driver_sql(+ "INSERT INTO nodes (id, type, label, custom_colors) "+ "VALUES ('good', 'groupRect', 'g', '{\"width\": 500, \"height\": 400}')"+ )++ await _run(engine, monkeypatch)++ sizes = await _sizes(engine)+ assert sizes["bad"] == (None, None)+ # One unreadable row must not cost the others their size.+ assert sizes["good"] == (500, 400)+ await engine.dispose()+++async def test_is_idempotent(tmp_path, monkeypatch):+ engine = await _engine(+ tmp_path,+ [("z1", "groupRect", {"width": 640, "height": 480}, None, None)],+ )++ await _run(engine, monkeypatch)+ await _run(engine, monkeypatch)++ assert (await _sizes(engine))["z1"] == (640, 480)+ await engine.dispose()diff --git a/frontend/src/stores/__tests__/canvasStore/zones.test.ts b/frontend/src/stores/__tests__/canvasStore/zones.test.tsindex d9c7c90..f0618ab 100644--- a/frontend/src/stores/__tests__/canvasStore/zones.test.ts+++ b/frontend/src/stores/__tests__/canvasStore/zones.test.ts@@ -240,12 +240,10 @@ describe('canvasStore — importZoneSubnet', () => {const z = useCanvasStore.getState().nodes.find((n) => n.id === 'z1')!expect(z.height!).toBeGreaterThan(300)- // The grown height has to survive a save/load round-trip. A zone has no- // height column, so the serializer stashes it in the custom_colors blob- // on the way out and hoists it back on the way in.- const wire = serializeNode(z) as { custom_colors: { height: number } }- expect(wire.custom_colors.height).toBe(z.height)- const reloaded = deserializeApiNode(wire as unknown as ApiNode, new Map())+ // The grown height has to survive a save/load round-trip.+ const wire = serializeNode(z) as unknown as ApiNode+ expect(wire.height).toBe(z.height)+ const reloaded = deserializeApiNode(wire, new Map())expect(reloaded.height).toBe(z.height)})diff --git a/frontend/src/utils/__tests__/canvasSerializer.test.ts b/frontend/src/utils/__tests__/canvasSerializer.test.tsindex 0da81fa..423276a 100644--- a/frontend/src/utils/__tests__/canvasSerializer.test.ts+++ b/frontend/src/utils/__tests__/canvasSerializer.test.ts@@ -165,7 +165,7 @@ describe('serializeNode — regular node', () => {// ── serializeNode — groupRect ─────────────────────────────────────────────────describe('serializeNode — groupRect', () => {- it('stores dimensions inside custom_colors', () => {+ it('stores dimensions in the width/height columns, like every other node type', () => {const node = makeRfNode({type: 'groupRect',data: { label: 'Zone A', type: 'groupRect', status: 'unknown', services: [] },@@ -173,8 +173,25 @@ describe('serializeNode — groupRect', () => {height: 250,})const result = serializeNode(node)- expect((result.custom_colors as Record<string, unknown>).width).toBe(400)- expect((result.custom_colors as Record<string, unknown>).height).toBe(250)+ expect(result.width).toBe(400)+ expect(result.height).toBe(250)+ })++ it('keeps the size out of the style blob, so the two cannot drift apart', () => {+ const node = makeRfNode({+ type: 'groupRect',+ // A zone loaded before the move still carries the legacy keys in memory.+ data: {+ label: 'Z', type: 'groupRect', status: 'unknown', services: [],+ custom_colors: { border: '#aaa', width: 111, height: 222 },+ },+ width: 400,+ height: 250,+ })+ const cc = serializeNode(node).custom_colors as Record<string, unknown>+ expect(cc.width).toBeUndefined()+ expect(cc.height).toBeUndefined()+ expect(cc.border).toBe('#aaa')})it('prefers explicit width/height over measured, falling back to measured per-axis', () => {@@ -184,15 +201,15 @@ describe('serializeNode — groupRect', () => {}const result = serializeNode(node)// Explicit width wins; height has no explicit value so it uses measured.- expect((result.custom_colors as Record<string, unknown>).width).toBe(400)- expect((result.custom_colors as Record<string, unknown>).height).toBe(260)+ expect(result.width).toBe(400)+ expect(result.height).toBe(260)})it('falls back to defaults when no dimensions available', () => {const node = makeRfNode({ type: 'groupRect', data: { label: 'Z', type: 'groupRect', status: 'unknown', services: [] } })const result = serializeNode(node)- expect((result.custom_colors as Record<string, unknown>).width).toBe(360)- expect((result.custom_colors as Record<string, unknown>).height).toBe(240)+ expect(result.width).toBe(360)+ expect(result.height).toBe(240)})it('preserves existing custom_colors fields alongside dimensions', () => {@@ -205,8 +222,8 @@ describe('serializeNode — groupRect', () => {const cc = result.custom_colors as Record<string, unknown>expect(cc.border).toBe('#aaa')expect(cc.z_order).toBe(2)- expect(cc.width).toBe(300)- expect(cc.height).toBe(200)+ expect(result.width).toBe(300)+ expect(result.height).toBe(200)})})@@ -420,9 +437,9 @@ describe('deserializeApiNode — regular node', () => {describe('deserializeApiNode — groupRect', () => {const emptyMap = new Map<string, boolean>()- it('restores width/height from custom_colors', () => {+ it('restores width/height from the columns', () => {const result = deserializeApiNode(- makeApiNode({ type: 'groupRect', custom_colors: { width: 400, height: 250, z_order: 2 } }),+ makeApiNode({ type: 'groupRect', width: 400, height: 250, custom_colors: { z_order: 2 } }),emptyMap,)expect(result.width).toBe(400)@@ -430,7 +447,27 @@ describe('deserializeApiNode — groupRect', () => {expect(result.zIndex).toBe(-8)})- it('defaults to 360x240 when custom_colors has no dimensions', () => {+ it('still reads a legacy canvas that kept its size in custom_colors', () => {+ // Saved before the size moved to the columns, and not yet migrated: no+ // fallback here means the zone comes back at the default 360x240.+ const result = deserializeApiNode(+ makeApiNode({ type: 'groupRect', custom_colors: { width: 400, height: 250, z_order: 2 } }),+ emptyMap,+ )+ expect(result.width).toBe(400)+ expect(result.height).toBe(250)+ })++ it('lets the columns win over a stale legacy blob', () => {+ const result = deserializeApiNode(+ makeApiNode({ type: 'groupRect', width: 500, height: 300, custom_colors: { width: 111, height: 222 } }),+ emptyMap,+ )+ expect(result.width).toBe(500)+ expect(result.height).toBe(300)+ })++ it('defaults to 360x240 when neither source has dimensions', () => {const result = deserializeApiNode(makeApiNode({ type: 'groupRect' }), emptyMap)expect(result.width).toBe(360)expect(result.height).toBe(240)diff --git a/frontend/src/utils/canvasSerializer.ts b/frontend/src/utils/canvasSerializer.tsindex 2d629d9..2bdbb7f 100644--- a/frontend/src/utils/canvasSerializer.ts+++ b/frontend/src/utils/canvasSerializer.ts@@ -64,6 +64,18 @@ export interface ApiEdge {// ── Serialization (RF node → API save payload) ───────────────────────────────+/** Drop the legacy geometry keys from a zone's style blob — its size lives in+ * the `width`/`height` columns now, and a stale copy here would be the one an+ * older canvas reads back. */+function omitZoneSize(+ colors: NodeData['custom_colors'],+): Record<string, unknown> {+ if (!colors) return {}+ return Object.fromEntries(+ Object.entries(colors).filter(([key]) => key !== 'width' && key !== 'height'),+ )+}+export function serializeNode(n: Node<NodeData>,factsBaseline?: FactsBaseline,@@ -89,10 +101,14 @@ export function serializeNode(custom_icon: null,pos_x: n.position.x,pos_y: n.position.y,+ // A zone's size goes in the real columns, like every other node type.+ // It used to live in the custom_colors blob; `width`/`height` are+ // stripped from it below so the two cannot drift apart, and a canvas+ // saved before the change is migrated by `_backfill_zone_size`.+ width: n.width ?? n.measured?.width ?? 360,+ height: n.height ?? n.measured?.height ?? 240,custom_colors: {- ...n.data.custom_colors,- width: n.width ?? n.measured?.width ?? 360,- height: n.height ?? n.measured?.height ?? 240,+ ...omitZoneSize(n.data.custom_colors),// Stash collapse state inside custom_colors so the API/YAML blob does// not need a new column. Hoisted back to `data.collapsed` on load.collapsed: n.data.collapsed ?? false,@@ -182,8 +198,11 @@ export function deserializeApiNode(): Node<NodeData> {const normalizedType = n.type === 'docker' ? 'docker_host' : n.typeif (n.type === 'groupRect') {- const w = (n.custom_colors?.width as number | undefined) ?? 360- const h = (n.custom_colors?.height as number | undefined) ?? 240+ // Prefer the real columns; fall back to the custom_colors stash for a+ // canvas saved before the size moved out of it, and which the backend+ // backfill has not reached (a payload from an older server, an import).+ const w = n.width ?? (n.custom_colors?.width as number | undefined) ?? 360+ const h = n.height ?? (n.custom_colors?.height as number | undefined) ?? 240const z = (n.custom_colors?.z_order as number | undefined) ?? 1// Hoist persisted collapse flag from the custom_colors stash to a// first-class field on NodeData. Tolerates legacy saves that already had