Files
hms-mediaengine/packages/protocol/hms_protocol/idempotency.py
T

38 lines
1.3 KiB
Python
Raw Normal View History

"""Idempotency-Registry für wiederholbare Commands (§6.2, §23.2)."""
from __future__ import annotations
from collections import OrderedDict
from typing import Any
class IdempotencyRegistry:
"""Merkt sich command_id → Ergebnis; Wiederholungen liefern dasselbe Ack."""
def __init__(self, capacity: int = 4096) -> None:
if capacity <= 0:
raise ValueError("capacity must be positive")
self._capacity = capacity
self._entries: OrderedDict[str, Any] = OrderedDict()
def register(self, command_id: str) -> bool:
"""False, wenn die command_id bereits bekannt ist (Duplikat)."""
if command_id in self._entries:
self._entries.move_to_end(command_id)
return False
self._entries[command_id] = None # Ergebnis folgt mit complete()
if len(self._entries) > self._capacity:
self._entries.popitem(last=False)
return True
def complete(self, command_id: str, result: Any) -> None:
if command_id in self._entries:
self._entries[command_id] = result
self._entries.move_to_end(command_id)
def result(self, command_id: str) -> Any | None:
return self._entries.get(command_id)
def __len__(self) -> int:
return len(self._entries)