Add firmware and extension catalogues, configuration transactions, sample review and QML diagnostics. Preserve explicit authority, bounded retries and stop recovery in motor transport.
38 lines
1.6 KiB
Python
38 lines
1.6 KiB
Python
"""Bounded snapshots, separate from durable configuration backups and write receipts."""
|
|
from collections import OrderedDict
|
|
import json
|
|
import time
|
|
|
|
SNAPSHOT_ACTIONS = frozenset({"vesc.tools.read", "vesc.terminal.read", "vesc.firmware.status", "vesc.configuration.read", "vesc.configuration.preview", "vesc.diagnostics.read"})
|
|
EXPIRED = {"state": "error", "error": "Снимок больше не хранится. Прочитайте данные заново."}
|
|
|
|
|
|
class ReadCache:
|
|
def __init__(self, *, count=8, bytes_limit=8 * 1024**2, ttl=600, clock=time.monotonic):
|
|
self.items = OrderedDict()
|
|
self.count, self.bytes_limit, self.ttl, self.clock = count, bytes_limit, ttl, clock
|
|
self.bytes = 0
|
|
|
|
def prune(self):
|
|
for key, (at, size, _) in list(self.items.items()):
|
|
if self.clock() - at >= self.ttl:
|
|
del self.items[key]
|
|
self.bytes -= size
|
|
|
|
def put(self, key, receipt):
|
|
raw = json.dumps(receipt, ensure_ascii=False, allow_nan=False).encode()
|
|
if len(raw) > self.bytes_limit:
|
|
raise ValueError("Read snapshot exceeds cache bound")
|
|
self.prune()
|
|
if key in self.items:
|
|
self.bytes -= self.items.pop(key)[1]
|
|
while self.items and (len(self.items) >= self.count or self.bytes + len(raw) > self.bytes_limit):
|
|
self.bytes -= self.items.popitem(last=False)[1][1]
|
|
self.items[key] = (self.clock(), len(raw), raw)
|
|
self.bytes += len(raw)
|
|
|
|
def get(self, key):
|
|
self.prune()
|
|
entry = self.items.get(key)
|
|
return json.loads(entry[2]) if entry else dict(EXPIRED)
|