feat(events): deliver state changes to the configurable operator event center
This commit is contained in:
@@ -0,0 +1,138 @@
|
||||
"""Disconnected simulated board, actual history and settings, no socket or hardware."""
|
||||
|
||||
from test_pairing import cert, create, heartbeat
|
||||
from test_pairing import setup as setup
|
||||
from test_rover_control import arm, cmd, exchange
|
||||
from test_rover_control import hub as hub
|
||||
|
||||
from k1link.fleet.board_event_transitions import BoardPresence, publish_control
|
||||
from k1link.fleet.node_operator_events import accept_operator_events
|
||||
from k1link.fleet.power import SCHEMA, BoardPower
|
||||
from k1link.notifications import NotificationHistory
|
||||
|
||||
ROW = {
|
||||
"id": "board",
|
||||
"node_id": "node",
|
||||
"binding": {"binding_id": "owner"},
|
||||
"name": "Тест",
|
||||
"enrollment": "paired",
|
||||
}
|
||||
|
||||
|
||||
def test_silence_and_return_use_local_deadline_only(tmp_path):
|
||||
h = NotificationHistory(tmp_path)
|
||||
now = [50]
|
||||
presence = BoardPresence(h, lambda: now[0], lambda: now[0] + 100)
|
||||
presence.expire(ROW)
|
||||
presence.received(ROW)
|
||||
for now[0] in (58, 65, 80):
|
||||
presence.received(ROW)
|
||||
assert not h.listing()["items"]
|
||||
for now[0] in (100, 102, 119):
|
||||
presence.expire(ROW)
|
||||
presence.received(ROW)
|
||||
presence.received(ROW)
|
||||
now[0] = 150
|
||||
presence.received(ROW) # Race: heartbeat before the expiry worker.
|
||||
assert [i["at"] for i in h.listing(ascending=True)["items"]] == [200, 219, 239, 250]
|
||||
reopened = BoardPresence(h)
|
||||
reopened.expire(ROW)
|
||||
assert len(h.listing()["items"]) == 4
|
||||
|
||||
|
||||
def test_power_ack_only_and_switches_and_bounded_replay(tmp_path):
|
||||
history = NotificationHistory(tmp_path)
|
||||
power = BoardPower()
|
||||
power.notifications = history
|
||||
epoch, ident = "a" * 43, "00000000-0000-4000-8000-000000000000"
|
||||
data = dict(schema=SCHEMA, epoch=epoch, available=True)
|
||||
power.heartbeat(ROW, {"power": data})
|
||||
power.start(ROW, epoch, ident)
|
||||
assert not history.listing()["items"]
|
||||
for _ in range(6):
|
||||
power.heartbeat(ROW, {"power": {**data, "result": {"id": ident, "state": "accepted"}}})
|
||||
history.configure("frames.loss", False)
|
||||
data = [
|
||||
{
|
||||
"id": str(n) * 43,
|
||||
"at": 150,
|
||||
"kind": kind,
|
||||
**(
|
||||
{"device": "instax4_" + "f" * 32} if kind.startswith(("frames.", "camera.")) else {}
|
||||
),
|
||||
}
|
||||
for n, kind in enumerate(
|
||||
(
|
||||
"board.boot",
|
||||
"camera.loss",
|
||||
"frames.loss",
|
||||
"frames.recovery",
|
||||
"camera.recovery",
|
||||
"thermal.loss",
|
||||
"thermal.recovery",
|
||||
)
|
||||
)
|
||||
]
|
||||
for _ in range(3):
|
||||
assert accept_operator_events(history, ROW, data)["operator_events_ack"] == data[-1]["id"]
|
||||
assert len(history.listing()["items"]) == 7
|
||||
assert "frames.loss" in {i["key"] for i in history.preferences() if not i["enabled"]}
|
||||
assert not accept_operator_events(history, ROW, [{**data[1], "device": "forged"}])
|
||||
assert not accept_operator_events(history, ROW, [{**data[0], "kind": "board.lost"}])
|
||||
|
||||
|
||||
def test_authority_stop_and_new_ready_without_driver_commands(hub, tmp_path): # noqa: F811
|
||||
control, clock = hub
|
||||
history = NotificationHistory(tmp_path)
|
||||
session = arm(control)
|
||||
# Keep the operator lease alive past the telemetry deadline.
|
||||
for n in range(2, 15):
|
||||
clock[0] += 0.085
|
||||
control.command("node", cmd(session, n))
|
||||
control.stream("node", "a" * 32)
|
||||
for _ in range(3):
|
||||
publish_control(history, ROW, control)
|
||||
items = history.listing()["items"]
|
||||
assert len(items) == 1 and "1000 мс" in items[0]["description"]
|
||||
driver = {"kind": "control.stop", "session": session, "id": "a" * 43, "at": 150}
|
||||
for _ in range(3):
|
||||
assert accept_operator_events(history, ROW, [driver])["operator_events_ack"] == driver["id"]
|
||||
assert len(history.listing()["items"]) == 1
|
||||
exchange(control)
|
||||
second = arm(control)
|
||||
exchange(control, state="ready", session_id=second)
|
||||
exchange(control, state="ready", session_id=second)
|
||||
control.command("node", cmd(second, 3, stop=True))
|
||||
publish_control(history, ROW, control)
|
||||
assert len(history.listing()["items"]) == 2
|
||||
assert "готовность" in history.listing()["items"][0]["description"]
|
||||
|
||||
|
||||
def test_paired_heartbeat_and_liveness_emit_without_core_requests(setup):
|
||||
fleet, _, _, requests = setup
|
||||
public, _ = create(setup)
|
||||
fleet.advance(public["id"])
|
||||
row = fleet.find(public["id"])
|
||||
leaf, body = cert(row), heartbeat(row)
|
||||
requests.clear()
|
||||
now = [100.0]
|
||||
fleet.board_presence = BoardPresence(fleet.notifications, lambda: now[0], lambda: now[0])
|
||||
event = {"id": "h" * 43, "kind": "thermal.loss", "at": 100}
|
||||
for _ in range(3):
|
||||
status, reply = fleet.receive(
|
||||
leaf, "/v1/node/heartbeat", {**body, "operator_events_v1": [event]}
|
||||
)
|
||||
assert status == 200 and reply["operator_events_ack"] == event["id"]
|
||||
now[0] = 122
|
||||
fleet.board_presence.expire(row)
|
||||
live = {k: v for k, v in body.items() if k not in ("host", "devices")}
|
||||
assert fleet.receive(leaf, "/v1/node/liveness", {**live, "binding_id": "invalid"})[0] != 200
|
||||
for _ in range(3):
|
||||
assert fleet.receive(leaf, "/v1/node/liveness", live)[0] == 200
|
||||
items = fleet.notifications.listing(ascending=True)["items"]
|
||||
assert [r["description"] for r in items] == [
|
||||
"Ядро включило тепловое ограничение процессора.",
|
||||
"Борт перестал выходить на связь.",
|
||||
"Связь восстановлена.",
|
||||
]
|
||||
assert requests == []
|
||||
@@ -364,6 +364,29 @@ def test_client_controls_round_trip_with_exact_sim_and_guards(action):
|
||||
assert fleet.routers.heartbeat(fleet.row, {})["router_commands"] == [request]
|
||||
|
||||
|
||||
def test_policy_notification_uses_confirmed_heartbeat_and_keeps_timeout_identity(tmp_path):
|
||||
from k1link.fleet.router_notifications import publish_router_results
|
||||
from k1link.notifications import NotificationHistory
|
||||
|
||||
fleet, state, request = ready_client_control()
|
||||
fleet.row['name'] = 'Test rover'
|
||||
history = NotificationHistory(tmp_path)
|
||||
receipt = fleet.routers.control(fleet, 'vehicle', request)
|
||||
entry = fleet.routers.pending[('vehicle', request['operation_id'])]
|
||||
entry['deadline'] = time.time() - 1
|
||||
fleet.routers.prune()
|
||||
publish_router_results(history, fleet.row, fleet.routers.pending)
|
||||
assert history.listing()['items'][0]['tone'] == 'warning'
|
||||
assert entry['public']['action'] == 'policy'
|
||||
state['results'] = [{**receipt, 'state': 'complete', 'at': int(time.time())}]
|
||||
fleet.routers.heartbeat(fleet.row, {'routers': state})
|
||||
publish_router_results(history, fleet.row, fleet.routers.pending)
|
||||
assert history.listing()['items'][0]['tone'] == 'success'
|
||||
fleet.routers.heartbeat(fleet.row, {'routers': state})
|
||||
publish_router_results(history, fleet.row, fleet.routers.pending)
|
||||
assert len(history.listing()['items']) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"change",
|
||||
[
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
from k1link.notifications import NotificationHistory
|
||||
|
||||
|
||||
def test_manual_rollback_message_names_failed_and_restored_channels(tmp_path):
|
||||
history = NotificationHistory(tmp_path)
|
||||
for i, (source, target, name) in enumerate([
|
||||
('ethernet', 'wifi', 'Wi-Fi'), ('wifi', 'ethernet', 'Ethernet')]):
|
||||
event = dict(id=f'{i:032x}', kind='manual_rollback', source=source, target=target, at=1000)
|
||||
history.uplink({'node_id': str(i), 'name': 'Rover'}, [event])
|
||||
message = history.listing()['items'][0]['description']
|
||||
assert f'Восстановлено подключение по {name}.' in message
|
||||
|
||||
|
||||
def test_history_read_dismiss_separation_and_repeated_node_event(tmp_path):
|
||||
history=NotificationHistory(tmp_path)
|
||||
row={'node_id':'board','name':'Test rover'}
|
||||
event=dict(id='a'*32,kind='fallback',source='ethernet',target='wifi',at=1000)
|
||||
history.uplink(row,[event])
|
||||
history.uplink(row,[event])
|
||||
page=history.listing()
|
||||
assert len(page['items'])==1 and page['unread']==1
|
||||
assert 'Wi-Fi' in page['items'][0]['description']
|
||||
history.read(page['latest'])
|
||||
assert history.listing()['unread']==0
|
||||
# Restart replays the bounded board receipt without another notification.
|
||||
history=NotificationHistory(tmp_path)
|
||||
history.uplink(row,[event])
|
||||
assert len(history.listing()['items'])==1
|
||||
|
||||
|
||||
def test_ui_retries_and_pagination_are_idempotent(tmp_path):
|
||||
history=NotificationHistory(tmp_path)
|
||||
for i in range(105):
|
||||
history.add('ui:'+str(i),'error','Error',str(i))
|
||||
history.add('ui:104','error','Error','104')
|
||||
newest=history.listing()
|
||||
assert len(newest['items'])==100 and newest['latest']==105
|
||||
older=history.listing(before=newest['items'][-1]['sequence'])
|
||||
assert len(older['items'])==5
|
||||
assert len(history.listing(after=103)['items'])==2
|
||||
|
||||
|
||||
|
||||
def test_history_api_requires_local_origin_and_bounds_cursors(tmp_path):
|
||||
from types import SimpleNamespace
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from k1link.web.notifications_api import router
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router)
|
||||
app.state.fleet = SimpleNamespace(notifications=NotificationHistory(tmp_path))
|
||||
with TestClient(app, base_url='http://127.0.0.1', client=('127.0.0.1', 12345)) as client:
|
||||
path = '/api/v1/notifications'
|
||||
message = dict(identity='ui:'+'a'*36, tone='success', title='Saved')
|
||||
rejected = client.post(path, json=message,
|
||||
headers={'Origin':'https://other.invalid'})
|
||||
assert rejected.status_code == 403
|
||||
assert client.get(path+'?after=999999999999999999999').status_code == 422
|
||||
assert client.post(path, json={**message, 'tone':'loading'}).status_code == 422
|
||||
assert client.post(path, json=message).status_code == 200
|
||||
page = client.get(path)
|
||||
assert page.headers['cache-control'] == 'no-store'
|
||||
assert len(page.json()['items']) == 1
|
||||
assert client.post(path+'/read', json={'through':page.json()['latest']}).status_code == 200
|
||||
assert client.get(path).json()['unread'] == 0
|
||||
@@ -0,0 +1,100 @@
|
||||
import asyncio
|
||||
|
||||
from k1link.fleet.node_operator_events import accept_operator_events
|
||||
from k1link.notifications import NotificationHistory
|
||||
|
||||
|
||||
def test_only_committed_board_transitions_wake_stream_and_disabled_receipts_stay_muted(tmp_path):
|
||||
row = dict(name="Rover", binding={"binding_id": "test"})
|
||||
history = NotificationHistory(tmp_path)
|
||||
loss = dict(kind="telemetry.loss", id="a" * 43, at=120)
|
||||
restored = dict(kind="telemetry.recovery", id="b" * 43, at=130)
|
||||
assert not accept_operator_events(history, row, [loss, {**restored, "at": -1}])
|
||||
|
||||
async def simulation():
|
||||
with history.subscribe() as signal:
|
||||
assert accept_operator_events(history, row, [loss]) == {
|
||||
"operator_events_ack": loss["id"]
|
||||
}
|
||||
await asyncio.wait_for(signal.wait(), 1)
|
||||
signal.clear()
|
||||
accept_operator_events(history, row, [loss])
|
||||
history.configure("telemetry.recovery", False)
|
||||
assert accept_operator_events(history, row, [restored]) == {
|
||||
"operator_events_ack": restored["id"]
|
||||
}
|
||||
await asyncio.sleep(0)
|
||||
assert not signal.is_set()
|
||||
|
||||
asyncio.run(simulation())
|
||||
reopened = NotificationHistory(tmp_path)
|
||||
assert not next(
|
||||
i["enabled"] for i in reopened.preferences() if i["key"] == "telemetry.recovery"
|
||||
)
|
||||
reopened.configure("telemetry.recovery", True)
|
||||
accept_operator_events(reopened, row, [restored])
|
||||
page = reopened.listing(after=0, ascending=True)
|
||||
assert [item["at"] for item in page["items"]] == [120]
|
||||
assert page["unread"] == 1
|
||||
|
||||
|
||||
def test_router_journal_baseline_replay_and_confirmed_mode(tmp_path):
|
||||
from k1link.fleet.router_notifications import publish_router_incidents
|
||||
|
||||
history = NotificationHistory(tmp_path)
|
||||
history.configure("router.mode", True)
|
||||
row = dict(name="Board", node_id="n", binding={"binding_id": "b"})
|
||||
|
||||
def journal(seq):
|
||||
return dict(
|
||||
binding="b",
|
||||
state=dict(
|
||||
journal={"last_sequence": seq},
|
||||
events=[
|
||||
dict(
|
||||
sequence=seq,
|
||||
boot_id="1" * 32,
|
||||
code="mode_changed",
|
||||
at=240,
|
||||
slot=0,
|
||||
before="direct",
|
||||
after="aggregation",
|
||||
)
|
||||
],
|
||||
),
|
||||
)
|
||||
|
||||
publish_router_incidents(history, row, journal(7))
|
||||
assert not history.listing()["items"]
|
||||
publish_router_incidents(history, row, journal(8))
|
||||
publish_router_incidents(NotificationHistory(tmp_path), row, journal(8))
|
||||
assert [i["description"] for i in history.listing()["items"]] == ["Одна SIM-карта → Агрегация"]
|
||||
|
||||
|
||||
def test_browser_stream_waits_for_commit_and_resumes_after_cursor(tmp_path):
|
||||
from types import SimpleNamespace
|
||||
|
||||
from starlette.requests import Request
|
||||
|
||||
from k1link.web.notifications_api import events
|
||||
|
||||
async def run():
|
||||
history = NotificationHistory(tmp_path)
|
||||
fleet = SimpleNamespace(notifications=history)
|
||||
history.publish("telemetry.loss", "first", "warning", "Первое", "")
|
||||
request = Request({"type": "http", "headers": [(b"last-event-id", b"1")]})
|
||||
stream = (await events(request, fleet, after=0)).body_iterator
|
||||
try:
|
||||
assert (await anext(stream)).startswith("retry:")
|
||||
assert '"items": []' in await anext(stream)
|
||||
waiting = asyncio.create_task(anext(stream))
|
||||
await asyncio.sleep(0.03)
|
||||
assert not waiting.done()
|
||||
history.publish("telemetry.recovery", "second", "success", "Второе", "")
|
||||
frame = await asyncio.wait_for(waiting, 1)
|
||||
assert "id: 2" in frame and "Второе" in frame and "Первое" not in frame
|
||||
finally:
|
||||
await stream.aclose()
|
||||
assert not history.subscribers
|
||||
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,43 @@
|
||||
from k1link.fleet.router_notifications import publish_router_results
|
||||
from k1link.notifications import NotificationHistory
|
||||
|
||||
|
||||
def test_outcome_is_durable_once_and_independent_of_open_windows(tmp_path):
|
||||
history = NotificationHistory(tmp_path)
|
||||
row = dict(id='rover', node_id='node', name='Test', binding={'binding_id': 'bound'})
|
||||
entry = dict(binding='bound', public=dict(operation_id='one', action='policy', state='queued'))
|
||||
pending = {('rover', 'one'): entry}
|
||||
for state in ['queued', 'applying']:
|
||||
entry['public']['state'] = state
|
||||
publish_router_results(history, row, pending)
|
||||
assert history.listing()['items'] == []
|
||||
entry['public'].update(state='error', error='router_busy')
|
||||
publish_router_results(history, row, pending)
|
||||
publish_router_results(history, row, pending)
|
||||
messages = history.listing()['items']
|
||||
assert len(messages) == 1 and messages[0]['tone'] == 'error'
|
||||
assert 'занят' in messages[0]['description']
|
||||
del entry['notified_state']
|
||||
publish_router_results(NotificationHistory(tmp_path), row, pending)
|
||||
assert len(history.listing()['items']) == 1
|
||||
|
||||
|
||||
def test_scope_is_operator_policy_and_late_confirmation_updates_uncertainty(tmp_path):
|
||||
history = NotificationHistory(tmp_path)
|
||||
history.configure('router.applied', True)
|
||||
row = dict(id='rover', node_id='node', name='Test', binding={'binding_id': 'bound'})
|
||||
entry = dict(binding='bound', public=dict(operation_id='one', action='policy', state='unknown'))
|
||||
pending = {
|
||||
('other', 'one'): entry.copy(),
|
||||
('rover', 'old'): {**entry, 'binding': 'old'},
|
||||
('rover', 'inspect'): {**entry, 'public': {'action': 'inspect', 'state': 'complete'}},
|
||||
('rover', 'one'): entry,
|
||||
}
|
||||
publish_router_results(history, row, pending)
|
||||
assert len(history.listing()['items']) == 1
|
||||
assert history.listing()['items'][0]['tone'] == 'warning'
|
||||
entry['public']['state'] = 'complete'
|
||||
publish_router_results(history, row, pending)
|
||||
messages = history.listing()['items']
|
||||
assert len(messages) == 2 and messages[0]['tone'] == 'success'
|
||||
assert 'Фактический канал' in messages[0]['description']
|
||||
Reference in New Issue
Block a user