ForcePilot/backend/package/yuxi/channels/adapters/bluebubbles/conversation_bindings.py

36 lines
1.1 KiB
Python
Raw Normal View History

from __future__ import annotations
from typing import Any
class ConversationBindings:
MAX_ENTRIES = 2048
def __init__(self) -> None:
self._bindings: dict[str, dict[str, Any]] = {}
def bind(self, conversation_id: str, chat_guid: str, context: dict[str, Any]) -> None:
self._trim()
self._bindings[conversation_id] = {
"chat_guid": chat_guid,
"context": context,
}
def resolve(self, conversation_id: str) -> dict[str, Any] | None:
return self._bindings.get(conversation_id)
def resolve_by_chat_guid(self, chat_guid: str) -> str | None:
for conv_id, binding in self._bindings.items():
if binding.get("chat_guid") == chat_guid:
return conv_id
return None
def unbind(self, conversation_id: str) -> None:
self._bindings.pop(conversation_id, None)
def _trim(self) -> None:
if len(self._bindings) > self.MAX_ENTRIES:
oldest = sorted(self._bindings.keys())[: len(self._bindings) - self.MAX_ENTRIES]
for k in oldest:
del self._bindings[k]