feat(api): per-service config schema endpoint + PUT/POST update+apply for fleet & topology
- GET /topologies/services/{name}/schema serves the declared ServiceConfigField
metadata so the Inspector can auto-render forms.
- PUT /(topologies/{id}/)deckies/{decky}/services/{svc}/config persists the
validated dict (DB + compose); container untouched (Save).
- POST /(topologies/{id}/)deckies/{decky}/services/{svc}/apply persists then
force-recreates <decky>-<svc> so the new env takes effect (Apply, destructive).
- New engine helper update_service_config wires both fleet and topology paths
through the existing _persist_fleet_change / _rerender_topology_compose
machinery; emits decky.<name>.service_config_changed on the bus.
This commit is contained in:
168
tests/api/deckies/test_service_config_api.py
Normal file
168
tests/api/deckies/test_service_config_api.py
Normal file
@@ -0,0 +1,168 @@
|
||||
"""API coverage for /services/{name}/schema + per-decky config PUT/POST.
|
||||
|
||||
Engine layer is patched so the tests don't touch docker; auth + routing
|
||||
+ schema-serialization + 4xx mapping run for real.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from decnet.engine import services_live
|
||||
from decnet.engine.services_live import ServiceMutationError
|
||||
from decnet.services.base import ConfigValidationError
|
||||
|
||||
_FLEET = "/api/v1/deckies"
|
||||
_TOPO = "/api/v1/topologies"
|
||||
|
||||
|
||||
def _hdr(token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
# ---------------- schema endpoint -----------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_ssh_schema_returns_declared_fields(
|
||||
client: httpx.AsyncClient, auth_token: str
|
||||
) -> None:
|
||||
res = await client.get(
|
||||
f"{_TOPO}/services/ssh/schema", headers=_hdr(auth_token),
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
body = res.json()
|
||||
assert body["name"] == "ssh"
|
||||
assert body["ports"] == [22]
|
||||
keys = {f["key"] for f in body["fields"]}
|
||||
assert keys == {"password", "hostname"}
|
||||
pw = next(f for f in body["fields"] if f["key"] == "password")
|
||||
assert pw["type"] == "password" and pw["secret"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_unknown_service_schema_404(
|
||||
client: httpx.AsyncClient, auth_token: str
|
||||
) -> None:
|
||||
res = await client.get(
|
||||
f"{_TOPO}/services/no-such-svc/schema", headers=_hdr(auth_token),
|
||||
)
|
||||
assert res.status_code == 404
|
||||
|
||||
|
||||
# ---------------- fleet PUT / POST apply ----------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fleet_put_config_persists_without_recreate(
|
||||
client: httpx.AsyncClient, auth_token: str, monkeypatch
|
||||
) -> None:
|
||||
seen: dict = {}
|
||||
|
||||
async def _fake_update(repo, **kw):
|
||||
seen.update(kw)
|
||||
return {"password": "hunter2"}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"decnet.web.router.deckies.api_services.update_service_config",
|
||||
_fake_update,
|
||||
)
|
||||
res = await client.put(
|
||||
f"{_FLEET}/web1/services/ssh/config",
|
||||
json={"config": {"password": "hunter2"}},
|
||||
headers=_hdr(auth_token),
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
body = res.json()
|
||||
assert body["recreated"] is False
|
||||
assert body["config"] == {"password": "hunter2"}
|
||||
assert seen["apply"] is False and seen["decky_kind"] == "fleet"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fleet_apply_config_triggers_recreate(
|
||||
client: httpx.AsyncClient, auth_token: str, monkeypatch
|
||||
) -> None:
|
||||
seen: dict = {}
|
||||
|
||||
async def _fake_update(repo, **kw):
|
||||
seen.update(kw)
|
||||
return kw["cfg"]
|
||||
|
||||
monkeypatch.setattr(
|
||||
"decnet.web.router.deckies.api_services.update_service_config",
|
||||
_fake_update,
|
||||
)
|
||||
res = await client.post(
|
||||
f"{_FLEET}/web1/services/ssh/apply",
|
||||
json={"config": {"password": "hunter2"}},
|
||||
headers=_hdr(auth_token),
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert res.json()["recreated"] is True
|
||||
assert seen["apply"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_put_config_400_on_validation_error(
|
||||
client: httpx.AsyncClient, auth_token: str, monkeypatch
|
||||
) -> None:
|
||||
async def _fake(*a, **kw):
|
||||
raise ConfigValidationError("response_code: expected int, got 'oops'")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"decnet.web.router.deckies.api_services.update_service_config", _fake,
|
||||
)
|
||||
res = await client.put(
|
||||
f"{_FLEET}/web1/services/http/config",
|
||||
json={"config": {"response_code": "oops"}},
|
||||
headers=_hdr(auth_token),
|
||||
)
|
||||
assert res.status_code == 400
|
||||
assert "response_code" in res.json()["detail"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_put_config_409_when_service_not_on_decky(
|
||||
client: httpx.AsyncClient, auth_token: str, monkeypatch
|
||||
) -> None:
|
||||
async def _fake(*a, **kw):
|
||||
raise ServiceMutationError("service 'ssh' not on decky 'web1'")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"decnet.web.router.deckies.api_services.update_service_config", _fake,
|
||||
)
|
||||
res = await client.put(
|
||||
f"{_FLEET}/web1/services/ssh/config",
|
||||
json={"config": {}},
|
||||
headers=_hdr(auth_token),
|
||||
)
|
||||
assert res.status_code == 409
|
||||
|
||||
|
||||
# ---------------- topology scope ------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_topology_put_config_passes_topology_id(
|
||||
client: httpx.AsyncClient, auth_token: str, monkeypatch
|
||||
) -> None:
|
||||
seen: dict = {}
|
||||
|
||||
async def _fake(repo, **kw):
|
||||
seen.update(kw)
|
||||
return kw["cfg"]
|
||||
|
||||
monkeypatch.setattr(
|
||||
"decnet.web.router.deckies.api_services.update_service_config", _fake,
|
||||
)
|
||||
res = await client.put(
|
||||
f"{_TOPO}/topo-abc/deckies/web1/services/ssh/config",
|
||||
json={"config": {"hostname": "mail-01"}},
|
||||
headers=_hdr(auth_token),
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
body = res.json()
|
||||
assert body["topology_id"] == "topo-abc"
|
||||
assert seen["topology_id"] == "topo-abc"
|
||||
assert seen["decky_kind"] == "topology"
|
||||
161
tests/engine/test_service_config_live.py
Normal file
161
tests/engine/test_service_config_live.py
Normal file
@@ -0,0 +1,161 @@
|
||||
"""Engine-layer coverage for services_live.update_service_config.
|
||||
|
||||
Mirrors test_services_live.py — _compose patched to a recorder, real
|
||||
SQLite + topology hydrator under test.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import AsyncIterator
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
from decnet.bus.fake import FakeBus
|
||||
from decnet.engine import services_live
|
||||
from decnet.engine.services_live import ServiceMutationError
|
||||
from decnet.services.base import ConfigValidationError
|
||||
from decnet.web.db.sqlite.repository import SQLiteRepository
|
||||
import decnet.web.db.models # noqa: F401 — register tables
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def repo(tmp_path) -> AsyncIterator[SQLiteRepository]:
|
||||
r = SQLiteRepository(str(tmp_path / "p.db"))
|
||||
await r.initialize()
|
||||
yield r
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def fake_bus(monkeypatch) -> AsyncIterator[FakeBus]:
|
||||
bus = FakeBus()
|
||||
await bus.connect()
|
||||
from decnet.bus import factory
|
||||
monkeypatch.setattr(factory, "get_bus", lambda: bus)
|
||||
yield bus
|
||||
await bus.close()
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def topology_with_ssh_decky(repo: SQLiteRepository) -> dict:
|
||||
topo_id = await repo.create_topology({"name": "topo", "description": ""})
|
||||
decky_uuid = await repo.add_topology_decky({
|
||||
"topology_id": topo_id,
|
||||
"name": "web1",
|
||||
"ip": "10.0.0.5",
|
||||
"decky_config": {"name": "web1", "ips_by_lan": {}},
|
||||
"services": ["ssh"],
|
||||
"state": "running",
|
||||
})
|
||||
return {"topology_id": topo_id, "decky_uuid": decky_uuid}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_persists_validated_cfg_no_recreate_on_save(
|
||||
repo: SQLiteRepository, topology_with_ssh_decky: dict, fake_bus: FakeBus,
|
||||
monkeypatch, tmp_path,
|
||||
) -> None:
|
||||
captured: list[tuple[str, ...]] = []
|
||||
monkeypatch.setattr(
|
||||
services_live, "_compose",
|
||||
lambda *a, **kw: captured.append(a),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
services_live, "_topology_compose_path",
|
||||
lambda topo_id: tmp_path / f"compose-{topo_id[:8]}.yml",
|
||||
)
|
||||
|
||||
validated = await services_live.update_service_config(
|
||||
repo,
|
||||
decky_kind="topology",
|
||||
topology_id=topology_with_ssh_decky["topology_id"],
|
||||
decky_name="web1",
|
||||
service_name="ssh",
|
||||
cfg={"password": "hunter2", "wat": "drop me"},
|
||||
apply=False,
|
||||
)
|
||||
# Unknown key dropped.
|
||||
assert validated == {"password": "hunter2"}
|
||||
# Persisted into the decky_config blob.
|
||||
rows = await repo.list_topology_deckies(
|
||||
topology_with_ssh_decky["topology_id"]
|
||||
)
|
||||
row = next(r for r in rows if r["uuid"] == topology_with_ssh_decky["decky_uuid"])
|
||||
cfg_blob = row["decky_config"]
|
||||
if isinstance(cfg_blob, str):
|
||||
cfg_blob = json.loads(cfg_blob)
|
||||
assert cfg_blob["service_config"]["ssh"] == {"password": "hunter2"}
|
||||
# Save-only: no compose force-recreate ran.
|
||||
assert not any("--force-recreate" in a for a in captured)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_apply_runs_force_recreate(
|
||||
repo: SQLiteRepository, topology_with_ssh_decky: dict, fake_bus: FakeBus,
|
||||
monkeypatch, tmp_path,
|
||||
) -> None:
|
||||
captured: list[tuple[str, ...]] = []
|
||||
monkeypatch.setattr(
|
||||
services_live, "_compose",
|
||||
lambda *a, **kw: captured.append(a),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
services_live, "_topology_compose_path",
|
||||
lambda topo_id: tmp_path / f"compose-{topo_id[:8]}.yml",
|
||||
)
|
||||
await services_live.update_service_config(
|
||||
repo,
|
||||
decky_kind="topology",
|
||||
topology_id=topology_with_ssh_decky["topology_id"],
|
||||
decky_name="web1",
|
||||
service_name="ssh",
|
||||
cfg={"password": "hunter2"},
|
||||
apply=True,
|
||||
)
|
||||
# Apply path issued compose up --force-recreate <decky>-<svc>.
|
||||
assert any(
|
||||
"--force-recreate" in a and "web1-ssh" in a
|
||||
for a in captured
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_rejects_service_not_on_decky(
|
||||
repo: SQLiteRepository, topology_with_ssh_decky: dict, fake_bus: FakeBus,
|
||||
) -> None:
|
||||
with pytest.raises(ServiceMutationError):
|
||||
await services_live.update_service_config(
|
||||
repo,
|
||||
decky_kind="topology",
|
||||
topology_id=topology_with_ssh_decky["topology_id"],
|
||||
decky_name="web1",
|
||||
service_name="http", # not on the decky
|
||||
cfg={},
|
||||
apply=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_rejects_bad_value_via_validator(
|
||||
repo: SQLiteRepository, topology_with_ssh_decky: dict, fake_bus: FakeBus,
|
||||
monkeypatch, tmp_path,
|
||||
) -> None:
|
||||
# Add http to the decky so we can submit a bad response_code.
|
||||
monkeypatch.setattr(services_live, "_compose", lambda *a, **kw: None)
|
||||
monkeypatch.setattr(
|
||||
services_live, "_topology_compose_path",
|
||||
lambda topo_id: tmp_path / f"compose-{topo_id[:8]}.yml",
|
||||
)
|
||||
await repo.update_topology_decky(
|
||||
topology_with_ssh_decky["decky_uuid"], {"services": ["ssh", "http"]},
|
||||
)
|
||||
with pytest.raises(ConfigValidationError):
|
||||
await services_live.update_service_config(
|
||||
repo,
|
||||
decky_kind="topology",
|
||||
topology_id=topology_with_ssh_decky["topology_id"],
|
||||
decky_name="web1",
|
||||
service_name="http",
|
||||
cfg={"response_code": "not-a-number"},
|
||||
apply=False,
|
||||
)
|
||||
Reference in New Issue
Block a user