plugin_utils.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """Thread-safe lazy singletons for plugin authors (stdlib-only).
  2. The ``if _client is None: _client = Expensive()`` footgun: two threads pass the guard, both
  3. build, the second leaks the first's connections. :func:`lazy_singleton` decorates a zero-arg
  4. accessor; :class:`SingletonSlot` is the manual slot when the instance depends on an argument.
  5. """
  6. from __future__ import annotations
  7. import functools
  8. import threading
  9. from typing import Callable, Generic, Optional, TypeVar
  10. __all__ = ["SingletonSlot", "lazy_singleton"]
  11. T = TypeVar("T")
  12. class SingletonSlot(Generic[T]):
  13. """Thread-safe lazy slot: caches the first successfully-built instance ("first config wins").
  14. The factory runs at most once under concurrent first calls; if it raises, nothing is cached
  15. and the next call retries. ``_slot.get(lambda: Honcho(**resolve(config)))``."""
  16. __slots__ = ("_lock", "_set", "_value")
  17. def __init__(self) -> None:
  18. self._lock = threading.Lock()
  19. self._value: Optional[T] = None
  20. self._set = False
  21. def get(self, factory: Callable[[], T]) -> T:
  22. # Fast path without the lock: a bool + ref read is atomic under the GIL.
  23. if self._set:
  24. return self._value # type: ignore[return-value]
  25. with self._lock:
  26. if self._set:
  27. return self._value # type: ignore[return-value]
  28. value = factory()
  29. self._value = value
  30. self._set = True
  31. return value
  32. def peek(self) -> Optional[T]:
  33. """Return the cached instance without building it (None if unset)."""
  34. return self._value if self._set else None
  35. def reset(self) -> None:
  36. """Drop the cached instance so the next ``get()`` rebuilds it."""
  37. with self._lock:
  38. self._value = None
  39. self._set = False
  40. def lazy_singleton(factory: Callable[[], T]) -> Callable[[], T]:
  41. """Wrap a zero-argument factory into a thread-safe lazy singleton accessor (factory runs once
  42. even under concurrent first calls; on raise the next call retries). ``.reset()`` drops it."""
  43. slot: SingletonSlot[T] = SingletonSlot()
  44. @functools.wraps(factory)
  45. def accessor() -> T:
  46. return slot.get(factory)
  47. accessor.reset = slot.reset # type: ignore[attr-defined]
  48. return accessor