Device node: a device's ports are wired in flows

- flow/nodes/device.py: `device` node with params `device` and `config`;
  provides the device's `in` ports, requires its `out` ports without
  waking anything, never run (Node.passive), down "Offline" from presence
- DeviceDef.io and DevicePort go; GET /devices/{id} computes `io` and
  `bindings` from the device nodes of published flows, in a fixed order,
  cached by FlowStore.revision; the credential's scope comes from them
- issues `unknown_device` and `device_port` (wired twice; against a report
  the wrong direction or dtype, or unlisted as advisory), rechecked when a
  device is created or deleted; ValidationIssue.advisory is a field
- a device publishing on a bound port is credited to its node by the
  server; the panel endpoint kind is gone from `_endpoints` and the canvas
- a rebuild that moves a device's bindings sends `dashboard_changed` with
  an empty name, which the firmware refetches on
- startup moves each device's `io` rows into device nodes in the flows
  declaring their messages, draft and published, one commit; rows no
  flow declares are logged and left out
- frontend: Device node settings (device, Publishes, Follows, a port
  picker from a report), palette shortcuts per reported port, DeviceDetail
  lists bindings with "Use in flow" in place of the I/O editor
- docs: devices, flow editor, node types, issues, API
This commit is contained in:
Melvin Strobl
2026-10-16 16:40:31 +02:00
parent 91e3b703f9
commit 29d3ec467f
35 changed files with 2195 additions and 494 deletions
+72 -21
View File
@@ -13,7 +13,8 @@ comes. Anyone on the internet can ask the portal for a code, so a request that
came that way is adopted by its code only.
The credential is scoped: ``fluksio.api.deps`` lets it reach the dashboards
that device was assigned, the messages their widgets bind to, and nothing else.
that device was assigned, the messages their widgets bind to, the messages the
device nodes in published flows wire its own ports to, and nothing else.
Deleting the device revokes it, and so does unpairing, which bumps the
device's nonce and leaves what it shows as it was.
@@ -25,6 +26,7 @@ from __future__ import annotations
import secrets
import time
from contextlib import suppress
from datetime import datetime, timedelta
from typing import Any, cast
@@ -43,9 +45,12 @@ from fluksio.api.deps import (
from fluksio.cloud import config as cloud_config
from fluksio.core import security
from fluksio.core.config import settings
from fluksio.flow.controller import RebuildBusy
from fluksio.flow.devices import (
DeviceBinding,
DeviceDef,
DeviceExists,
DeviceIo,
DeviceNotFound,
DeviceStore,
is_lan,
@@ -288,12 +293,27 @@ class DeviceCreate(BaseModel):
title: str = ""
class DevicePublic(DeviceDef):
class DeviceDocument(DeviceDef):
"""A device as it reads itself: what it shows, and what its ports carry.
``io`` is worked out from the device nodes in published flows, in a fixed
order, so an unchanged state reads back as the same bytes.
"""
#: Each port the flows wire, and the message it publishes or follows.
io: list[DeviceIo] = Field(default_factory=list)
#: The same ports by the flow and node holding them.
bindings: list[DeviceBinding] = Field(default_factory=list)
class DevicePublic(DeviceDocument):
"""A device as the Devices tab lists it, with whether it is there."""
online: bool = False
#: The last request it made, since this instance started.
last_seen: datetime | None = None
#: What the device says it has, as it last said so. None until it reports.
report: dict[str, Any] | None = None
class DevicesPublic(BaseModel):
@@ -364,6 +384,26 @@ def _not_found(device_id: str) -> HTTPException:
return HTTPException(status_code=404, detail=f"No device named {device_id!r}")
def _document(device: DeviceDef, store: DeviceStore) -> DeviceDocument:
return DeviceDocument(
**device.model_dump(),
io=store.io(device.id),
bindings=store.bindings(device.id),
)
async def _recheck(request: Request) -> None:
"""Validate the flows again: a device node may name this device.
The device is saved either way, so a busy engine is not this request's
failure: the next rebuild validates again.
"""
controller = getattr(request.app.state, "flow_controller", None)
if controller is not None:
with suppress(RebuildBusy):
await controller.recheck()
def _changed() -> None:
"""Tell every device socket that what it shows may have moved.
@@ -457,15 +497,19 @@ panels_router.add_api_route(
@router.get("/", response_model=DevicesPublic, dependencies=[Depends(get_current_user)])
async def read_devices(store: DeviceStoreDep) -> Any:
"""Every device, what each one shows, and whether it is connected."""
devices = await run_in_threadpool(store.list)
data = [
DevicePublic(
**device.model_dump(),
online=presence.online(device.id),
last_seen=presence.last_seen(device.id),
)
for device in devices
]
def gather() -> list[DevicePublic]:
return [
DevicePublic(
**_document(device, store).model_dump(),
online=presence.online(device.id),
last_seen=presence.last_seen(device.id),
report=store.state(device.id).report,
)
for device in store.list()
]
data = await run_in_threadpool(gather)
return DevicesPublic(
data=data,
count=len(data),
@@ -503,7 +547,10 @@ def pending_device(code: str) -> Any:
dependencies=[Depends(get_current_active_superuser)],
)
async def create_device(
device_id: str, store: DeviceStoreDep, body: DeviceCreate | None = None
device_id: str,
store: DeviceStoreDep,
request: Request,
body: DeviceCreate | None = None,
) -> Any:
"""Add a device. It shows nothing until it is given dashboards."""
if device_id in RESERVED:
@@ -513,35 +560,38 @@ async def create_device(
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc))
try:
return await run_in_threadpool(store.create, device)
created = await run_in_threadpool(store.create, device)
except DeviceExists:
raise HTTPException(status_code=409, detail=f"{device_id!r} already exists")
await _recheck(request)
return created
@router.get(
"/{device_id}",
response_model=DeviceDef,
response_model=DeviceDocument,
dependencies=[Depends(get_current_user)],
)
async def read_device(device_id: str, store: DeviceStoreDep) -> Any:
"""One device, read by a person or by the device holding its credential.
The definition alone: a device compares what it reads with what it is
showing, and a field that changes on every request would rebuild its
screen each time. Declared after the pairing routes and ``/pending``, so
neither is mistaken for a device of that name.
The definition and what the flows wire its ports to, nothing about this
moment: a device compares what it reads with what it is showing, and a
field that changes on every request would rebuild its screen each time.
Declared after the pairing routes and ``/pending``, so neither is mistaken
for a device of that name.
"""
device = await run_in_threadpool(store.find, device_id)
if device is None:
raise _not_found(device_id)
return device
return await run_in_threadpool(_document, device, store)
panels_router.add_api_route(
"/{device_id}",
read_device,
methods=["GET"],
response_model=DeviceDef,
response_model=DeviceDocument,
dependencies=[Depends(get_current_user)],
)
@@ -580,12 +630,13 @@ async def save_device(device_id: str, body: DeviceDef, store: DeviceStoreDep) ->
response_model=Message,
dependencies=[Depends(get_current_active_superuser)],
)
async def delete_device(device_id: str, store: DeviceStoreDep) -> Any:
async def delete_device(device_id: str, store: DeviceStoreDep, request: Request) -> Any:
"""Remove the device and refuse its credential, wherever it was minted here."""
try:
await run_in_threadpool(store.delete, device_id)
except DeviceNotFound:
raise _not_found(device_id)
await _recheck(request)
_changed()
return Message(message=f"Deleted {device_id}")