feat(routers): integrate Banana Pi Client API and onboard LibreSpeed measurements
Discover Ethernet routers under the board, map physical SIM slots, expose vendor controls and real telemetry, and provide packaged VPS speed tests with a live monochrome gauge. Enforce compact typography across Core and Node UI.
This commit is contained in:
@@ -0,0 +1,157 @@
|
||||
"""LibreSpeed identity owner. Only configuration is durable; measurements live on Node."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from . import vps_transport
|
||||
from .trust import PairingError
|
||||
|
||||
Document = dict[str, Any]
|
||||
lock = threading.RLock()
|
||||
|
||||
|
||||
def invitation(document: str) -> Document:
|
||||
try:
|
||||
value = json.loads(document)
|
||||
if set(value) != {
|
||||
"schema",
|
||||
"server_id",
|
||||
"endpoint",
|
||||
"fingerprint",
|
||||
"bootstrap",
|
||||
"expires_at",
|
||||
}:
|
||||
raise ValueError
|
||||
if value["schema"] != "missioncore.librespeed-connect/v1":
|
||||
raise ValueError
|
||||
for key, pattern in (
|
||||
("server_id", r"ls_[a-f0-9]{32}"),
|
||||
("fingerprint", r"[a-f0-9]{64}"),
|
||||
("bootstrap", r"[A-Za-z0-9_-]{43}"),
|
||||
):
|
||||
if not isinstance(value[key], str) or not re.fullmatch(pattern, value[key]):
|
||||
raise ValueError
|
||||
if not time.time() < value["expires_at"] <= time.time() + 86500:
|
||||
raise PairingError("Приглашение LibreSpeed просрочено. Скачайте новое с VPS.")
|
||||
vps_transport.destination(value["endpoint"])
|
||||
return dict(value)
|
||||
except (ValueError, TypeError, KeyError):
|
||||
raise PairingError("Файл приглашения LibreSpeed повреждён или просрочен.") from None
|
||||
|
||||
|
||||
class LibreSpeed:
|
||||
def __init__(self, root: Path):
|
||||
self.path = root / "librespeed.sqlite3"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
with self.db() as db:
|
||||
db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS services (id TEXT PRIMARY KEY, body TEXT NOT NULL)"
|
||||
)
|
||||
self.path.chmod(0o600)
|
||||
|
||||
@contextmanager
|
||||
def db(self) -> Iterator[sqlite3.Connection]:
|
||||
connection = sqlite3.connect(self.path)
|
||||
try:
|
||||
with connection:
|
||||
yield connection
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def rows(self) -> list[Document]:
|
||||
with lock, self.db() as db:
|
||||
return [json.loads(r[0]) for r in db.execute("SELECT body FROM services")]
|
||||
|
||||
def listing(self) -> list[Document]:
|
||||
return [
|
||||
{k: r[k] for k in ("id", "endpoint", "state", "fingerprint")}
|
||||
for r in self.rows()
|
||||
if r["state"] == "connected"
|
||||
]
|
||||
|
||||
def save(self, row: Document) -> None:
|
||||
with self.db() as db:
|
||||
db.execute("INSERT OR REPLACE INTO services VALUES (?,?)", (row["id"], json.dumps(row)))
|
||||
|
||||
def find(self, identifier: str) -> Document:
|
||||
row = next(
|
||||
(r for r in self.rows() if r["id"] == identifier and r["state"] == "connected"), None
|
||||
)
|
||||
if not row:
|
||||
raise PairingError("Подключите службу LibreSpeed на VPS.")
|
||||
return row
|
||||
|
||||
def pair(self, document: str, network_interface: str | None = None) -> Document:
|
||||
value = invitation(document)
|
||||
vps_transport.validate_interface(network_interface)
|
||||
with lock:
|
||||
row = next((r for r in self.rows() if r["id"] == value["server_id"]), None)
|
||||
if row and (
|
||||
row["fingerprint"] != value["fingerprint"] or row["endpoint"] != value["endpoint"]
|
||||
):
|
||||
raise PairingError("Идентичность LibreSpeed изменилась.")
|
||||
if row is None:
|
||||
row = {
|
||||
"id": value["server_id"],
|
||||
"endpoint": value["endpoint"],
|
||||
"fingerprint": value["fingerprint"],
|
||||
"token": secrets.token_urlsafe(32),
|
||||
"core_id": "core_" + secrets.token_hex(16),
|
||||
"state": "pending",
|
||||
}
|
||||
row["network_interface"] = network_interface
|
||||
self.save(row) # Retry a lost claim reply using the same controller identity.
|
||||
result = vps_transport.request(
|
||||
row,
|
||||
"POST",
|
||||
"/v1/claim",
|
||||
{
|
||||
"core_id": row["core_id"],
|
||||
"bootstrap": value["bootstrap"],
|
||||
"credential": row["token"],
|
||||
},
|
||||
)
|
||||
if (
|
||||
result.get("server_id") != row["id"]
|
||||
or result.get("schema") != "missioncore.librespeed/v1"
|
||||
):
|
||||
raise PairingError("VPS вернул другую службу.")
|
||||
row["state"] = "connected"
|
||||
self.save(row)
|
||||
return {"id": row["id"], "state": "connected"}
|
||||
|
||||
def forget(self, identifiers: set[str]) -> None:
|
||||
with lock, self.db() as db:
|
||||
db.executemany("DELETE FROM services WHERE id=?", [(i,) for i in identifiers])
|
||||
|
||||
def lease(self, identifier: str, operation: str) -> Document:
|
||||
row = self.find(identifier)
|
||||
result = vps_transport.request(row, "POST", "/v1/tests", {"operation_id": operation})
|
||||
if (
|
||||
result.get("operation_id") != operation
|
||||
or not re.fullmatch(r"[A-Za-z0-9_-]{43}", str(result.get("token", "")))
|
||||
or not time.time() < result.get("expires_at", 0) <= time.time() + 95
|
||||
):
|
||||
raise PairingError("Сервер не подтвердил замер.")
|
||||
_, _, address = vps_transport.destination(row["endpoint"])
|
||||
return {
|
||||
"endpoint": row["endpoint"],
|
||||
"address": address,
|
||||
"fingerprint": row["fingerprint"],
|
||||
"token": result["token"],
|
||||
"expires_at": result["expires_at"],
|
||||
"server_id": identifier,
|
||||
}
|
||||
|
||||
def cancel(self, identifier: str, operation: str) -> None:
|
||||
vps_transport.request(
|
||||
self.find(identifier), "POST", "/v1/tests/cancel", {"operation_id": operation}
|
||||
)
|
||||
@@ -1,7 +1,11 @@
|
||||
"""Allowlisted public router telemetry; never raw vendor responses or secrets."""
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
from .router_details_contracts import ClientDetails
|
||||
from .router_evidence import EvidenceChunk
|
||||
|
||||
|
||||
class PublicModel(BaseModel):
|
||||
@@ -9,6 +13,9 @@ class PublicModel(BaseModel):
|
||||
|
||||
|
||||
class Modem(PublicModel):
|
||||
radio_age_seconds: float | None = Field(default=None, ge=0, le=1e12)
|
||||
earfcn: float | None = Field(default=None, ge=0, le=1e7)
|
||||
tac: str = Field(default="", max_length=128)
|
||||
slot: int = Field(ge=1, le=3)
|
||||
operator: str = Field(max_length=128)
|
||||
connectivity: str = Field(max_length=128)
|
||||
@@ -27,10 +34,91 @@ class Modem(PublicModel):
|
||||
up_kbps: float | None = Field(ge=0, le=1e9)
|
||||
|
||||
|
||||
class ClientPolicy(PublicModel):
|
||||
mode: Literal["direct", "vpn", "aggregation", "whitelist"]
|
||||
preferred_sim: Literal["M1", "M2", "M3"] | None = None
|
||||
allow_fallback: bool
|
||||
return_to_preferred: bool
|
||||
persist: bool
|
||||
fail_seconds: int = Field(ge=15, le=300)
|
||||
recover_seconds: int = Field(ge=30, le=600)
|
||||
min_vpn_seconds: int = Field(ge=60, le=900)
|
||||
fallback_sims: list[Literal["M1", "M2", "M3"]] = Field(default_factory=list, max_length=3)
|
||||
|
||||
|
||||
class WANCounters(PublicModel):
|
||||
rx_bytes: float | None = Field(ge=0, le=2**53 - 1)
|
||||
tx_bytes: float | None = Field(ge=0, le=2**53 - 1)
|
||||
rx_packets: float | None = Field(ge=0, le=2**53 - 1)
|
||||
tx_packets: float | None = Field(ge=0, le=2**53 - 1)
|
||||
rx_errors: float | None = Field(ge=0, le=2**53 - 1)
|
||||
tx_errors: float | None = Field(ge=0, le=2**53 - 1)
|
||||
rx_dropped: float | None = Field(ge=0, le=2**53 - 1)
|
||||
tx_dropped: float | None = Field(ge=0, le=2**53 - 1)
|
||||
|
||||
|
||||
class SlotBinding(PublicModel):
|
||||
slot: int = Field(ge=1, le=3)
|
||||
sim: int = Field(ge=1, le=3)
|
||||
position: Literal["right", "center", "left"]
|
||||
|
||||
|
||||
class ClientWAN(PublicModel):
|
||||
traffic: WANCounters | None = None
|
||||
observed_uptime: float | None = Field(default=None, ge=0, le=1e12)
|
||||
session_uptime: float | None = Field(default=None, ge=0, le=1e12)
|
||||
|
||||
slot: int = Field(ge=1, le=3)
|
||||
wan: str = Field(max_length=128)
|
||||
interface: str = Field(max_length=128)
|
||||
up: bool | None
|
||||
sim_present: bool | None
|
||||
modem_present: bool | None
|
||||
registration: str = Field(max_length=128)
|
||||
failure_reason: str = Field(max_length=128)
|
||||
fresh: bool | None
|
||||
age_seconds: float | None = Field(ge=0, le=1e12)
|
||||
|
||||
|
||||
class ClientCheck(PublicModel):
|
||||
id: str = Field(max_length=128)
|
||||
state: Literal["ok", "error", "warn", "unknown", "na"]
|
||||
code: str = Field(max_length=128)
|
||||
|
||||
|
||||
class ClientAPI(PublicModel):
|
||||
details: ClientDetails | None = None
|
||||
module_version: str = Field(max_length=128)
|
||||
schema_version: Literal["1.1"]
|
||||
clock_quality: str = Field(max_length=128)
|
||||
boot_id: str = Field(max_length=128)
|
||||
revision: str = Field(max_length=128)
|
||||
rights: list[Literal["read", "policy", "recovery", "reboot", "diagnostics", "bundle"]] = Field(
|
||||
max_length=6
|
||||
)
|
||||
policy: ClientPolicy
|
||||
wan: list[ClientWAN] = Field(max_length=3)
|
||||
recovery_phase: str = Field(max_length=128)
|
||||
recovery_reason: str = Field(max_length=128)
|
||||
checks: list[ClientCheck] = Field(max_length=32)
|
||||
|
||||
|
||||
class Router(PublicModel):
|
||||
name: str = Field(default="", max_length=128)
|
||||
model_name: str = Field(default="", max_length=128)
|
||||
board_id: str = Field(default="", max_length=128)
|
||||
slot_map: list[SlotBinding] | None = Field(default=None, max_length=3)
|
||||
attached: bool | None = None
|
||||
connection: Literal["", "ethernet"] = ""
|
||||
web_access: bool = False
|
||||
web_username: str = Field(default="", max_length=64)
|
||||
|
||||
model_id: Literal["", "bananapi.bpi-r4-pro"] = ""
|
||||
adapter: Literal["", "dexaflow-client-api/v1"] = ""
|
||||
client_api: ClientAPI | None = None
|
||||
id: str = Field(pattern=r"^router_[a-f0-9]{24}$")
|
||||
family: Literal["DexaFlow"]
|
||||
identity: Literal["local_mac"]
|
||||
identity: Literal["local_mac", "device_ca"]
|
||||
address: str = Field(max_length=45)
|
||||
interface: str = Field(max_length=64)
|
||||
local_ip: str = Field(max_length=45)
|
||||
@@ -53,37 +141,107 @@ class Router(PublicModel):
|
||||
up_kbps: float | None = Field(ge=0, le=1e9)
|
||||
modems: list[Modem] = Field(max_length=3)
|
||||
|
||||
@field_validator("active_slots", mode="before")
|
||||
@classmethod
|
||||
def empty_active_slots(cls, value: object) -> object:
|
||||
# Go discovery emits a nil slice before the first authorized observation.
|
||||
# This means no confirmed active selection, never an active SIM number.
|
||||
return [] if value is None else value
|
||||
|
||||
|
||||
class Incident(PublicModel):
|
||||
sequence: int = Field(ge=1, le=2**53-1)
|
||||
sequence: int = Field(ge=1, le=2**53 - 1)
|
||||
at: int = Field(ge=0)
|
||||
boot_id: str = Field(pattern=r"^[a-f0-9]{32}$")
|
||||
elapsed_ms: int = Field(ge=0)
|
||||
device_id: str = Field(pattern=r"^router_[a-f0-9]{24}$")
|
||||
code: Literal["discovered", "availability", "address_changed", "router_restarted", "mode_changed", "internet_verification", "firmware_changed", "modem_state", "operator_changed", "signal_weak", "signal_recovered", "access_rejected", "access_granted", "command_requested", "command_complete", "command_unconfirmed", "command_failed"]
|
||||
code: Literal[
|
||||
"discovered",
|
||||
"availability",
|
||||
"address_changed",
|
||||
"router_restarted",
|
||||
"mode_changed",
|
||||
"internet_verification",
|
||||
"firmware_changed",
|
||||
"modem_state",
|
||||
"operator_changed",
|
||||
"signal_weak",
|
||||
"signal_recovered",
|
||||
"access_rejected",
|
||||
"access_granted",
|
||||
"command_requested",
|
||||
"command_complete",
|
||||
"command_unconfirmed",
|
||||
"command_failed",
|
||||
]
|
||||
slot: int = Field(default=0, ge=0, le=3)
|
||||
before: str = Field(default="", max_length=128)
|
||||
after: str = Field(default="", max_length=128)
|
||||
|
||||
|
||||
class Journal(PublicModel):
|
||||
first_sequence: int = Field(ge=0, le=2**53-1)
|
||||
last_sequence: int = Field(ge=0, le=2**53-1)
|
||||
dropped: int = Field(ge=0, le=2**53-1)
|
||||
first_sequence: int = Field(ge=0, le=2**53 - 1)
|
||||
last_sequence: int = Field(ge=0, le=2**53 - 1)
|
||||
dropped: int = Field(ge=0, le=2**53 - 1)
|
||||
limit: Literal[256]
|
||||
retention_days: Literal[7]
|
||||
error: bool
|
||||
|
||||
|
||||
class Measurement(PublicModel):
|
||||
phase: Literal["latency", "download", "upload", "complete", "cancelled", "error"]
|
||||
server_id: str = Field(pattern=r"^ls_[a-f0-9]{32}$")
|
||||
interface: str = Field(max_length=20)
|
||||
started_at: int = Field(ge=0)
|
||||
finished_at: int = Field(default=0, ge=0)
|
||||
sampled_at: int = Field(default=0, ge=0)
|
||||
current_bps: float = Field(default=0, ge=0, le=1e12)
|
||||
download_bps: float = Field(default=0, ge=0, le=1e12)
|
||||
upload_bps: float = Field(default=0, ge=0, le=1e12)
|
||||
latency_ms: float = Field(default=0, ge=0, le=1e6)
|
||||
jitter_ms: float = Field(default=0, ge=0, le=1e6)
|
||||
error: str = Field(default="", max_length=80, pattern=r"^[a-z_]*$")
|
||||
|
||||
|
||||
class Receipt(PublicModel):
|
||||
measurement: Measurement | None = None
|
||||
at: int = Field(default=0, ge=0)
|
||||
vendor_id: str = Field(default="", max_length=80, pattern=r"^[A-Za-z0-9_-]*$")
|
||||
operation_id: str = Field(pattern=r"^op_[a-f0-9]{32}$")
|
||||
device_id: str = Field(default="", max_length=32)
|
||||
action: Literal["", "mode", "reboot"] = ""
|
||||
action: Literal[
|
||||
"",
|
||||
"mode",
|
||||
"reboot",
|
||||
"policy",
|
||||
"recovery",
|
||||
"diagnostics",
|
||||
"inspect",
|
||||
"speedtest",
|
||||
"speedtest_cancel",
|
||||
] = ""
|
||||
state: Literal["queued", "applying", "complete", "error", "unknown"]
|
||||
error: Literal["", "router_unavailable", "expired", "access_rejected", "unsupported_response", "storage_error", "command_rejected", "router_busy", "sim_unavailable", "confirmation_timeout"] = ""
|
||||
error: Literal[
|
||||
"",
|
||||
"router_unavailable",
|
||||
"expired",
|
||||
"access_rejected",
|
||||
"unsupported_response",
|
||||
"storage_error",
|
||||
"command_rejected",
|
||||
"router_busy",
|
||||
"sim_unavailable",
|
||||
"confirmation_timeout",
|
||||
"router_certificate_rejected",
|
||||
"router_conflict",
|
||||
"result_expired",
|
||||
] = ""
|
||||
|
||||
|
||||
class Snapshot(PublicModel):
|
||||
speedtest_version: Literal[0, 1] = 0
|
||||
read_version: Literal[0, 1] = 0
|
||||
evidence: EvidenceChunk | None = None
|
||||
control_version: Literal[0, 1] = 0
|
||||
schema_version: Literal["missioncore.routers/v1"] = Field(alias="schema")
|
||||
runtime_id: str = Field(pattern=r"^[a-f0-9]{32}$")
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Nullable live VPN and prepared reserve facts; not inferred reachability."""
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class Detail(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True, allow_inf_nan=False)
|
||||
|
||||
|
||||
class VPN(Detail):
|
||||
selected: bool | None
|
||||
active: bool | None
|
||||
verified: bool | None
|
||||
sim: str = Field(max_length=128)
|
||||
server: str = Field(max_length=128)
|
||||
watch_state: str = Field(max_length=128)
|
||||
watch_age: float | None = Field(ge=0, le=1e12)
|
||||
proof_age: float | None = Field(ge=0, le=1e12)
|
||||
last_success_age: float | None = Field(ge=0, le=1e12)
|
||||
|
||||
|
||||
class Pair(Detail):
|
||||
sim: str = Field(max_length=128)
|
||||
server: str = Field(max_length=128)
|
||||
transport: str = Field(max_length=128)
|
||||
age: float | None = Field(ge=0, le=1e12)
|
||||
|
||||
|
||||
class Reserve(Detail):
|
||||
available: bool | None
|
||||
running: bool | None
|
||||
count: float | None = Field(ge=0, le=1000)
|
||||
target: float | None = Field(ge=0, le=1000)
|
||||
distinct_sims: float | None = Field(ge=0, le=3)
|
||||
age: float | None = Field(ge=0, le=1e12)
|
||||
ttl: float | None = Field(ge=0, le=1e12)
|
||||
phase: str = Field(max_length=128)
|
||||
pairs: list[Pair] = Field(max_length=12)
|
||||
|
||||
|
||||
class ClientDetails(Detail):
|
||||
vpn: VPN
|
||||
reserve: Reserve
|
||||
pending: bool | None
|
||||
fallback: bool | None
|
||||
fallback_reason: str = Field(max_length=128)
|
||||
recovery_age: float | None = Field(ge=0, le=1e12)
|
||||
last_attempt_current: bool | None
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Bounded on-demand router documents. RAM only; the router owns its history."""
|
||||
|
||||
import base64
|
||||
import copy
|
||||
import time
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
|
||||
|
||||
from .trust import PairingError
|
||||
|
||||
Resource = Literal[
|
||||
"diagnostics_latest",
|
||||
"diagnostic",
|
||||
"bundle",
|
||||
"events",
|
||||
"recovery_history",
|
||||
"recordings",
|
||||
"recording",
|
||||
"targets",
|
||||
]
|
||||
|
||||
|
||||
class EvidenceQuery(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
resource: Resource
|
||||
id: str = Field(max_length=80)
|
||||
after: str = Field(max_length=512)
|
||||
transfer: str = Field(pattern=r"^(?:[a-f0-9]{64})?$")
|
||||
offset: int = Field(ge=0, lt=2097152)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def bounds(self):
|
||||
import re
|
||||
|
||||
identified = self.resource in ("diagnostic", "bundle", "recording")
|
||||
if identified != bool(self.id) or (
|
||||
self.id and not re.fullmatch(r"[A-Za-z0-9_-]{1,80}", self.id)
|
||||
):
|
||||
raise ValueError("resource identity")
|
||||
if self.after and self.resource not in ("events", "recovery_history"):
|
||||
raise ValueError("cursor resource")
|
||||
if self.offset % 32768 or (not self.transfer and self.offset):
|
||||
raise ValueError("chunk boundary")
|
||||
return self
|
||||
|
||||
|
||||
class EvidenceRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
operation_id: str = Field(pattern=r"^op_[a-f0-9]{32}$")
|
||||
runtime_id: str = Field(pattern=r"^[a-f0-9]{32}$")
|
||||
device_id: str = Field(pattern=r"^router_[a-f0-9]{24}$")
|
||||
action: Literal["inspect"]
|
||||
deadline: int
|
||||
expected_boot_id: str = Field(min_length=1, max_length=128)
|
||||
query: EvidenceQuery
|
||||
|
||||
|
||||
class EvidenceChunk(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
operation_id: str = Field(pattern=r"^op_[a-f0-9]{32}$")
|
||||
device_id: str = Field(pattern=r"^router_[a-f0-9]{24}$")
|
||||
boot_id: str = Field(min_length=1, max_length=128)
|
||||
resource: Resource
|
||||
id: str = Field(max_length=80)
|
||||
transfer: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
offset: int = Field(ge=0, lt=2097152)
|
||||
total: int = Field(gt=0, le=2097152)
|
||||
at: int = Field(ge=0)
|
||||
data: str = Field(max_length=43692)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def valid_chunk(self):
|
||||
try:
|
||||
raw = base64.b64decode(self.data, validate=True)
|
||||
except ValueError:
|
||||
raise ValueError("invalid chunk") from None
|
||||
if self.offset % 32768 or not 0 < len(raw) <= 32768 or self.offset + len(raw) > self.total:
|
||||
raise ValueError("invalid extent")
|
||||
if len(raw) != min(32768, self.total - self.offset):
|
||||
raise ValueError("partial chunk")
|
||||
return self
|
||||
|
||||
|
||||
def inspect(owner, fleet, vehicle_id, body):
|
||||
try:
|
||||
request = EvidenceRequest.model_validate(body)
|
||||
except (ValidationError, TypeError, ValueError):
|
||||
raise PairingError("Проверьте запрос отчёта.") from None
|
||||
now = time.time()
|
||||
if not 0 < request.deadline - now <= 90:
|
||||
raise PairingError("Запрос устарел. Обновите состояние.")
|
||||
with fleet.lock:
|
||||
row = fleet.find(vehicle_id)
|
||||
state = owner.view(row)
|
||||
device = next((d for d in state["items"] if d["id"] == request.device_id), None)
|
||||
api = (device or {}).get("client_api")
|
||||
right = "bundle" if request.query.resource == "bundle" else "read"
|
||||
if (
|
||||
not state.get("fresh")
|
||||
or not state.get("available")
|
||||
or state.get("read_version") != 1
|
||||
or state.get("runtime_id") != request.runtime_id
|
||||
or not device
|
||||
or device["state"] != "ready"
|
||||
or not -30 <= now - device["observed_at"] < 40
|
||||
or not api
|
||||
or api["boot_id"] != request.expected_boot_id
|
||||
or right not in api["rights"]
|
||||
):
|
||||
raise PairingError("Чтение отчёта пока недоступно. Обновите состояние борта.")
|
||||
key = (vehicle_id, request.operation_id)
|
||||
if key in owner.pending:
|
||||
entry = owner.pending[key]
|
||||
if entry["binding"] != row["binding"]["binding_id"]:
|
||||
raise PairingError("Привязка борта изменилась.")
|
||||
return copy.deepcopy(entry["public"])
|
||||
if any(
|
||||
e["public"]["state"] in ("queued", "applying")
|
||||
for (v, _), e in owner.pending.items()
|
||||
if v == vehicle_id
|
||||
):
|
||||
raise PairingError("Дождитесь завершения текущего запроса.")
|
||||
# At most one cached document chunk per vehicle. No history enters DB.
|
||||
for k, entry in list(owner.pending.items()):
|
||||
if k[0] == vehicle_id and entry["public"].get("action") == "inspect":
|
||||
del owner.pending[k]
|
||||
if len(owner.pending) >= 16:
|
||||
raise PairingError("Дождитесь завершения текущих запросов.")
|
||||
public = {
|
||||
"operation_id": request.operation_id,
|
||||
"device_id": request.device_id,
|
||||
"action": "inspect",
|
||||
"state": "queued",
|
||||
}
|
||||
owner.pending[key] = {
|
||||
"payload": request.model_dump(),
|
||||
"public": public,
|
||||
"binding": row["binding"]["binding_id"],
|
||||
"created": now,
|
||||
"deadline": request.deadline,
|
||||
"query": request.model_dump(),
|
||||
}
|
||||
return dict(public)
|
||||
|
||||
|
||||
def attach_chunk(entry, result, evidence):
|
||||
request = entry.get("query")
|
||||
if not request or result.get("action") != "inspect" or result["state"] != "complete":
|
||||
return result
|
||||
query = request["query"]
|
||||
if (
|
||||
not evidence
|
||||
or evidence["operation_id"] != request["operation_id"]
|
||||
or evidence["device_id"] != request["device_id"]
|
||||
or evidence["boot_id"] != request["expected_boot_id"]
|
||||
or evidence["resource"] != query["resource"]
|
||||
or evidence["id"] != query["id"]
|
||||
or evidence["offset"] != query["offset"]
|
||||
or (query["transfer"] and evidence["transfer"] != query["transfer"])
|
||||
):
|
||||
return {**result, "state": "error", "error": "unsupported_response"}
|
||||
return {**result, "evidence": copy.deepcopy(evidence)}
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Authenticated speed measurement admission, using the existing Node command channel."""
|
||||
|
||||
import copy
|
||||
import re
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from .librespeed import LibreSpeed, lock
|
||||
from .trust import PairingError
|
||||
|
||||
|
||||
def start(fleet: Any, vehicle: str, value: dict[str, Any]) -> dict[str, Any]:
|
||||
required = {"operation_id", "runtime_id", "device_id", "server_id"}
|
||||
if (
|
||||
set(value) != required
|
||||
or any(not isinstance(v, str) for v in value.values())
|
||||
or not re.fullmatch(r"op_[a-f0-9]{32}", value["operation_id"])
|
||||
):
|
||||
raise PairingError("Некорректный запрос замера.")
|
||||
with lock:
|
||||
with fleet.lock:
|
||||
row = fleet.find(vehicle)
|
||||
state = fleet.routers.view(row)
|
||||
device = next((d for d in state["items"] if d["id"] == value["device_id"]), None)
|
||||
key = (vehicle, value["operation_id"])
|
||||
if key in fleet.routers.pending:
|
||||
return copy.deepcopy(fleet.routers.pending[key]["public"])
|
||||
if (
|
||||
not state.get("fresh")
|
||||
or state.get("runtime_id") != value["runtime_id"]
|
||||
or state.get("speedtest_version") != 1
|
||||
or not device
|
||||
or device["state"] != "ready"
|
||||
or device.get("connection") != "ethernet"
|
||||
or not device.get("attached")
|
||||
):
|
||||
raise PairingError("Нужны доступный Ethernet-роутер и обновлённый бортовой агент.")
|
||||
if len(fleet.routers.pending) >= 16 or any(
|
||||
k[0] == vehicle and e["public"]["state"] in ("queued", "applying")
|
||||
for k, e in fleet.routers.pending.items()
|
||||
):
|
||||
raise PairingError("Дождитесь завершения текущей операции на борту.")
|
||||
binding = row["binding"]["binding_id"]
|
||||
service = LibreSpeed(fleet.root)
|
||||
grant = service.lease(value["server_id"], value["operation_id"])
|
||||
with fleet.lock:
|
||||
row = fleet.find(vehicle)
|
||||
current = fleet.routers.view(row)
|
||||
if (
|
||||
row["binding"]["binding_id"] != binding
|
||||
or not current.get("fresh")
|
||||
or current.get("runtime_id") != value["runtime_id"]
|
||||
):
|
||||
service.cancel(value["server_id"], value["operation_id"])
|
||||
raise PairingError("Борт переподключился. Повторите замер.")
|
||||
command = {k: value[k] for k in ("operation_id", "runtime_id", "device_id")}
|
||||
command.update(action="speedtest", deadline=int(time.time()) + 85, speedtest=grant)
|
||||
public = {"operation_id": value["operation_id"], "state": "queued"}
|
||||
fleet.routers.pending[key] = {
|
||||
"payload": command,
|
||||
"public": public,
|
||||
"binding": binding,
|
||||
"created": time.time(),
|
||||
"deadline": command["deadline"],
|
||||
"speedtest_server": value["server_id"],
|
||||
"device_id": value["device_id"],
|
||||
"runtime_id": value["runtime_id"],
|
||||
}
|
||||
return dict(public)
|
||||
|
||||
|
||||
def cancel(fleet: Any, vehicle: str, operation: str) -> dict[str, Any]:
|
||||
import secrets
|
||||
|
||||
with lock:
|
||||
with fleet.lock:
|
||||
row = fleet.find(vehicle)
|
||||
entry = fleet.routers.pending.get((vehicle, operation))
|
||||
if (
|
||||
not entry
|
||||
or not entry.get("speedtest_server")
|
||||
or entry["binding"] != row["binding"]["binding_id"]
|
||||
):
|
||||
raise PairingError("Замер не найден.")
|
||||
if entry.get("cancel_operation"):
|
||||
return {"operation_id": operation, "state": "cancelling"}
|
||||
if len(fleet.routers.pending) >= 32:
|
||||
raise PairingError("Дождитесь подтверждения предыдущей операции.")
|
||||
identifier = "op_" + secrets.token_hex(16)
|
||||
entry["cancel_operation"] = identifier
|
||||
command = {
|
||||
"operation_id": identifier,
|
||||
"runtime_id": entry["runtime_id"],
|
||||
"device_id": entry["device_id"],
|
||||
"deadline": int(time.time()) + 30,
|
||||
"action": "speedtest_cancel",
|
||||
"speedtest_cancel": operation,
|
||||
}
|
||||
# Stop delivery of an unreceived start; always send cancellation for an in-flight one.
|
||||
entry["payload"] = None
|
||||
fleet.routers.pending[(vehicle, identifier)] = {
|
||||
"payload": command,
|
||||
"public": {"operation_id": identifier, "state": "queued"},
|
||||
"binding": entry["binding"],
|
||||
"created": time.time(),
|
||||
"deadline": command["deadline"],
|
||||
}
|
||||
# Node must acknowledge cancellation before its lease is released.
|
||||
# Revoking first turns an interrupted stream into a spurious transfer error.
|
||||
# Node closes sockets and finishes the lease; loss of contact is bounded by expiry.
|
||||
return {"operation_id": operation, "state": "cancelling"}
|
||||
+239
-23
@@ -3,14 +3,17 @@
|
||||
No raw radio time series, access password or command payload enters Fleet DB.
|
||||
All methods run under FleetRegistry.lock; Node sends its immutable cached state.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from .router_contracts import Snapshot
|
||||
from .router_contracts import ClientPolicy, Snapshot
|
||||
from .router_evidence import attach_chunk, inspect
|
||||
from .trust import PairingError
|
||||
|
||||
|
||||
@@ -34,7 +37,9 @@ class Routers:
|
||||
for key, entry in list(self.pending.items()):
|
||||
if now - entry["created"] > 600:
|
||||
del self.pending[key]
|
||||
elif (entry["deadline"] <= now and entry["public"]["state"] == "queued") or (now - entry["created"] > 300 and entry["public"]["state"] == "applying"):
|
||||
elif (entry["deadline"] <= now and entry["public"]["state"] == "queued") or (
|
||||
now - entry["created"] > 300 and entry["public"]["state"] == "applying"
|
||||
):
|
||||
entry["payload"] = None
|
||||
entry["public"] = {"operation_id": key[1], "state": "unknown"}
|
||||
|
||||
@@ -44,7 +49,11 @@ class Routers:
|
||||
if not cached or cached["binding"] != (row.get("binding") or {}).get("binding_id"):
|
||||
return {"available": False, "fresh": False, "items": [], "events": [], "results": []}
|
||||
value = copy.deepcopy(cached["state"])
|
||||
value["fresh"] = not cached.get("invalid", False) and row["enrollment"] == "paired" and time.time() - cached["received"] < 30
|
||||
value["fresh"] = (
|
||||
not cached.get("invalid", False)
|
||||
and row["enrollment"] == "paired"
|
||||
and time.time() - cached["received"] < 30
|
||||
)
|
||||
value["received_at"] = cached["received"]
|
||||
return value
|
||||
|
||||
@@ -53,8 +62,10 @@ class Routers:
|
||||
raw = payload.get("routers")
|
||||
if raw is not None:
|
||||
try:
|
||||
if not isinstance(raw, dict) or len(json.dumps(raw)) > 196608:
|
||||
if not isinstance(raw, dict) or len(json.dumps(raw)) > 262144:
|
||||
raise ValueError("router payload limit")
|
||||
if len(json.dumps({k: v for k, v in raw.items() if k != "evidence"})) > 196608:
|
||||
raise ValueError("router telemetry payload limit")
|
||||
value = Snapshot.model_validate(raw).model_dump(by_alias=True)
|
||||
if len({item["id"] for item in value["items"]}) != len(value["items"]):
|
||||
raise ValueError("duplicate router")
|
||||
@@ -63,12 +74,16 @@ class Routers:
|
||||
raise ValueError("invalid journal sequence")
|
||||
if len(self.latest) >= 128 and row["node_id"] not in self.latest:
|
||||
raise ValueError("router cache limit")
|
||||
self.latest[row["node_id"]] = {"binding": row["binding"]["binding_id"], "received": time.time(), "state": value}
|
||||
self.latest[row["node_id"]] = {
|
||||
"binding": row["binding"]["binding_id"],
|
||||
"received": time.time(),
|
||||
"state": value,
|
||||
}
|
||||
for result in value["results"]:
|
||||
entry = self.pending.get((row["id"], result["operation_id"]))
|
||||
if entry and entry["binding"] == row["binding"]["binding_id"]:
|
||||
entry["payload"] = None
|
||||
entry["public"] = result
|
||||
entry["public"] = attach_chunk(entry, result, value.get("evidence"))
|
||||
except (ValidationError, ValueError, TypeError):
|
||||
# A broken optional vendor adapter cannot fail camera/control
|
||||
# heartbeat. Its previous observation expires instead.
|
||||
@@ -88,17 +103,88 @@ class Routers:
|
||||
def authorize(self, fleet, vehicle_id, value):
|
||||
# Manual validation intentionally does not echo a rejected password in
|
||||
# Pydantic/FastAPI validation responses or exception strings.
|
||||
expected = {"operation_id", "runtime_id", "device_id", "deadline", "username", "password"}
|
||||
base = {"operation_id", "runtime_id", "device_id", "deadline"}
|
||||
api_access = isinstance(value, dict) and "client_api" in value
|
||||
settings_request = isinstance(value, dict) and "settings" in value
|
||||
expected = base | (
|
||||
{"settings"}
|
||||
if settings_request
|
||||
else {"client_api", "model_id"}
|
||||
if api_access
|
||||
else {"username", "password"}
|
||||
)
|
||||
if not isinstance(value, dict) or set(value) != expected:
|
||||
raise PairingError("Неверный запрос доступа к роутеру.")
|
||||
if any(not isinstance(value[k], str) or not 1 <= len(value[k]) <= limit for k, limit in (("username", 64), ("password", 256), ("device_id", 32), ("runtime_id", 32), ("operation_id", 35))):
|
||||
fields = [("device_id", 32), ("runtime_id", 32), ("operation_id", 35)]
|
||||
if settings_request:
|
||||
settings = value["settings"]
|
||||
if not isinstance(settings, dict) or set(settings) != {
|
||||
"name",
|
||||
"address",
|
||||
"username",
|
||||
"password",
|
||||
}:
|
||||
raise PairingError("Проверьте общие настройки.")
|
||||
for key, limit in (("name", 128), ("address", 45), ("username", 64), ("password", 256)):
|
||||
if not isinstance(settings[key], str) or len(settings[key]) > limit:
|
||||
raise PairingError("Проверьте общие настройки.")
|
||||
try:
|
||||
address = ipaddress.ip_address(settings["address"])
|
||||
valid = (
|
||||
address.version == 4
|
||||
and address.is_private
|
||||
and not address.is_loopback
|
||||
and not address.is_link_local
|
||||
)
|
||||
except ValueError:
|
||||
valid = False
|
||||
if (
|
||||
not valid
|
||||
or bool(settings["username"]) != bool(settings["password"])
|
||||
or any(ord(ch) < 32 or ord(ch) == 127 for ch in settings["name"])
|
||||
):
|
||||
raise PairingError("Проверьте адрес и данные админки.")
|
||||
elif api_access:
|
||||
access = value["client_api"]
|
||||
if (
|
||||
value["model_id"] not in ("", "bananapi.bpi-r4-pro")
|
||||
or not isinstance(access, dict)
|
||||
or set(access) != {"token", "ca"}
|
||||
):
|
||||
raise PairingError("Проверьте профиль и данные доступа.")
|
||||
if any(
|
||||
not isinstance(access[k], str) or not 1 <= len(access[k]) <= limit
|
||||
for k, limit in (("token", 4096), ("ca", 8192))
|
||||
):
|
||||
raise PairingError("Проверьте ключ и сертификат роутера.")
|
||||
else:
|
||||
fields += [("username", 64), ("password", 256)]
|
||||
if any(
|
||||
not isinstance(value[k], str) or not 1 <= len(value[k]) <= limit for k, limit in fields
|
||||
):
|
||||
raise PairingError("Проверьте данные доступа.")
|
||||
if not re.fullmatch(r"op_[a-f0-9]{32}", value["operation_id"]) or type(value["deadline"]) is not int or not 0 < value["deadline"] - time.time() <= 90:
|
||||
if (
|
||||
not re.fullmatch(r"op_[a-f0-9]{32}", value["operation_id"])
|
||||
or type(value["deadline"]) is not int
|
||||
or not 0 < value["deadline"] - time.time() <= 90
|
||||
):
|
||||
raise PairingError("Запрос устарел. Обновите карточку роутера.")
|
||||
with fleet.lock:
|
||||
row = fleet.find(vehicle_id)
|
||||
state = self.view(row)
|
||||
if not state.get("available") or not state.get("fresh") or state.get("runtime_id") != value["runtime_id"] or not any(d["id"] == value["device_id"] and d["state"] in {"ready", "access_required", "access_rejected"} for d in state["items"]):
|
||||
if (
|
||||
not state.get("available")
|
||||
or not state.get("fresh")
|
||||
or state.get("runtime_id") != value["runtime_id"]
|
||||
or not any(
|
||||
d["id"] == value["device_id"]
|
||||
and (
|
||||
settings_request
|
||||
or d["state"] in {"ready", "access_required", "access_rejected"}
|
||||
)
|
||||
for d in state["items"]
|
||||
)
|
||||
):
|
||||
raise PairingError("Роутер недоступен. Обновите его состояние.")
|
||||
key = (vehicle_id, value["operation_id"])
|
||||
if key in self.pending:
|
||||
@@ -106,9 +192,18 @@ class Routers:
|
||||
if len(self.pending) >= 16:
|
||||
raise PairingError("Дождитесь завершения текущих запросов.")
|
||||
receipt = {"operation_id": value["operation_id"], "state": "queued"}
|
||||
self.pending[key] = {"payload": copy.deepcopy(value), "public": receipt, "binding": row["binding"]["binding_id"], "created": time.time(), "deadline": value["deadline"]}
|
||||
self.pending[key] = {
|
||||
"payload": copy.deepcopy(value),
|
||||
"public": receipt,
|
||||
"binding": row["binding"]["binding_id"],
|
||||
"created": time.time(),
|
||||
"deadline": value["deadline"],
|
||||
}
|
||||
return dict(receipt)
|
||||
|
||||
def inspect(self, fleet, vehicle_id, value):
|
||||
return inspect(self, fleet, vehicle_id, value)
|
||||
|
||||
def operation(self, row, identifier):
|
||||
self.prune()
|
||||
entry = self.pending.get((row["id"], identifier))
|
||||
@@ -117,21 +212,102 @@ class Routers:
|
||||
return copy.deepcopy(entry["public"])
|
||||
|
||||
def control(self, fleet, vehicle_id, value):
|
||||
expected = {"operation_id", "runtime_id", "device_id", "deadline", "action", "mode", "slots"}
|
||||
if not isinstance(value, dict) or set(value) != expected:
|
||||
expected = {
|
||||
"operation_id",
|
||||
"runtime_id",
|
||||
"device_id",
|
||||
"deadline",
|
||||
"action",
|
||||
"mode",
|
||||
"slots",
|
||||
}
|
||||
api_command = isinstance(value, dict) and set(value) == expected | {
|
||||
"policy",
|
||||
"recovery",
|
||||
"sim",
|
||||
"expected_boot_id",
|
||||
"expected_revision",
|
||||
}
|
||||
if not isinstance(value, dict) or (set(value) != expected and not api_command):
|
||||
raise PairingError("Неверная команда роутеру.")
|
||||
if any(not isinstance(value[k], str) or not re.fullmatch(pattern, value[k]) for k, pattern in (
|
||||
("operation_id", r"op_[a-f0-9]{32}"), ("runtime_id", r"[a-f0-9]{32}"), ("device_id", r"router_[a-f0-9]{24}"))):
|
||||
if any(
|
||||
not isinstance(value[k], str) or not re.fullmatch(pattern, value[k])
|
||||
for k, pattern in (
|
||||
("operation_id", r"op_[a-f0-9]{32}"),
|
||||
("runtime_id", r"[a-f0-9]{32}"),
|
||||
("device_id", r"router_[a-f0-9]{24}"),
|
||||
)
|
||||
):
|
||||
raise PairingError("Неверная команда роутеру.")
|
||||
if type(value["deadline"]) is not int or not 0 < value["deadline"] - time.time() <= 90:
|
||||
raise PairingError("Запрос устарел. Обновите карточку роутера.")
|
||||
slots = value["slots"]
|
||||
if not isinstance(slots, list) or len(slots) > 3 or any(type(s) is not int or s not in (1, 2, 3) for s in slots) or len(set(slots)) != len(slots):
|
||||
if (
|
||||
not isinstance(slots, list)
|
||||
or len(slots) > 3
|
||||
or any(type(s) is not int or s not in (1, 2, 3) for s in slots)
|
||||
or len(set(slots)) != len(slots)
|
||||
):
|
||||
raise PairingError("Проверьте выбранные SIM-карты.")
|
||||
if value["action"] == "reboot":
|
||||
if api_command:
|
||||
valid = value["mode"] == "" and not slots
|
||||
valid = (
|
||||
valid
|
||||
and isinstance(value["expected_boot_id"], str)
|
||||
and 1 <= len(value["expected_boot_id"]) <= 128
|
||||
)
|
||||
valid = (
|
||||
valid
|
||||
and isinstance(value["expected_revision"], str)
|
||||
and bool(re.fullmatch(r"[a-zA-Z0-9_.:-]{1,128}", value["expected_revision"]))
|
||||
)
|
||||
if value["action"] == "policy":
|
||||
try:
|
||||
policy = ClientPolicy.model_validate(value["policy"])
|
||||
valid = (
|
||||
valid
|
||||
and policy.allow_fallback
|
||||
and policy.return_to_preferred
|
||||
and policy.persist
|
||||
and not policy.fallback_sims
|
||||
)
|
||||
valid = valid and (
|
||||
(policy.mode == "direct" and policy.preferred_sim in ("M1", "M2", "M3"))
|
||||
or (policy.mode != "direct" and policy.preferred_sim is None)
|
||||
)
|
||||
except (ValidationError, ValueError, TypeError):
|
||||
valid = False
|
||||
valid = valid and value["recovery"] == "" and value["sim"] == ""
|
||||
elif value["action"] == "recovery":
|
||||
valid = (
|
||||
valid
|
||||
and value["policy"] is None
|
||||
and (
|
||||
(
|
||||
value["recovery"] == "wan_reconnect"
|
||||
and value["sim"] in ("M1", "M2", "M3")
|
||||
)
|
||||
or (
|
||||
value["recovery"] in ("vpn_reconnect", "dns_restart")
|
||||
and value["sim"] == ""
|
||||
)
|
||||
)
|
||||
)
|
||||
else:
|
||||
valid = (
|
||||
valid
|
||||
and value["action"] in ("reboot", "diagnostics")
|
||||
and value["policy"] is None
|
||||
and value["recovery"] == ""
|
||||
and value["sim"] == ""
|
||||
)
|
||||
elif value["action"] == "reboot":
|
||||
valid = value["mode"] == "" and not slots
|
||||
else:
|
||||
valid = value["action"] == "mode" and ((value["mode"] == "direct" and len(slots) == 1) or (value["mode"] == "aggregation" and bool(slots)))
|
||||
valid = value["action"] == "mode" and (
|
||||
(value["mode"] == "direct" and len(slots) == 1)
|
||||
or (value["mode"] == "aggregation" and bool(slots))
|
||||
)
|
||||
if not valid:
|
||||
raise PairingError("Неподдерживаемая команда роутеру.")
|
||||
with fleet.lock:
|
||||
@@ -140,15 +316,55 @@ class Routers:
|
||||
key = (vehicle_id, value["operation_id"])
|
||||
if key in self.pending and self.pending[key]["binding"] == row["binding"]["binding_id"]:
|
||||
return copy.deepcopy(self.pending[key]["public"])
|
||||
if not state.get("available") or not state.get("fresh") or state.get("control_version") != 1 or state.get("runtime_id") != value["runtime_id"]:
|
||||
if (
|
||||
not state.get("available")
|
||||
or not state.get("fresh")
|
||||
or state.get("control_version") != 1
|
||||
or state.get("runtime_id") != value["runtime_id"]
|
||||
):
|
||||
raise PairingError("Обновите состояние и версию Mission Core на борту.")
|
||||
device = next((d for d in state["items"] if d["id"] == value["device_id"]), None)
|
||||
if not device or device["state"] != "ready" or not -30 <= time.time() - device["observed_at"] < 40:
|
||||
if (
|
||||
not device
|
||||
or device["state"] != "ready"
|
||||
or not -30 <= time.time() - device["observed_at"] < 40
|
||||
):
|
||||
raise PairingError("Нет свежего состояния роутера.")
|
||||
busy = any(e["public"]["state"] in {"queued", "applying"} for (v, _), e in self.pending.items() if v == vehicle_id)
|
||||
client_api = device.get("client_api")
|
||||
if (
|
||||
api_command
|
||||
and client_api
|
||||
and (
|
||||
value["expected_boot_id"] != client_api["boot_id"]
|
||||
or value["expected_revision"] != client_api["revision"]
|
||||
)
|
||||
):
|
||||
raise PairingError(
|
||||
"Настройки роутера изменились. Обновите состояние перед новой командой."
|
||||
)
|
||||
if bool(client_api) != api_command or (
|
||||
api_command and value["action"] not in client_api["rights"]
|
||||
):
|
||||
raise PairingError("Команда недоступна для этого роутера или ключа.")
|
||||
busy = any(
|
||||
e["public"]["state"] in {"queued", "applying"}
|
||||
for (v, _), e in self.pending.items()
|
||||
if v == vehicle_id
|
||||
)
|
||||
busy = busy or any(r["state"] in {"queued", "applying"} for r in state["results"])
|
||||
if busy or len(self.pending) >= 16:
|
||||
raise PairingError("Дождитесь завершения текущей команды.")
|
||||
receipt = {"operation_id": value["operation_id"], "device_id": value["device_id"], "action": value["action"], "state": "queued"}
|
||||
self.pending[key] = {"payload": copy.deepcopy(value), "public": receipt, "binding": row["binding"]["binding_id"], "created": time.time(), "deadline": value["deadline"]}
|
||||
receipt = {
|
||||
"operation_id": value["operation_id"],
|
||||
"device_id": value["device_id"],
|
||||
"action": value["action"],
|
||||
"state": "queued",
|
||||
}
|
||||
self.pending[key] = {
|
||||
"payload": copy.deepcopy(value),
|
||||
"public": receipt,
|
||||
"binding": row["binding"]["binding_id"],
|
||||
"created": time.time(),
|
||||
"deadline": value["deadline"],
|
||||
}
|
||||
return dict(receipt)
|
||||
|
||||
@@ -11,6 +11,8 @@ from typing import Any
|
||||
|
||||
from k1link.compute_connections.store import ConnectionStore, Registry, WorkerBinding
|
||||
from k1link.fleet import network_client
|
||||
from k1link.fleet.librespeed import LibreSpeed
|
||||
from k1link.fleet.librespeed import lock as speed_lock
|
||||
from k1link.fleet.server_catalog import Document, ServerCatalog, endpoint_address
|
||||
|
||||
|
||||
@@ -27,6 +29,7 @@ class ServerRemoval:
|
||||
# Existing owners retain their locks. Profile imports and tunnel changes
|
||||
# cannot race retirement; fleet/connection revisions invalidate stale tabs.
|
||||
with (
|
||||
speed_lock,
|
||||
self.networks.import_lock,
|
||||
self.hosts.lock,
|
||||
self.networks.sync_lock,
|
||||
@@ -89,7 +92,22 @@ class ServerRemoval:
|
||||
outbox = {x for r in db.execute("SELECT host,target FROM network_outbox") for x in r}
|
||||
if any(r.get("host_id") in host_ids for r in pending) or (probes | outbox) & host_ids:
|
||||
blocked.append("Дождитесь завершения команд оборудования, отправленных через этот VPS.")
|
||||
speed = [
|
||||
r
|
||||
for r in LibreSpeed(self.fleet.root).rows()
|
||||
if endpoint_address(r["endpoint"]) == host["address"]
|
||||
]
|
||||
speed_ids = {r["id"] for r in speed}
|
||||
if speed_ids and any(
|
||||
e.get("speedtest_server") in speed_ids
|
||||
and e["public"]["state"] in ("queued", "applying")
|
||||
for e in self.fleet.routers.pending.values()
|
||||
):
|
||||
blocked.append("Остановите замер скорости перед отключением VPS.")
|
||||
signature = {
|
||||
"librespeed": [
|
||||
{k: r[k] for k in ("id", "endpoint", "fingerprint", "state")} for r in speed
|
||||
],
|
||||
"server": {k: host[k] for k in ("id", "name", "address", "revision")},
|
||||
"arnavi": [
|
||||
{k: r.get(k) for k in ("id", "revision", "endpoint", "fingerprint", "vehicle_ids")}
|
||||
@@ -118,7 +136,9 @@ class ServerRemoval:
|
||||
"confirmation": digest,
|
||||
"name": host["name"],
|
||||
"blocked": blocked,
|
||||
"services": ["ARNavi"] * len(arnavi) + ["WireGuard"] * len(wg),
|
||||
"services": ["ARNavi"] * len(arnavi)
|
||||
+ ["WireGuard"] * len(wg)
|
||||
+ ["LibreSpeed"] * len(speed),
|
||||
"vehicle_connections": len(affected),
|
||||
"worker_connections": sum(
|
||||
c.profile_id in profiles for w in registry.workers for c in w.connections
|
||||
@@ -208,5 +228,12 @@ class ServerRemoval:
|
||||
db.execute("DELETE FROM links WHERE host=?", (row["id"],))
|
||||
db.execute("DELETE FROM packets WHERE host=?", (row["id"],))
|
||||
db.execute("DELETE FROM hosts WHERE id=?", (row["id"],))
|
||||
LibreSpeed(self.fleet.root).forget(
|
||||
{
|
||||
r["id"]
|
||||
for r in LibreSpeed(self.fleet.root).rows()
|
||||
if endpoint_address(r["endpoint"]) == host["address"]
|
||||
}
|
||||
)
|
||||
self.catalog.remove(host["id"])
|
||||
return {"removed": True, "id": host["id"]}
|
||||
|
||||
Reference in New Issue
Block a user