cache.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """Local caches for Atlas."""
  2. from __future__ import annotations
  3. from collections import OrderedDict
  4. from typing import Iterable, Optional
  5. from app.models import AtlasEntity
  6. class EntityCache:
  7. def __init__(self, max_entries: int = 512):
  8. self.max_entries = max_entries
  9. self._data: OrderedDict[str, AtlasEntity] = OrderedDict()
  10. def _normalize_token(self, token: str | None) -> str:
  11. return str(token or "").strip().lower()
  12. def get(self, token: str | None) -> Optional[AtlasEntity]:
  13. key = self._normalize_token(token)
  14. if not key:
  15. return None
  16. entity = self._data.get(key)
  17. if entity is not None:
  18. self._data.move_to_end(key)
  19. return entity
  20. def store(self, entity: AtlasEntity, extra_tokens: Iterable[str] | None = None) -> None:
  21. tokens = set(extra_tokens or [])
  22. tokens.add(entity.canonical_label)
  23. tokens.add(entity.atlas_id)
  24. for alias in entity.aliases:
  25. tokens.add(alias.label)
  26. mid = entity.active_identifier("mid")
  27. if mid:
  28. tokens.add(mid)
  29. for token in tokens:
  30. key = self._normalize_token(token)
  31. if not key:
  32. continue
  33. self._data[key] = entity
  34. self._data.move_to_end(key)
  35. while len(self._data) > self.max_entries:
  36. self._data.popitem(last=False)