registry.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import threading
  2. from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional
  3. # Optional import - OTel SDK may not be installed
  4. # Use Any as fallback type when OTel is not available
  5. if TYPE_CHECKING:
  6. try:
  7. from opentelemetry.metrics import Observation
  8. except ImportError:
  9. Observation = Any # type: ignore[misc]
  10. else:
  11. Observation = Any
  12. class ObservablesRegistry:
  13. """
  14. Global registry for storing callbacks for observable metrics.
  15. """
  16. def __init__(self, registry: Dict[str, List[Callable[[], List[Any]]]] = None):
  17. self._registry = registry or {}
  18. self._lock = threading.Lock()
  19. def register(self, name: str, callback: Callable[[], List[Any]]) -> None:
  20. """
  21. Register a callback for an observable metric.
  22. """
  23. with self._lock:
  24. self._registry.setdefault(name, []).append(callback)
  25. def get(self, name: str) -> List[Callable[[], List[Any]]]:
  26. """
  27. Get all callbacks for an observable metric.
  28. """
  29. with self._lock:
  30. return self._registry.get(name, [])
  31. def clear(self) -> None:
  32. """
  33. Clear the registry.
  34. """
  35. with self._lock:
  36. self._registry.clear()
  37. def __len__(self) -> int:
  38. """
  39. Get the number of registered callbacks.
  40. """
  41. return len(self._registry)
  42. # Global singleton instance
  43. _observables_registry_instance: Optional[ObservablesRegistry] = None
  44. def get_observables_registry_instance() -> ObservablesRegistry:
  45. """
  46. Get the global observables registry singleton instance.
  47. This is the Pythonic way to get the singleton instance.
  48. Returns:
  49. The global ObservablesRegistry singleton
  50. Example:
  51. >>>
  52. >>> registry = get_observables_registry_instance()
  53. >>> registry.register('my_metric', my_callback)
  54. """
  55. global _observables_registry_instance
  56. if _observables_registry_instance is None:
  57. _observables_registry_instance = ObservablesRegistry()
  58. return _observables_registry_instance