Files
NODEDC_MISSION_CORE/src/k1link/fleet/equipment_operations.py
T

129 lines
4.0 KiB
Python

"""Core projection of VPS-owned durable tracker maintenance operations."""
import json
import math
ATTEMPT_FACTS = {
"dispatched_at",
"received_at",
"device_accepted_at",
"device_code",
"roundtrip_seconds",
"reconnected_at",
"reconnect_seconds",
"verified_at",
"configuration_received_at",
"write_reply_sent_at",
"active_sim",
"telemetry_measured_at",
"unchanged",
"stage",
"queue_seconds",
"attempt_expires_at",
"delivered_at",
"delivery_seconds",
}
KINDS = {
"request-position",
"restart",
"read-configuration",
"configure-all",
"select-sim",
"set-output",
"pulse-output",
}
def supported(host, kind):
if kind in {"set-output", "pulse-output"}:
return "arnavi-b2-command-scheduler-v2" in host.get("status", {}).get("capabilities", [])
return kind in KINDS and "arnavi-b2-durable-operations-v1" in host.get("status", {}).get(
"capabilities", []
)
def path(op):
return "/v1/operations/" if op.get("durable") else "/v1/commands/"
def project(op, result):
if not op.get("durable"):
return
if result.get("durable") is not True:
raise ValueError("durable operation result missing")
# A new attempt must not inherit an earlier ACK, timing or write stage.
for field in ATTEMPT_FACTS:
op.pop(field, None)
op["reconcile_pending"] = False
for field in ("attempt_count", "next_attempt_at", "attempt_expires_at"):
value = result.get(field)
if type(value) in (int, float) and math.isfinite(value) and value >= 0:
op[field] = value
phase = result.get("runtime_phase")
if phase in {
"waiting-link",
"waiting-identity",
"retry-wait",
"checking-result",
"executing",
"complete",
"stopped",
}:
op["runtime_phase"] = phase
if result.get("stop_requested") is True:
op["stop_requested"] = True
if result.get("reason") in {
"sim_card_changed",
"delivery_deadline",
"connection_closed",
"host_restarted",
"socket_error",
"write_failed",
"expired_before_write",
"pulse_result_unknown",
}:
op["reason"] = result["reason"]
def disconnected(equipment, identifier, operation_id):
with equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
row = equipment._find(db, "instances", identifier)
op = row.get("network_operation", {})
if op.get("id") != operation_id or not op.get("durable") or op.get("reconcile_pending"):
return
op.update(reconcile_pending=True, runtime_phase="reconciling")
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier))
from .equipment_command_journal import capture
capture(db, row)
def attempts(hosts, identifier, request_id, before=None):
"""Only the paired owning host may supply this instance's attempt history."""
from .independent_equipment import EquipmentError
from .vps_transport import request
with hosts.equipment.db() as db:
row = db.execute(
"SELECT body FROM command_journal WHERE instance=? AND id=?",
(identifier, request_id),
).fetchone()
value = json.loads(row[0]) if row else {}
host = next(
(h for h in hosts.rows() if h["id"] == value.get("host_id") and h["state"] == "paired"),
None,
)
if not value.get("durable") or not host:
raise EquipmentError("История попыток этой операции недоступна.")
suffix = f"?before={before}" if before is not None else ""
result = request(host, "GET", f"/v1/operations/{request_id}/attempts{suffix}")
allowed = ATTEMPT_FACTS | {"id", "number", "phase", "state", "observed_at"}
return {
"items": [
{k: v for k, v in item.items() if k in allowed} for item in result.get("items", [])[:20]
],
"next_before": result.get("next_before"),
}