1
0
This commit is contained in:
2024-01-15 20:20:10 +00:00
parent c75ea4ea9d
commit 38cd64ea9a
87 changed files with 3946 additions and 2040 deletions

View File

@@ -1,14 +1,16 @@
# -*- coding: utf-8 -*-
# django-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
from .decorators import register_method # noqa
from .exceptions import ( # noqa
# bthlabs-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
from .codecs import Codec, JSONCodec # noqa: F401
from .decorators import register_method # noqa: F401
from .exceptions import ( # noqa: F401
BaseJSONRPCError,
JSONRPCAccessDeniedError,
JSONRPCInternalError,
JSONRPCParseError,
JSONRPCSerializerError,
)
from .executor import Executor # noqa
from .serializer import JSONRPCSerializer # noqa
from .executor import Executor # noqa: F401
from .registry import MethodRegistry # noqa: F401
from .serializer import JSONRPCSerializer # noqa: F401
__version__ = '1.0.0'
__version__ = '1.1.0b1'

View File

@@ -0,0 +1,64 @@
# -*- coding: utf-8 -*-
# bthlabs-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
from __future__ import annotations
import abc
import json
import typing
class Codec(abc.ABC):
"""Base class for codecs."""
# pragma mark - Abstract public interface
@abc.abstractmethod
def decode(self, payload: str | bytes, **decoder_kwargs) -> typing.Any:
"""
Decode the *payload*. *decoder_kwargs* are implementation specific.
Subclasses must implement this method.
"""
...
@abc.abstractmethod
def encode(self, payload: typing.Any, **encoder_kwargs) -> str:
"""
Encode the *payload*. *encoder_kwargs* are implementation specific.
Subclasses must implement this method.
"""
...
@abc.abstractmethod
def get_content_type(self) -> str:
"""
Return the MIME type for the encoded content.
Subclasses must implement this method.
"""
...
class JSONCodec(Codec):
"""JSON codec"""
# pragma mark - Public interface
def decode(self, payload: str | bytes, **decoder_kwargs) -> typing.Any:
"""
Decode *payload* using :py:func:`json.loads`. *decoder_kwargs* will
be passed verbatim to the decode function.
"""
return json.loads(payload, **decoder_kwargs)
def encode(self, payload: typing.Any, **encoder_kwargs) -> str:
"""
Encode *payload* using :py:func:`json.dumps`. *encoder_kwargs* will
be passed verbatim to the encode function.
"""
return json.dumps(payload, **encoder_kwargs)
def get_content_type(self):
"""Returns ``application/json``."""
return 'application/json'

View File

@@ -1,12 +1,14 @@
# -*- coding: utf-8 -*-
# django-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
# bthlabs-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
from __future__ import annotations
import typing
from bthlabs_jsonrpc_core.registry import MethodRegistry
def register_method(method: str,
namespace: typing.Optional[str] = None,
namespace: str | None = None,
) -> typing.Callable:
"""
Registers the decorated function as JSONRPC *method* in *namespace*.
@@ -28,8 +30,8 @@ def register_method(method: str,
registry = MethodRegistry.shared_registry()
registry.register_method(namespace, method, handler)
handler.jsonrpc_method = method
handler.jsonrpc_namespace = namespace
handler.jsonrpc_method = method # type: ignore[attr-defined]
handler.jsonrpc_namespace = namespace # type: ignore[attr-defined]
return handler
return decorator

View File

@@ -1,5 +1,8 @@
# -*- coding: utf-8
# django-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
# bthlabs-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
from __future__ import annotations
class BaseJSONRPCError(Exception):
"""
Base class for JSONRPC exceptions.
@@ -16,6 +19,8 @@ class BaseJSONRPCError(Exception):
def __init__(self, data=None):
self.data = data
# pragma mark - Public interface
def to_rpc(self) -> dict:
"""Returns payload for :py:class:`JSONRPCSerializer`."""
result = {

View File

@@ -1,11 +1,13 @@
# -*- coding: utf-8 -*-
# django-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
from contextlib import contextmanager
from dataclasses import dataclass
import json
# bthlabs-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
from __future__ import annotations
import contextlib
import dataclasses
import logging
import typing
from bthlabs_jsonrpc_core.codecs import Codec, JSONCodec
from bthlabs_jsonrpc_core.exceptions import (
BaseJSONRPCError,
JSONRPCInternalError,
@@ -28,6 +30,9 @@ class Executor:
*namespace* will be used to look up called methods in the registry. If
omitted, it'll fall back to the default namespace.
*codec* will be used to deserialize the request payload. If omitted,
it'll fall back to :py:class:`JSONCodec`.
Example:
.. code-block:: python
@@ -51,7 +56,7 @@ class Executor:
# The serializer registry class to use for response serialization.
serializer = JSONRPCSerializer
@dataclass
@dataclasses.dataclass
class CallContext:
"""
The context of a single call.
@@ -72,7 +77,7 @@ class Executor:
kwargs: dict
#: Call result
result: typing.Optional[typing.Any] = None
result: typing.Any = None
@classmethod
def invalid_context(cls):
@@ -88,7 +93,7 @@ class Executor:
self.kwargs is not None,
))
@dataclass
@dataclasses.dataclass
class ExecuteContext:
"""
The context of an execute call.
@@ -100,13 +105,16 @@ class Executor:
results: list
#: The serializer instance.
serializer: typing.Optional[JSONRPCSerializer] = None
serializer: JSONRPCSerializer | None = None
def __init__(self,
namespace: str | None = None,
codec: Codec | None = None):
self.namespace = namespace or MethodRegistry.DEFAULT_NAMESPACE
self.codec = codec or JSONCodec()
# pragma mark - Private interface
def __init__(self, namespace=None):
self.namespace = namespace or MethodRegistry.DEFAULT_NAMESPACE
def get_internal_handler(self, method: str) -> typing.Callable:
"""
Returns the internal handler for *method* or raises
@@ -194,7 +202,7 @@ class Executor:
def process_results(self,
results: list,
) -> typing.Optional[typing.Union[list, dict]]:
) -> typing.Union[list, dict] | None:
"""
Post-processes the *results* and returns responses.
@@ -236,8 +244,10 @@ class Executor:
return responses
@contextmanager
def call_context(self, execute_context: ExecuteContext, call: dict):
@contextlib.contextmanager
def call_context(self,
execute_context: ExecuteContext,
call: dict) -> typing.Generator[CallContext, None, None]:
"""
The call context manager. Yields ``CallContext``, which can be
invalid invalid if there was en error processing the call.
@@ -263,7 +273,9 @@ class Executor:
error = exception
else:
LOGGER.error(
f'Error handling RPC method: {method}!',
'Unhandled exception when handling RPC method `%s`: %s',
method,
exception,
exc_info=exception,
)
error = JSONRPCInternalError(str(exception))
@@ -273,8 +285,8 @@ class Executor:
else:
execute_context.results.append((call, context.result))
@contextmanager
def execute_context(self):
@contextlib.contextmanager
def execute_context(self) -> typing.Generator[ExecuteContext, None, None]:
"""
The execution context. Yields ``ExecuteContext``.
@@ -297,7 +309,7 @@ class Executor:
# pragma mark - Public interface
def deserialize_data(self, data: bytes) -> typing.Any:
def deserialize_data(self, data: str | bytes) -> typing.Any:
"""
Deserializes *data* and returns the result.
@@ -306,9 +318,13 @@ class Executor:
response object conforms to the spec.
"""
try:
return json.loads(data)
return self.codec.decode(data)
except Exception as exception:
LOGGER.error('Error deserializing RPC call!', exc_info=exception)
LOGGER.error(
'Unhandled exception when deserializing RPC call: %s',
exception,
exc_info=exception,
)
raise JSONRPCParseError() from exception
def list_methods(self, *args, **kwargs) -> list[str]:
@@ -368,9 +384,7 @@ class Executor:
"""
pass
def execute(self,
payload: typing.Any,
) -> typing.Optional[JSONRPCSerializer]:
def execute(self, payload: typing.Any) -> JSONRPCSerializer | None:
"""
Executes the JSONRPC request in *payload*.

View File

@@ -0,0 +1,152 @@
# -*- coding: utf-8 -*-
# bthlabs-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
from __future__ import annotations
import datetime
import dataclasses
import typing
from jose import jwt
from jose.constants import ALGORITHMS
from jose.jwk import ( # noqa: F401
ECKey,
HMACKey,
RSAKey,
)
import pytz
from bthlabs_jsonrpc_core.codecs import Codec
@dataclasses.dataclass
class KeyPair:
"""
Key pair used to verify and sign JWTs.
For HMAC, both *decode_key* and *encode_key* should be `HMACKey` instances,
wrapping the respective secrets.
For RSA and ECDSA, *decode_key* must be a public key for signature
verification. *encode_key* must be a private key for signing.
"""
decode_key: ECKey | HMACKey | RSAKey
encode_key: ECKey | HMACKey | RSAKey
@dataclasses.dataclass
class TimeClaims:
"""Time claims container."""
iat: datetime.datetime
nbf: datetime.datetime | None
exp: datetime.datetime | None
def as_claims(self) -> dict:
"""
Return dict representation of the claims suitable for including in a
JWT.
"""
result = {
'iat': self.iat,
}
if self.nbf is not None:
result['nbf'] = self.nbf
if self.exp is not None:
result['exp'] = self.exp
return result
class JWTCodec(Codec):
"""
JWT codec. Uses keys specified in *key_pair* when decoding and encoding
tokens.
*algorithm* specifies the signature algorithm to use. Defaults to
:py:attr:`ALGORITHMS.HS256`.
*issuer* specifies the ``iss`` claim. Defaults to ``None`` for no issuer.
*ttl* specifies the token's TTL. It'll be used to generate the ``exp``
claim. Defaults to ``None`` for non-expiring token.
*include_nbf* specifies if the ``nbf`` claim should be added to the token.
"""
def __init__(self,
key_pair: KeyPair,
*,
algorithm: str = ALGORITHMS.HS256,
issuer: str | None = None,
ttl: datetime.timedelta | None = None,
include_nbf: bool = True):
super().__init__()
self.key_pair = key_pair
self.algorithm = algorithm
self.issuer = issuer
self.ttl = ttl
self.include_nbf = include_nbf
# pragma mark - Private interface
def get_time_claims(self) -> TimeClaims:
"""
Get time claims.
:meta: private
"""
now = datetime.datetime.now().astimezone(pytz.utc)
exp: datetime.datetime | None = None
if self.ttl is not None:
exp = now + self.ttl
return TimeClaims(
iat=now,
nbf=now if self.include_nbf is True else None,
exp=exp,
)
# pragma mark - Public interface
def decode(self, payload: str | bytes, **decoder_kwargs) -> typing.Any:
"""
Decode payload using :py:func:`jose.jwt.decode`. *decoder_kwargs* will
be passed verbatim to the decode function.
Consult *python-jose* documentation for more information.
"""
decoded_payload = jwt.decode(
payload,
self.key_pair.decode_key,
algorithms=[self.algorithm],
**decoder_kwargs,
)
return decoded_payload['jsonrpc']
def encode(self, payload: typing.Any, **encoder_kwargs) -> str:
"""
Encode payload using :py:func:`jose.jwt.encode`. *encoder_kwargs* will
be passed verbatim to the encode function.
Consult *python-jose* documentation for more information.
"""
claims: dict = {
**self.get_time_claims().as_claims(),
'jsonrpc': payload,
}
if self.issuer is not None:
claims['iss'] = self.issuer
return jwt.encode(
claims,
self.key_pair.encode_key,
algorithm=self.algorithm,
**encoder_kwargs,
)
def get_content_type(self) -> str:
"""Returns ``application/jwt``."""
return 'application/jwt'

View File

@@ -0,0 +1,3 @@
# -*- coding: utf-8 -*-
# bthlabs-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
from .fixtures import * # noqa: F401,F403

View File

@@ -0,0 +1,40 @@
# -*- coding: utf-8 -*-
# bthlabs-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
# type: ignore
from __future__ import annotations
from unittest import mock
import pytest
from bthlabs_jsonrpc_core.codecs import Codec
@pytest.fixture
def fake_custom_codec() -> mock.Mock:
return mock.Mock(spec=Codec)
@pytest.fixture
def single_call() -> dict:
return {
'jsonrpc': '2.0',
'id': 'test',
'method': 'system.list_methods',
}
@pytest.fixture
def batch_calls() -> list:
return [
{
'jsonrpc': '2.0',
'id': 'test',
'method': 'system.list_methods',
},
{
'jsonrpc': '2.0',
'id': 'test2',
'method': 'system.list_methods',
},
]

View File

@@ -1,28 +1,51 @@
# -*- coding: utf-8 -*-
# django-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
class MethodRegistry:
INSTANCE = None
DEFAULT_NAMESPACE = 'jsonrpc'
# bthlabs-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
from __future__ import annotations
def __init__(self, *args, **kwargs):
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, *args, **kwargs):
def shared_registry(cls: type[MethodRegistry]) -> MethodRegistry:
"""Return the shared instance."""
if cls.INSTANCE is None:
cls.INSTANCE = cls(*args, **kwargs)
cls.INSTANCE = cls()
return cls.INSTANCE
def register_method(self, namespace, method, handler):
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):
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):
def get_handler(self, namespace, method) -> typing.Callable:
"""Returns the handler for *method* in *namespace*."""
return self.registry.get(namespace, {}).get(method, None)

View File

@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-
# django-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
# bthlabs-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
from __future__ import annotations
import datetime
import decimal
import typing
@@ -62,6 +64,8 @@ class JSONRPCSerializer:
def __init__(self, data):
self._data = data
# pragma mark - Private interface
def is_simple_value(self, value: typing.Any) -> bool:
"""
Returns ``True`` if *value* is a simple value.
@@ -172,6 +176,8 @@ class JSONRPCSerializer:
return value
# pragma mark - Public interface
@property
def data(self) -> typing.Any:
"""The serialized data."""