244 lines
11 KiB
Python
244 lines
11 KiB
Python
from __future__ import annotations
|
|
|
|
import time
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
from test_xgrids_application_mqtt import FakeControlClient, _binding
|
|
|
|
from k1link.device_plugins.xgrids_k1.device_management import DeviceManagementRequest
|
|
from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
|
|
ApplicationControlAuthority,
|
|
)
|
|
from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
|
|
_bytes_field as blob,
|
|
)
|
|
from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
|
|
_text_field as text,
|
|
)
|
|
from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
|
|
_varint_field as uint,
|
|
)
|
|
from k1link.device_plugins.xgrids_k1.protocol.application_mqtt import (
|
|
ApplicationCommandOutcomeUnknown,
|
|
ReviewedApplicationMqttTransport,
|
|
)
|
|
from k1link.device_plugins.xgrids_k1.protocol.application_session import (
|
|
ApplicationConnectionBinding,
|
|
InteractiveApplicationControlSession,
|
|
)
|
|
from k1link.device_plugins.xgrids_k1.protocol.device_management import (
|
|
CONTROL_RESPONSE,
|
|
PROJECT_RESPONSE,
|
|
decode_management_response,
|
|
decode_storage_mode,
|
|
management_action,
|
|
management_envelope,
|
|
management_identity,
|
|
)
|
|
from k1link.device_plugins.xgrids_k1.protocol.management_mailbox import (
|
|
MaintenanceJob,
|
|
ManagementMailbox,
|
|
)
|
|
from k1link.device_plugins.xgrids_k1.protocol.modeling_control import OPENAPI_SUCCESS
|
|
from k1link.device_plugins.xgrids_k1.protocol.protobuf_wire import iter_fields
|
|
|
|
|
|
def envelope(operation="projects", ids=()):
|
|
return management_envelope(operation, "synthetic-op", ApplicationControlAuthority(
|
|
openapi_key="11111111-2222-3333-4444-555555555555"), _binding(), ids)
|
|
|
|
|
|
def response(operation="projects", projects=()):
|
|
request = envelope(operation, ("synthetic",) if operation == "delete-projects" else ())
|
|
header = next(item.value for item in iter_fields(request.payload) if item.number == 1)
|
|
return (blob(1, header) + uint(2, management_action(request.payload))
|
|
+ b"".join(blob(4, text(1, ident) + text(2, name) + text(12, "private-url"))
|
|
for ident, name in projects)
|
|
+ blob(15, uint(1, OPENAPI_SUCCESS)))
|
|
|
|
|
|
def info(*, storage=False, storage_type=1):
|
|
return blob(2, blob(7, uint(4, int(storage))) + blob(10, uint(1, storage_type * 2))) \
|
|
+ blob(15, uint(1, OPENAPI_SUCCESS))
|
|
|
|
|
|
@pytest.mark.parametrize("operation,code", [
|
|
("usb-storage", 15), ("usb-data", 16), ("format-storage", 17),
|
|
("power-off", 20), ("reboot", 22), ("projects", 23), ("delete-projects", 25),
|
|
])
|
|
def test_vendor_actions_and_exact_single_or_batch_delete(operation, code):
|
|
request = envelope(operation, ("one",) if operation == "delete-projects" else ())
|
|
assert management_action(request.payload) == code
|
|
assert request.qos == 2 and not request.retain
|
|
if operation == "delete-projects":
|
|
assert [p.number for p in iter_fields(request.payload)] == [1, 2, 3]
|
|
assert [p.number for p in iter_fields(envelope(operation, ("one", "two")).payload)] \
|
|
== [1, 2, 5, 5]
|
|
|
|
|
|
def test_large_catalog_retains_names_only_and_rejects_duplicate_ids():
|
|
raw = response(projects=[(str(i), f"Проект {i}") for i in range(100)])
|
|
assert management_identity(raw).session_id.endswith(":synthetic-op")
|
|
result = decode_management_response(raw, "projects")
|
|
assert len(result["projects"]) == 100
|
|
assert result["projects"][0] == {"id": "0", "name": "Проект 0"}
|
|
with pytest.raises(ValueError, match="duplicate"):
|
|
decode_management_response(response(projects=[("one", "A"), ("one", "B")]), "projects")
|
|
|
|
|
|
def test_mode_is_observed_and_never_inferred_from_command():
|
|
assert decode_storage_mode(info(storage=True)) == {
|
|
"usb_mode": "storage", "storage_type": "microSD",
|
|
}
|
|
assert decode_storage_mode(info())["usb_mode"] == "data"
|
|
with pytest.raises(ValueError):
|
|
decode_storage_mode(response("usb-storage"))
|
|
|
|
|
|
def test_mismatched_action_cannot_satisfy_same_session_response():
|
|
request = envelope("reboot")
|
|
fake = FakeControlClient(response_topic=CONTROL_RESPONSE)
|
|
transport = ReviewedApplicationMqttTransport("192.168.1.20", client_factory=lambda: fake)
|
|
transport.open()
|
|
# Same identity, wrong action: neither UI success nor control proof.
|
|
fake.events.append(("message", (CONTROL_RESPONSE, response("power-off"))))
|
|
with pytest.raises(ApplicationCommandOutcomeUnknown):
|
|
transport.exchange_batch_once([request],
|
|
required_response_operation_keys={request.operation_key})
|
|
assert transport.snapshot().correlated_responses == 0
|
|
|
|
|
|
def test_management_dispatch_commit_runs_with_physical_observer_noop():
|
|
fake = FakeControlClient(response_topic=PROJECT_RESPONSE)
|
|
transport = ReviewedApplicationMqttTransport("192.168.1.20", client_factory=lambda: fake)
|
|
transport.install_evidence_observer(SimpleNamespace(
|
|
publish_dispatching=lambda *a, **kw: None, publish_result=lambda *a, **kw: None,
|
|
qos2_completed=lambda *a: None, application_response=lambda *a: None,
|
|
))
|
|
transport.open()
|
|
commits = []
|
|
request = envelope()
|
|
transport.exchange_batch_once([request],
|
|
required_response_operation_keys={request.operation_key},
|
|
dispatch_admission_commit=lambda: commits.append(True))
|
|
transport.close()
|
|
assert commits == [True]
|
|
|
|
|
|
class MailboxTransport:
|
|
def __init__(self, *, standby=True, lose_reply=False):
|
|
self.standby, self.lose_reply, self.sent = standby, lose_reply, []
|
|
|
|
def standby_complete(self, binding):
|
|
return self.standby
|
|
|
|
def exchange_batch_once(self, batch, **kwargs):
|
|
assert not kwargs["dispatch_admission_deadline_reached"]()
|
|
kwargs["dispatch_admission_commit"]()
|
|
self.sent.append(batch[0])
|
|
if self.lose_reply:
|
|
raise TimeoutError()
|
|
raw = info() if batch[0].operation_key.startswith("management-info:") else response()
|
|
return {batch[0].operation_key: raw}
|
|
|
|
|
|
def pump(box, transport, operation="projects", *, stale=False, expired=False, ids=()):
|
|
job = MaintenanceJob(operation, "synthetic-op", ids, 1, 2,
|
|
time.monotonic() + (-1 if expired else 5))
|
|
box.pending = job
|
|
def validate(_job):
|
|
if stale:
|
|
raise ValueError("stale checkpoint")
|
|
box.pump(transport, ApplicationControlAuthority(
|
|
openapi_key="11111111-2222-3333-4444-555555555555"), _binding(), validate)
|
|
assert job.finished.is_set() and box.pending is None
|
|
return job.result
|
|
|
|
|
|
@pytest.mark.parametrize("reason", ["active", "stale", "expired", "unknown-catalog"])
|
|
def test_no_hardware_publish_without_current_idle_admission(reason):
|
|
box, transport = ManagementMailbox(), MailboxTransport(standby=reason != "active")
|
|
result = pump(box, transport, "delete-projects" if reason == "unknown-catalog" else "projects",
|
|
stale=reason == "stale", expired=reason == "expired",
|
|
ids=("one",) if reason == "unknown-catalog" else ())
|
|
assert result["status"] == "blocked" and not transport.sent
|
|
|
|
|
|
def test_lost_write_reply_is_unknown_blocks_start_and_is_not_retried():
|
|
box, transport = ManagementMailbox(), MailboxTransport(lose_reply=True)
|
|
result = pump(box, transport, "usb-storage")
|
|
assert result["status"] == "unknown" and box.block_start
|
|
box.pump(transport, None, None, lambda job: None)
|
|
assert len(transport.sent) == 1
|
|
|
|
|
|
def test_closed_worker_cancels_queued_unpublished_job():
|
|
box = ManagementMailbox()
|
|
job = MaintenanceJob("projects", "synthetic-op", (), 1, 2, time.monotonic() + 5)
|
|
box.pending = job
|
|
box.cancel_queued()
|
|
assert box.pending is None and job.finished.is_set() and job.result["status"] == "blocked"
|
|
|
|
|
|
@pytest.mark.parametrize("failure", [None, "reject-second", "lose-second"])
|
|
def test_group_deletion_uses_confirmed_single_requests_and_stops_on_failure(failure):
|
|
class DeletingTransport(MailboxTransport):
|
|
def exchange_batch_once(self, batch, **kwargs):
|
|
assert not kwargs["dispatch_admission_deadline_reached"]()
|
|
kwargs["dispatch_admission_commit"]()
|
|
request = batch[0]
|
|
self.sent.append(request)
|
|
if request.operation_key.startswith("management-info:"):
|
|
return {request.operation_key: info()}
|
|
fields = list(iter_fields(request.payload))
|
|
assert [p.number for p in fields] == [1, 2, 3]
|
|
index = len(self.sent)
|
|
if failure == "lose-second" and index == 2:
|
|
raise TimeoutError()
|
|
code = 839122945 if failure == "reject-second" and index == 2 else OPENAPI_SUCCESS
|
|
raw = blob(1, fields[0].value) + uint(2, 25) + blob(15, uint(1, code))
|
|
return {request.operation_key: raw}
|
|
|
|
box, transport = ManagementMailbox(), DeletingTransport()
|
|
box.generation, box.catalog_revision, box.project_ids = 1, "catalog", {"one", "two", "three"}
|
|
job = MaintenanceJob("delete-projects", "batch", ("one", "two", "three"), 1, 2,
|
|
time.monotonic() + 5, catalog_revision="catalog")
|
|
box.pending = job
|
|
box.pump(transport, ApplicationControlAuthority(
|
|
openapi_key="11111111-2222-3333-4444-555555555555"), _binding(), lambda _: None)
|
|
assert job.finished.is_set()
|
|
requests = [p for p in transport.sent if p.operation_key.startswith("management:")]
|
|
assert len({p.operation_key for p in requests}) == len(requests)
|
|
assert [next(f.value for f in iter_fields(p.payload) if f.number == 3) for p in requests] \
|
|
== ([b"one", b"two"] if failure else [b"one", b"two", b"three"])
|
|
assert job.result["deleted_project_ids"] == (["one"] if failure else ["one", "two", "three"])
|
|
expected = {None: "succeeded", "reject-second": "rejected", "lose-second": "unknown"}
|
|
assert job.result["status"] == expected[failure]
|
|
assert box.block_start is (failure == "lose-second")
|
|
|
|
|
|
def test_destructive_request_requires_confirmation_and_no_arbitrary_parameters():
|
|
base = dict(operation_id="synthetic-op", expected_session_generation=1,
|
|
expected_state_revision=2, operation="format-storage")
|
|
with pytest.raises(ValueError):
|
|
DeviceManagementRequest(**base)
|
|
with pytest.raises(ValueError):
|
|
DeviceManagementRequest(**base, operator_confirmed=True, path="/arbitrary")
|
|
|
|
|
|
def test_mass_storage_cannot_remove_its_only_control_path():
|
|
session = InteractiveApplicationControlSession(SimpleNamespace())
|
|
session._phase = "connection-ready"
|
|
job = MaintenanceJob("usb-storage", "synthetic-op", (), 0, 0, time.monotonic() + 5)
|
|
for mode in ("usb", "quick-connect", "direct-connect", "bridge"):
|
|
session._connection_binding = ApplicationConnectionBinding(
|
|
"synthetic-intent", "synthetic-transport", 1, "192.0.2.1", 1883, mode,
|
|
)
|
|
if mode == "bridge":
|
|
session._validate_management_job(job)
|
|
else:
|
|
with pytest.raises(ValueError, match="Bridge"):
|
|
session._validate_management_job(job)
|
|
assert session._management.pending is None
|