registration_lifecycle.py 3.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. """Ownership leases for replaceable runtime registrations.
  2. The coordinator models registration *generations*, not just value identity: the same provider
  3. singleton may be registered again after an older ownership generation was unloaded.
  4. """
  5. from __future__ import annotations
  6. import threading
  7. from collections.abc import Callable, Hashable
  8. from contextlib import contextmanager
  9. from dataclasses import dataclass, field
  10. from typing import Any
  11. def same_registration(left: Any, right: Any) -> bool:
  12. """Compare opaque registry snapshots using identity only (element-wise for tuples)."""
  13. if isinstance(left, tuple) and isinstance(right, tuple):
  14. return len(left) == len(right) and all(same_registration(a, b) for a, b in zip(left, right))
  15. return left is right
  16. @dataclass
  17. class ReplacementLease:
  18. """One ownership generation in a replaceable registry slot."""
  19. coordinator: ReplacementCoordinator
  20. slot: Hashable
  21. current: Any
  22. previous: Any
  23. restore: Callable[[Any], bool]
  24. finalize: Callable[[], None] | None = None
  25. predecessor: ReplacementLease | None = None
  26. active: bool = field(default=True, init=False)
  27. def dispose(self) -> None:
  28. self.coordinator.dispose(self)
  29. class ReplacementCoordinator:
  30. """Link and remove registration generations in arbitrary unload order."""
  31. def __init__(self) -> None:
  32. self._active: dict[Hashable, list[ReplacementLease]] = {}
  33. self._lock = threading.RLock()
  34. @contextmanager
  35. def transaction(self):
  36. """Serialize a registry snapshot/write/acquire with lease disposal."""
  37. with self._lock:
  38. yield
  39. def acquire(self, slot: Hashable, *, current: Any, previous: Any, restore: Callable[[Any], bool],
  40. finalize: Callable[[], None] | None = None) -> ReplacementLease:
  41. """Attach a new live generation to the matching active predecessor."""
  42. with self._lock:
  43. leases = self._active.setdefault(slot, [])
  44. predecessor = next((c for c in reversed(leases) if c.active and same_registration(c.current, previous)), None)
  45. lease = ReplacementLease(self, slot, current, previous, restore, finalize, predecessor)
  46. leases.append(lease)
  47. return lease
  48. def dispose(self, lease: ReplacementLease) -> None:
  49. """Remove *lease*, restoring the nearest still-live predecessor.
  50. ``restore`` -> ``finalize`` -> slot pruning each run even when an earlier step raises.
  51. """
  52. with self._lock:
  53. if not lease.active:
  54. return
  55. leases = self._active.get(lease.slot, [])
  56. latest = next((c for c in reversed(leases) if c.active), None)
  57. lease.active = False
  58. # An older generation can share the exact object identity of a newer one; registry-level
  59. # CAS cannot tell them apart, so only the latest live generation may mutate the slot.
  60. try:
  61. try:
  62. if latest is lease:
  63. # Restore the nearest still-live predecessor, else the last dead generation's previous.
  64. replacement, predecessor = lease.previous, lease.predecessor
  65. while predecessor is not None and not predecessor.active:
  66. replacement, predecessor = predecessor.previous, predecessor.predecessor
  67. lease.restore(predecessor.current if predecessor is not None else replacement)
  68. finally:
  69. if lease.finalize is not None:
  70. lease.finalize()
  71. finally:
  72. live = [item for item in leases if item.active]
  73. if live:
  74. self._active[lease.slot] = live
  75. elif leases:
  76. self._active.pop(lease.slot, None)
  77. replacement_coordinator = ReplacementCoordinator()