Files
NODEDC_MISSION_CORE/src/k1link/network/speedtest.py
T

198 lines
7.1 KiB
Python

"""One local operator measurement, bounded RAM receipts, existing VPS authority."""
import copy
import threading
import time
from contextlib import suppress
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
from k1link.fleet.librespeed import LibreSpeed
from .speed_measure import measure
from .speed_transport import SpeedTransport
Document = dict[str, Any]
ACTIVE = {"queued", "applying", "cancelling"}
class CoreSpeedtest:
def __init__(self, root: Path):
self.store = LibreSpeed(root)
self.lock = threading.RLock()
self.receipts: dict[str, Document] = {}
self.cancelled = threading.Event()
self.client: SpeedTransport | None = None
self.worker: threading.Thread | None = None
self.expiry: threading.Timer | None = None
self.closed = False
def _prune(self) -> None:
now = time.time()
self.receipts = {
key: row
for key, row in self.receipts.items()
if row["expires_at"] > now or row["state"] in ACTIVE
}
def snapshot(self) -> Document:
with self.lock:
self._prune()
return {"receipt": copy.deepcopy(next(reversed(self.receipts.values()), None))}
def start(self, operation: str, server: str, name: str) -> Document:
with self.lock:
self._prune()
if self.closed:
raise ValueError("Служба замеров останавливается.")
if operation in self.receipts:
row = self.receipts[operation]
if row["server_id"] != server:
raise ValueError("Этот запрос уже относится к другому VPS.")
return copy.deepcopy(row)
if self.worker and self.worker.is_alive():
raise ValueError("Дождитесь завершения текущего замера.")
self.store.find(server) # Only already-admitted services, never a browser-supplied URL.
self.cancelled.clear()
self.client = None
midnight = (
datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
+ timedelta(days=1)
).timestamp()
self.receipts[operation] = dict(
operation_id=operation,
server_id=server,
server_name=name,
state="queued",
expires_at=min(time.time() + 600, midnight),
)
while len(self.receipts) > 16:
del self.receipts[next(iter(self.receipts))]
self.worker = threading.Thread(
target=self._run, args=(operation, server), name="core-speedtest", daemon=True
)
self.worker.start()
return copy.deepcopy(self.receipts[operation])
def cancel(self, operation: str) -> Document:
with self.lock:
self._prune()
row = self.receipts.get(operation)
if not row:
raise ValueError("Замер не найден или срок результата истёк.")
if row["state"] in ACTIVE:
row["state"] = "cancelling"
self.cancelled.set()
if self.client:
self.client.stop()
return copy.deepcopy(row)
def _run(self, operation: str, server: str) -> None:
measurement: Document = dict(
phase="latency",
server_id=server,
interface="",
started_at=int(time.time()),
download_bps=0,
upload_bps=0,
latency_ms=0,
jitter_ms=0,
)
timed_out = threading.Event()
client: SpeedTransport | None = None
def report(update: Document) -> None:
with self.lock:
measurement.update(update)
row = self.receipts[operation]
if row["state"] != "cancelling":
row["state"] = "applying"
row["measurement"] = dict(measurement)
def timeout() -> None:
timed_out.set()
with self.lock:
if self.client:
self.client.stop()
deadline = threading.Timer(80, timeout)
deadline.daemon = True
deadline.start()
try:
grant = self.store.lease(server, operation, system_route=True)
deadline.cancel()
deadline = threading.Timer(
max(
0,
min(
80 - (time.time() - measurement["started_at"]),
grant["expires_at"] - time.time(),
),
),
timeout,
)
deadline.daemon = True
deadline.start()
client = SpeedTransport(grant)
with self.lock:
self.client = client
if self.cancelled.is_set() or timed_out.is_set():
client.stop()
client.check()
result = measure(client, report)
client.check()
measurement.update({**result, "phase": "complete"})
except Exception:
report(
{
"phase": "cancelled" if self.cancelled.is_set() else "error",
"error": "deadline_exceeded" if timed_out.is_set() else "measurement_failed",
}
)
finally:
deadline.cancel()
if client:
client.stop()
# Also closes a lease when its acquisition reply was lost. Never revoke while streaming.
with suppress(Exception):
self.store.cancel(server, operation, system_route=True)
with self.lock:
if self.cancelled.is_set():
measurement["phase"] = "cancelled"
measurement["finished_at"] = int(time.time())
row = self.receipts[operation]
row.update(
state="error" if measurement["phase"] == "error" else "complete",
measurement=dict(measurement),
)
self.client = None
if self.expiry:
self.expiry.cancel()
if self.closed:
self.receipts.clear()
else:
self.expiry = threading.Timer(
max(0, row["expires_at"] - time.time()), self.expire
)
self.expiry.daemon = True
self.expiry.start()
def expire(self) -> None:
with self.lock:
self._prune()
def close(self) -> None:
with self.lock:
self.closed = True
self.cancelled.set()
if self.client:
self.client.stop()
if self.worker:
self.worker.join(timeout=20)
with self.lock:
if self.expiry:
self.expiry.cancel()
if not self.worker or not self.worker.is_alive():
self.receipts.clear()