| 1 |
"""AsusRouter Registry.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import threading |
| 6 |
from typing import Any |
| 7 |
|
| 8 |
from asusrouter.tools.types import ARCallableType |
| 9 |
|
| 10 |
|
| 11 |
class ARCallableRegistryBase: |
| 12 |
"""Simple, thread-safe registry mapping source classes -> named callables. |
| 13 |
|
| 14 |
- Modules register their functions explicitly. |
| 15 |
- Lookup resolves by class then MRO (most-specific first). |
| 16 |
""" |
| 17 |
|
| 18 |
def __init__(self) -> None: |
| 19 |
"""Initialize the registry.""" |
| 20 |
|
| 21 |
self._map: dict[type, dict[str, ARCallableType]] = {} |
| 22 |
self._lock = threading.RLock() |
| 23 |
|
| 24 |
def register(self, source_cls: type, **callables: ARCallableType) -> None: |
| 25 |
"""Register one or more named callables for `source_cls`.""" |
| 26 |
|
| 27 |
with self._lock: |
| 28 |
entry = self._map.setdefault(source_cls, {}) |
| 29 |
entry.update(callables) |
| 30 |
|
| 31 |
def unregister(self, source_cls: type) -> None: |
| 32 |
"""Remove all registrations for a source class.""" |
| 33 |
|
| 34 |
with self._lock: |
| 35 |
self._map.pop(source_cls, None) |
| 36 |
|
| 37 |
def clear(self) -> None: |
| 38 |
"""Clear all registrations.""" |
| 39 |
|
| 40 |
with self._lock: |
| 41 |
self._map.clear() |
| 42 |
|
| 43 |
def get_callable(self, source: Any, name: str) -> ARCallableType | None: |
| 44 |
"""Return the callable for `source` (instance or class) or None. |
| 45 |
|
| 46 |
Resolves by checking the exact class and then walking the MRO. |
| 47 |
""" |
| 48 |
|
| 49 |
cls = source if isinstance(source, type) else type(source) |
| 50 |
with self._lock: |
| 51 |
for base in getattr(cls, "__mro__", ()): |
| 52 |
entry = self._map.get(base) |
| 53 |
if entry and name in entry: |
| 54 |
return entry[name] |
| 55 |
return None |
| 56 |
|
| 57 |
def get_all_for(self, source: Any) -> dict[str, ARCallableType]: |
| 58 |
"""Return all resolved callables for `source` by name (MRO merged). |
| 59 |
|
| 60 |
More specific classes override less specific ones. |
| 61 |
""" |
| 62 |
|
| 63 |
cls = source if isinstance(source, type) else type(source) |
| 64 |
merged: dict[str, ARCallableType] = {} |
| 65 |
with self._lock: |
| 66 |
# walk MRO from base -> subclass so subclasses override |
| 67 |
for base in reversed(getattr(cls, "__mro__", ())): |
| 68 |
entry = self._map.get(base) |
| 69 |
if entry: |
| 70 |
merged.update(entry) |
| 71 |
return merged |
| 72 |
|
| 73 |
|
| 74 |
ARCallableRegistry: ARCallableRegistryBase = ARCallableRegistryBase() |