52 lines
1.5 KiB
Python
52 lines
1.5 KiB
Python
# -*- coding: utf-8 -*-
|
|
# bthlabs-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
|
|
from __future__ import annotations
|
|
|
|
import typing
|
|
|
|
|
|
class MethodRegistry:
|
|
"""
|
|
The method registry. Maps method to handler within a namespace.
|
|
|
|
This class is a singleton. Use :py:meth:`MethodRegistry.shared_instance`
|
|
to get the shared instance.
|
|
"""
|
|
|
|
INSTANCE: MethodRegistry | None = None
|
|
|
|
#: Default namespace
|
|
DEFAULT_NAMESPACE: str = 'jsonrpc'
|
|
|
|
def __init__(self):
|
|
self.registry = {}
|
|
self.registry[self.DEFAULT_NAMESPACE] = {}
|
|
|
|
# pragma mark - Public interface
|
|
|
|
@classmethod
|
|
def shared_registry(cls: type[MethodRegistry]) -> MethodRegistry:
|
|
"""Return the shared instance."""
|
|
if cls.INSTANCE is None:
|
|
cls.INSTANCE = cls()
|
|
|
|
return cls.INSTANCE
|
|
|
|
def register_method(self,
|
|
namespace: str,
|
|
method: str,
|
|
handler: typing.Callable):
|
|
"""Register a *method* with *handler* in a *namespace*."""
|
|
if namespace not in self.registry:
|
|
self.registry[namespace] = {}
|
|
|
|
self.registry[namespace][method] = handler
|
|
|
|
def get_methods(self, namespace) -> list[str]:
|
|
"""Returns list of methods in a *namespace*."""
|
|
return self.registry.get(namespace, {}).keys()
|
|
|
|
def get_handler(self, namespace, method) -> typing.Callable:
|
|
"""Returns the handler for *method* in *namespace*."""
|
|
return self.registry.get(namespace, {}).get(method, None)
|