Keep B2 client fixes and move VPS implementation to its standalone repository

This commit is contained in:
DCCONSTRUCTIONS
2026-09-29 12:41:21 +03:00
parent 03d44d0fb1
commit 6dd652f71e
85 changed files with 2201 additions and 9299 deletions
@@ -1,4 +1,4 @@
"""B2 231/0.01 configuration HTTP payloads, observed 2026-09-26.
"""B2 231/0.01 and 0.06 configuration HTTP payloads, observed 2026-09-26/28.
The HTTP transport is separate from INTERNAL. Unknown commands and firmware
fail closed. Parsing upload evidence is not proof that a write was applied.
@@ -7,7 +7,9 @@ fail closed. Parsing upload evidence is not proof that a write was applied.
from .usb_protocol import Configuration, ProtocolError, decode_configuration
MAX_BODY = 16384
QUALIFIED_METADATA = bytes.fromhex("0001e7020000")
QUALIFIED_METADATA = frozenset(
bytes.fromhex(value) for value in ("0001e7020000", "0006e7020000")
)
def decode_request(raw: bytes, *, observe_empty_check: bool = False) -> tuple[str, int, bytes]:
@@ -16,7 +18,7 @@ def decode_request(raw: bytes, *, observe_empty_check: bool = False) -> tuple[st
or raw[:2] != b"[\x01"
or raw[-1:] != b"]"
or int.from_bytes(raw[2:4], "big") != len(raw) - 5
or raw[12:18] != QUALIFIED_METADATA
or raw[12:18] not in QUALIFIED_METADATA
):
raise ProtocolError("unsupported_web_request")
imei = str(int.from_bytes(raw[4:12], "little"))
+2 -2
View File
@@ -8,7 +8,7 @@ KINDS = {"request-position", "pulse-output", "set-output", "restart"}
def plan(equipment: EquipmentStore, row: Document, command: Document) -> Document:
if row["model_id"] != "arnavi-b2" or row["observed"]["firmware"] != "0.01":
if row["model_id"] != "arnavi-b2" or row["observed"]["firmware"] not in ("0.01", "0.06"):
raise EquipmentError("Команды для этой версии устройства не проверены.")
kind = command.get("kind")
if kind not in KINDS:
@@ -41,6 +41,6 @@ def plan(equipment: EquipmentStore, row: Document, command: Document) -> Documen
**private,
"imei": row["identity_key"],
"model": 231,
"firmware": "0.01",
"firmware": row["observed"]["firmware"],
"secondary": {"host": config.text(3), "port": config.integer(4, 2)},
}
+5
View File
@@ -58,6 +58,11 @@ def apply(hosts, identifier, revision):
"0.1.39",
"0.1.40",
"0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
)
or time.time() - host["last_sync_at"] > 30
):
@@ -34,7 +34,7 @@ def presets() -> list[Document]:
"command": {"kind": "set-output", "pin": pin, "enabled": enabled},
"wire": f"••••••*SERV*8.{pin}.{int(enabled)}",
"encoding": "INTERNAL · FC",
"queue_seconds": 3,
"queue_seconds": 30,
"confirmation": "Текстовая команда без токена. "
"Ответ не доказывает положение контактов реле.",
}
@@ -46,7 +46,7 @@ def presets() -> list[Document]:
"command": {"kind": "pulse-output", "pin": pin, "seconds": 5},
"wire": f"••••••*SERV*24.{pin}.0.5",
"encoding": "INTERNAL · FC",
"queue_seconds": 3,
"queue_seconds": 30,
"confirmation": "Текстовая команда без токена. "
"Ответ не доказывает положение контактов реле.",
}
@@ -0,0 +1,149 @@
"""Independent durable command jobs; settings revisions do not own their queue."""
import http.client
import json
import time
from . import equipment_actions, equipment_operations
from . import equipment_command_journal as journal
from .independent_equipment import EquipmentError
from .vps_transport import request
CAPABILITY = "arnavi-b2-command-scheduler-v2"
def supported(host):
return CAPABILITY in (host or {}).get("status", {}).get("capabilities", [])
def initialize(db):
db.execute(
"CREATE TABLE IF NOT EXISTS command_dispatch("
"id TEXT PRIMARY KEY,body TEXT NOT NULL,accepted INTEGER NOT NULL DEFAULT 0,"
"next_poll REAL NOT NULL DEFAULT 0)"
)
def prepare(hosts, identifier, value):
from .equipment_command_runtime import guard, source
with hosts.equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
current = json.loads(
db.execute("SELECT body FROM command_journal WHERE id=?", (value["id"],)).fetchone()[0]
)
if current["state"] != "waiting":
return
row = hosts.equipment._find(db, "instances", identifier)
if guard(row) != current["guard"]:
journal.finish(db, identifier, current, "rejected", "device_changed")
return
host = source(hosts, row)
if not host or host["id"] != current["host_id"] or not supported(host):
return
try:
body = equipment_actions.plan(hosts.equipment, row, current["command"])
except EquipmentError:
journal.finish(db, identifier, current, "rejected", "device_changed")
return
body.pop("secondary")
body.update(id=value["id"], priority="manual")
db.execute(
"INSERT INTO command_dispatch(id,body) VALUES(?,?)", (value["id"], json.dumps(body))
)
current.update(state="submitting", runtime_phase="reconciling")
journal.capture(db, {**row, "network_operation": current})
def project(hosts, identifier, value, result):
if (
result.get("id") != value["id"]
or result.get("kind") != value["kind"]
or result.get("durable") is not True
):
raise ValueError("durable command identity mismatch")
allowed_states = {
"queued",
"dispatched",
"delivered",
"device_confirmed",
"device_rejected",
"reconnected",
"accepted",
"unconfirmed",
"uncertain",
"rejected",
"stopped",
}
if result.get("state") not in allowed_states:
raise ValueError("invalid durable command outcome")
if result["state"] == "delivered" and (
value["kind"] not in {"set-output", "pulse-output"}
or type(result.get("delivered_at")) not in (int, float)
):
raise ValueError("output transport receipt missing")
with hosts.equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
row = hosts.equipment._find(db, "instances", identifier)
current = json.loads(
db.execute("SELECT body FROM command_journal WHERE id=?", (value["id"],)).fetchone()[0]
)
if current["state"] not in journal.PENDING:
return
equipment_operations.project(current, result)
current.update(
{
k: v
for k, v in result.items()
if k in journal.FIELDS and k not in {"created_at", "command", "host_id", "scope"}
}
)
current["vps_created_at"] = result.get("created_at", current["created_at"])
journal.capture(db, {**row, "network_operation": current})
if current["state"] not in journal.PENDING:
db.execute("DELETE FROM command_dispatch WHERE id=?", (value["id"],))
else:
db.execute("UPDATE command_dispatch SET accepted=1 WHERE id=?", (value["id"],))
def pump(hosts):
# Bounded batches, persisted rows: backlog size does not become RAM usage.
with hosts.equipment.db() as db:
waiting = db.execute(
"SELECT instance,body FROM command_journal WHERE state='waiting' "
"AND json_extract(body,'$.detached')=1 ORDER BY seq LIMIT 16"
).fetchall()
for identifier, encoded in waiting:
prepare(hosts, identifier, json.loads(encoded))
with hosts.equipment.db() as db:
jobs = db.execute(
"SELECT j.instance,j.body,d.body,d.accepted FROM command_dispatch d "
"JOIN command_journal j ON j.id=d.id WHERE d.next_poll<=? "
"AND j.state IN ('submitting','queued','dispatched') "
"ORDER BY d.next_poll,j.seq LIMIT 8",
(time.time(),),
).fetchall()
owners = {h["id"]: h for h in hosts.rows() if h["state"] == "paired"}
for identifier, encoded, body, accepted in jobs:
value = json.loads(encoded)
with hosts.equipment.db() as db:
db.execute(
"UPDATE command_dispatch SET next_poll=? WHERE id=?", (time.time() + 2, value["id"])
)
host = owners.get(value["host_id"])
if not host or not supported(host):
continue
try:
if value.get("stop_requested"):
result = request(
host, "POST", f"/v1/operations/{value['id']}/cancel", {"kind": value["kind"]}
)
elif accepted:
result = request(host, "GET", f"/v1/operations/{value['id']}")
else:
result = request(host, "POST", "/v1/operations", json.loads(body))
project(hosts, identifier, value, result)
except (OSError, ValueError, http.client.HTTPException):
# The same persisted ID and body survive both outage and lost reply.
# An unknown HTTP outcome never authorizes a fresh tracker command.
continue
+12 -2
View File
@@ -41,10 +41,16 @@ FIELDS = {
"recovery_at",
"recovery_count",
"recovery_verification",
"delivered_at",
"delivery_seconds",
"reason",
}
def initialize(db):
from .equipment_command_dispatch import initialize as initialize_dispatch
initialize_dispatch(db)
db.executescript("""
CREATE TABLE IF NOT EXISTS command_journal(seq INTEGER PRIMARY KEY AUTOINCREMENT,
id TEXT UNIQUE NOT NULL, instance TEXT NOT NULL,
@@ -159,7 +165,11 @@ def finish(db, instance, value, state, reason):
def public(value):
return {k: v for k, v in value.items() if k not in {"guard", "digest", "preset_id"}}
return {
k: v
for k, v in value.items()
if k not in {"guard", "digest", "preset_id", "network_intent", "detached"}
}
def listing(equipment, identifier, before=None, limit=25, tracked=()):
@@ -185,7 +195,7 @@ def listing(equipment, identifier, before=None, limit=25, tracked=()):
"(state IN ('waiting','submitting','queued','dispatched') "
"OR id IN (SELECT id FROM command_result_probes WHERE instance=? "
"ORDER BY rowid DESC LIMIT 32) "
f"OR id IN ({placeholders})) ORDER BY seq DESC",
f"OR id IN ({placeholders})) ORDER BY seq DESC LIMIT 64",
(identifier, identifier, *tracked),
).fetchall()
return {
@@ -0,0 +1,120 @@
"""An explicit repeat creates a new intent; an HTTP retry keeps that intent's ID."""
import hashlib
import json
import re
import time
from . import equipment_command_journal as journal
from .equipment_command_catalog import presets
from .equipment_command_runtime import CAPACITY, enqueue, guard, source
from .equipment_network import plan
from .equipment_operations import supported
from .independent_equipment import EquipmentError
def fingerprint(equipment, row, intent):
body = plan(equipment, row, intent["read_only"], True, select_sim=intent["select_sim"])
return hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
def repeat(hosts, identifier, original_id, request_id):
if not re.fullmatch(r"[a-f0-9]{32}", request_id):
raise EquipmentError("Некорректный идентификатор запроса.")
equipment = hosts.equipment
with equipment.db() as db:
found = db.execute(
"SELECT body FROM command_journal WHERE instance=? AND id=?",
(identifier, original_id),
).fetchone()
if not found:
raise EquipmentError("Операция не найдена.")
original = json.loads(found[0])
if original["state"] in journal.PENDING:
raise EquipmentError("Дождитесь завершения этой операции.")
preset = next((p for p in presets() if p["command"] == original.get("command")), None)
if preset:
# Revalidate firmware/output mode and use a new original deadline.
return enqueue(hosts, identifier, request_id, preset["id"])
if original["kind"] not in {"read-configuration", "configure-all", "select-sim"}:
raise EquipmentError("Для этой старой операции не сохранились параметры повтора.")
digest = hashlib.sha256(f"{identifier}:repeat:{original_id}".encode()).hexdigest()
with equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
old = db.execute("SELECT body FROM command_journal WHERE id=?", (request_id,)).fetchone()
if old:
value = json.loads(old[0])
if value.get("digest") != digest:
raise EquipmentError("Этот ID уже принадлежит другой команде.")
return journal.public(value)
row = equipment._find(db, "instances", identifier)
host = source(hosts, row)
if (
not host
or host["id"] != original.get("host_id")
or not supported(host, original["kind"])
):
raise EquipmentError("Изменилась привязка VPS или версия устройства.")
previous_row = row if row.get("network_operation", {}).get("id") == original_id else None
if previous_row is None:
saved = db.execute(
"SELECT body FROM history WHERE instance_id=? AND "
"json_extract(body,'$.network_operation.id')=? ORDER BY revision DESC LIMIT 1",
(identifier, original_id),
).fetchone()
previous_row = json.loads(saved[0]) if saved else None
if not previous_row or guard(previous_row) != guard(row):
raise EquipmentError("Устройство или параметры этой старой операции изменились.")
previous = previous_row["network_operation"]
intent = {
"read_only": original["kind"] == "read-configuration",
"select_sim": original["kind"] == "select-sim",
}
current = plan(equipment, row, intent["read_only"], True, select_sim=intent["select_sim"])
# Repeat precisely the reviewed configuration, with a newly read baseline.
# The outbox is deleted on acknowledgement; immutable revision history
# retains the target digest without copying private wire data into the UI.
if not intent["read_only"]:
digest_now = hashlib.sha256(bytes.fromhex(current["target_configuration"])).hexdigest()
if digest_now != previous.get("target_configuration_sha256") or any(
current.get(key) != previous.get(key) for key in ("kind", "sim_slot", "sim_policy")
):
raise EquipmentError(
"Настройки изменились. Откройте настройки устройства "
"и примените нужные значения."
)
if previous.get("automatic_card") or row["settings"]["connectivity"].get("automatic"):
raise EquipmentError(
"Повторите выбор SIM в настройках, чтобы проверить установленную карту."
)
count = db.execute(
"SELECT count(*) FROM command_journal WHERE instance=? "
"AND state IN ('waiting','submitting','queued','dispatched')",
(identifier,),
).fetchone()[0]
if count >= CAPACITY:
raise EquipmentError(
"Очередь устройства заполнена (32 операции). Дождитесь завершения."
)
now = time.time()
intent["fingerprint"] = fingerprint(equipment, row, intent)
value = {
"id": request_id,
"digest": digest,
"repeat_of": original_id,
"host_id": host["id"],
"guard": guard(row),
"firmware": row["observed"]["firmware"],
"command": None,
"kind": original["kind"],
"scope": original["scope"],
"description": original["description"],
"network_intent": intent,
"durable": True,
"state": "waiting",
"created_at": now,
"events": [{"state": "waiting", "observed_at": now, "historical": False}],
}
journal.put(db, identifier, value)
hosts.command_wake.set()
return journal.public(value)
+42 -5
View File
@@ -5,8 +5,8 @@ import json
import re
import time
from . import equipment_command_dispatch, equipment_operations
from . import equipment_command_journal as journal
from . import equipment_operations
from .equipment_command_catalog import catalog
from .independent_equipment import EquipmentError
@@ -73,6 +73,11 @@ def enqueue(hosts, identifier, request_id, preset_id):
"0.1.39",
"0.1.40",
"0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
}:
raise EquipmentError("Подключите проверенную версию VPS Host с поддержкой очереди.")
count = db.execute(
@@ -80,7 +85,7 @@ def enqueue(hosts, identifier, request_id, preset_id):
"('waiting','submitting','queued','dispatched')",
(identifier,),
).fetchone()[0]
if count >= CAPACITY:
if count >= CAPACITY and not equipment_command_dispatch.supported(host):
raise EquipmentError(
"Очередь устройства заполнена (32 операции). Дождитесь завершения."
)
@@ -101,13 +106,22 @@ def enqueue(hosts, identifier, request_id, preset_id):
"scope": "command",
"created_at": now,
"queue_deadline": now + selected["queue_seconds"],
"expires_at": now + (180 if preset_id == "restart" else 30),
"expires_at": now
+ (
180
if preset_id == "restart"
else 60
if selected["command"]["kind"] in {"set-output", "pulse-output"}
else 30
),
"events": [{"state": "waiting", "observed_at": now, "historical": False}],
}
if equipment_operations.supported(host, value["kind"]):
value["durable"] = True
value.pop("queue_deadline")
value.pop("expires_at")
if equipment_command_dispatch.supported(host):
value["detached"] = True
journal.put(db, identifier, value)
hosts.command_wake.set()
return journal.public(value)
@@ -124,6 +138,12 @@ def cancel(equipment, identifier, request_id, hosts=None):
value = json.loads(found[0])
if value["state"] == "cancelled":
return journal.public(value)
if value.get("detached") and value["state"] in {"submitting", "queued", "dispatched"}:
value["stop_requested"] = True
journal.put(db, identifier, value)
if hosts is not None:
hosts.command_wake.set()
return journal.public(value)
if value.get("durable") and value["state"] in {"submitting", "queued", "dispatched"}:
row = equipment._find(db, "instances", identifier)
op = row.get("network_operation", {})
@@ -144,10 +164,12 @@ def cancel(equipment, identifier, request_id, hosts=None):
def pump(hosts):
from .equipment_network import PENDING, start
equipment_command_dispatch.pump(hosts)
equipment = hosts.equipment
with equipment.db() as db:
rows = db.execute(
"SELECT instance,body FROM command_journal WHERE state='waiting' ORDER BY seq"
"SELECT instance,body FROM command_journal WHERE state='waiting' "
"AND coalesce(json_extract(body,'$.detached'),0)=0 ORDER BY seq LIMIT 64"
).fetchall()
visited = set()
for identifier, body in rows:
@@ -168,6 +190,12 @@ def pump(hosts):
if guard(row) != value["guard"]:
journal.finish(db, identifier, value, "rejected", "device_changed")
continue
if intent := value.get("network_intent"):
from .equipment_command_repeat import fingerprint
if fingerprint(equipment, row, intent) != intent["fingerprint"]:
journal.finish(db, identifier, value, "rejected", "settings_changed")
continue
if identifier in visited:
continue
visited.add(identifier)
@@ -181,7 +209,16 @@ def pump(hosts):
if time.time() - (host.get("last_sync_at") or 0) > 30:
continue
try:
start(hosts, identifier, row["revision"], command=value["command"], queued_job=value)
intent = value.get("network_intent", {})
start(
hosts,
identifier,
row["revision"],
read_only=intent.get("read_only", False),
select_sim=intent.get("select_sim", False),
command=value["command"],
queued_job=value,
)
except EquipmentError:
# A concurrent config/USB change or an expired/cancelled intent is
# re-evaluated on the next tick; never manufacture a new ID.
+66 -4
View File
@@ -24,6 +24,7 @@ if TYPE_CHECKING:
PENDING = {"submitting", "queued", "dispatched"}
TERMINAL = {
"delivered",
"verified",
"observed",
"rejected",
@@ -54,7 +55,7 @@ def plan(
select_sim: bool = False,
automatic_access: Document | None = None,
) -> Document:
if row["model_id"] != "arnavi-b2" or row["observed"]["firmware"] != "0.01":
if row["model_id"] != "arnavi-b2" or row["observed"]["firmware"] not in ("0.01", "0.06"):
raise EquipmentError("Сетевая запись для этой модели или версии ПО не проверена.")
config = decode_configuration(
(equipment.root / "evidence" / row["evidence_id"] / "configuration.bin").read_bytes()
@@ -65,7 +66,7 @@ def plan(
body = {
"kind": "read-configuration" if read_only else "configure-all",
"model": 231,
"firmware": "0.01",
"firmware": row["observed"]["firmware"],
"imei": row["identity_key"],
"password": config.text(5),
"secondary": {"host": config.text(3), "port": config.integer(4, 2)},
@@ -137,7 +138,7 @@ def plan(
return {
"kind": "configure-server1",
"model": 231,
"firmware": "0.01",
"firmware": row["observed"]["firmware"],
"imei": row["identity_key"],
"password": config.text(5),
"expected": {"host": config.text(1), "port": config.integer(2, 2)},
@@ -185,6 +186,11 @@ def start(
or queued_job["command"] != command
):
raise EquipmentError("Операция отменена, просрочена или устройство изменилось.")
if intent := queued_job.get("network_intent"):
from .equipment_command_repeat import fingerprint
if fingerprint(equipment, row, intent) != intent["fingerprint"]:
raise EquipmentError("Настройки изменились после запроса повтора.")
if (
queued_job is None
and previous.get("requested_revision") == revision
@@ -238,6 +244,11 @@ def start(
"0.1.39",
"0.1.40",
"0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
)
)
automatic_access = None
@@ -303,7 +314,18 @@ def start(
assert body is not None
if body.get("sim_policy") == "both" and source.get("status", {}).get(
"version"
) not in {"0.1.37", "0.1.38", "0.1.39", "0.1.40", "0.1.41"}:
) not in {
"0.1.37",
"0.1.38",
"0.1.39",
"0.1.40",
"0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
}:
raise EquipmentError("Для разрешения обеих SIM установите актуальный VPS Host.")
if body["kind"] == "select-sim" and source.get("status", {}).get("version") not in {
"0.1.24",
@@ -324,6 +346,11 @@ def start(
"0.1.39",
"0.1.40",
"0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
}:
raise EquipmentError("Для смены SIM установите актуальный VPS Host.")
else:
@@ -370,6 +397,11 @@ def start(
"0.1.39",
"0.1.40",
"0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
),
"request-position": (
"0.1.8",
@@ -406,6 +438,11 @@ def start(
"0.1.39",
"0.1.40",
"0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
),
"pulse-output": (
"0.1.9",
@@ -441,6 +478,11 @@ def start(
"0.1.39",
"0.1.40",
"0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
),
"set-output": (
"0.1.10",
@@ -475,6 +517,11 @@ def start(
"0.1.39",
"0.1.40",
"0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
),
}
if source.get("status", {}).get("version") not in versions[command["kind"]]:
@@ -519,6 +566,11 @@ def start(
"0.1.39",
"0.1.40",
"0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
)
for h in (source, target)
):
@@ -601,6 +653,11 @@ def start(
"0.1.39",
"0.1.40",
"0.1.41",
"0.1.42",
"0.1.43",
"0.1.44",
"0.1.45",
"0.1.46",
}
if durable_delivery:
lifetime = (
@@ -608,6 +665,8 @@ def start(
if body["kind"] == "select-sim"
else 180
if full or body["kind"] == "restart"
else 60
if body["kind"] in {"set-output", "pulse-output"}
else 30
if command is not None
else 120
@@ -769,6 +828,7 @@ def record(
return
if op.get("scope") == "command":
if result["state"] not in PENDING | {
"delivered",
"device_confirmed",
"device_rejected",
"reconnected",
@@ -799,6 +859,8 @@ def record(
"reconnected_at",
"reconnect_seconds",
"telemetry_measured_at",
"delivered_at",
"delivery_seconds",
):
value = result.get(key)
if type(value) in (int, float) and math.isfinite(value) and value >= 0:
+24 -3
View File
@@ -20,12 +20,24 @@ ATTEMPT_FACTS = {
"stage",
"queue_seconds",
"attempt_expires_at",
"delivered_at",
"delivery_seconds",
}
KINDS = {"request-position", "restart", "read-configuration", "configure-all", "select-sim"}
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", []
)
@@ -61,8 +73,17 @@ def project(op, result):
op["runtime_phase"] = phase
if result.get("stop_requested") is True:
op["stop_requested"] = True
if result.get("reason") == "sim_card_changed":
op["reason"] = "sim_card_changed"
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):
+3
View File
@@ -361,10 +361,13 @@ class VPSHosts:
self.command_wake.wait(1 if pending else 5)
def _runtime_tick(self, next_sync: dict[str, float]) -> bool:
from . import equipment_command_dispatch
from .equipment_command_runtime import pump
from .equipment_network import refresh
with self.lock:
with suppress(OSError, ValueError, KeyError, sqlite3.Error, http.client.HTTPException):
equipment_command_dispatch.pump(self)
for row in self.rows():
if self.stop.is_set():
break
+17 -1
View File
@@ -201,6 +201,7 @@ def command_runtime(
tracked: Annotated[list[str] | None, Query(max_length=32)] = None,
) -> Document:
from k1link.fleet.equipment_command_catalog import catalog
from k1link.fleet.equipment_command_dispatch import supported as scheduler_supported
from k1link.fleet.equipment_command_journal import listing
from k1link.fleet.equipment_command_runtime import source
from k1link.fleet.equipment_operations import KINDS, supported
@@ -215,7 +216,7 @@ def command_runtime(
**listing(equipment, identifier, before, tracked=tracked or ()),
"device": equipment.public(row),
"catalog": catalog(equipment, row),
"capacity": 32,
"capacity": None if scheduler_supported(host) else 32,
"durable_kinds": sorted(k for k in KINDS if supported(host or {}, k)),
}
@@ -244,6 +245,21 @@ def cancel_command(identifier: str, request_id: str, response: Response, fleet:
)
class RepeatCommandRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
request_id: str = Field(pattern=r"^[a-f0-9]{32}$")
@router.post("/instances/{identifier}/commands/{original_id}/repeat")
def repeat_command(
identifier: str, original_id: str, body: RepeatCommandRequest, response: Response, fleet: Fleet
) -> Document:
from k1link.fleet.equipment_command_repeat import repeat
from k1link.web.vps_host_api import store
return action(response, lambda: repeat(store(fleet), identifier, original_id, body.request_id))
@router.get("/instances/{identifier}/commands/{request_id}/attempts")
def command_attempts(
identifier: str,