Skip to content

Commit

Permalink
Merge pull request #87 from dapper91/refactoring
Browse files Browse the repository at this point in the history
- added MaybeSet generic type to eliminate boilerplate typing.
  • Loading branch information
dapper91 authored Jul 11, 2022
2 parents c72bb0d + a78dcc2 commit 0f21f4d
Show file tree
Hide file tree
Showing 13 changed files with 215 additions and 210 deletions.
4 changes: 2 additions & 2 deletions pjrpc/client/backend/kombu.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import pjrpc
from pjrpc.client import AbstractClient
from pjrpc.common import UNSET, UnsetType
from pjrpc.common import UNSET, MaybeSet, UnsetType

logger = logging.getLogger(__package__)

Expand Down Expand Up @@ -98,7 +98,7 @@ def _request(self, request_text: str, is_notification: bool = False, **kwargs: A
**kwargs,
)

response: Optional[Union[UnsetType, str, Exception]] = UNSET
response: MaybeSet[Union[None, str, Exception]] = UNSET

def on_response(message: kombu.Message) -> None:
nonlocal response
Expand Down
10 changes: 5 additions & 5 deletions pjrpc/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from pjrpc import AbstractRequest, AbstractResponse, BatchRequest, BatchResponse, Request, Response, common
from pjrpc.client import retry
from pjrpc.common import UNSET, UnsetType, exceptions, generators, v20
from pjrpc.common import UNSET, MaybeSet, UnsetType, exceptions, generators, v20
from pjrpc.common.typedefs import JsonRpcRequestId, MethodType

from .tracer import Tracer
Expand Down Expand Up @@ -457,7 +457,7 @@ def send(
self,
request: Request,
_trace_ctx: SimpleNamespace = SimpleNamespace(),
_retry_strategy: Union[UnsetType, retry.RetryStrategy] = UNSET,
_retry_strategy: MaybeSet[retry.RetryStrategy] = UNSET,
**kwargs: Any,
) -> Optional[Response]:
"""
Expand Down Expand Up @@ -515,7 +515,7 @@ def retried(method: Callable[..., Any]) -> Callable[..., Any]:
def wrapper(
self: 'AbstractClient',
request: AbstractRequest,
_retry_strategy: Union[UnsetType, retry.RetryStrategy] = UNSET,
_retry_strategy: MaybeSet[retry.RetryStrategy] = UNSET,
**kwargs: Any,
) -> Optional[AbstractResponse]:
"""
Expand Down Expand Up @@ -589,7 +589,7 @@ async def send(
self,
request: Request,
_trace_ctx: SimpleNamespace = SimpleNamespace(),
_retry_strategy: Union[UnsetType, retry.RetryStrategy] = UNSET,
_retry_strategy: MaybeSet[retry.RetryStrategy] = UNSET,
**kwargs: Any,
) -> Optional[Response]:
"""
Expand Down Expand Up @@ -647,7 +647,7 @@ def retried(method: Callable[..., Awaitable[Any]]) -> Callable[..., Any]:
async def wrapper(
self: 'AbstractClient',
request: AbstractRequest,
_retry_strategy: Union[UnsetType, retry.RetryStrategy] = UNSET,
_retry_strategy: MaybeSet[retry.RetryStrategy] = UNSET,
**kwargs: Any,
) -> Optional[AbstractResponse]:
"""
Expand Down
10 changes: 5 additions & 5 deletions pjrpc/client/integrations/pytest.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

import pjrpc
from pjrpc import Response
from pjrpc.common import UNSET, UnsetType
from pjrpc.common import UNSET, MaybeSet
from pjrpc.common.typedefs import JsonRpcParams, JsonRpcRequestId

CallType = Dict[Tuple[str, str], unittest.mock.Mock]
Expand Down Expand Up @@ -75,8 +75,8 @@ def add(
self,
endpoint: str,
method_name: str,
result: UnsetType = UNSET,
error: UnsetType = UNSET,
result: MaybeSet[Any] = UNSET,
error: MaybeSet[Any] = UNSET,
id: Optional[JsonRpcRequestId] = None,
version: str = '2.0',
once: bool = False,
Expand All @@ -102,8 +102,8 @@ def replace(
self,
endpoint: str,
method_name: str,
result: UnsetType = UNSET,
error: UnsetType = UNSET,
result: MaybeSet[Any] = UNSET,
error: MaybeSet[Any] = UNSET,
id: Optional[JsonRpcRequestId] = None,
version: str = '2.0',
once: bool = False,
Expand Down
3 changes: 2 additions & 1 deletion pjrpc/common/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"""

from . import generators, typedefs
from .common import UNSET, JSONEncoder, UnsetType
from .common import UNSET, JSONEncoder, MaybeSet, UnsetType
from .v20 import AbstractRequest, AbstractResponse, BatchRequest, BatchResponse, Request, Response

DEFAULT_CONTENT_TYPE = 'application/json'
Expand Down Expand Up @@ -36,6 +36,7 @@ def set_default_content_type(content_type: str) -> None:
'BatchResponse',
'UNSET',
'UnsetType',
'MaybeSet',
'JSONEncoder',
'DEFAULT_CONTENT_TYPE',
'REQUEST_CONTENT_TYPES',
Expand Down
7 changes: 5 additions & 2 deletions pjrpc/common/common.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import json
import sys
from typing import Any
from typing import Any, TypeVar, Union

if sys.version_info >= (3, 8):
from typing import Literal
Expand Down Expand Up @@ -34,7 +34,10 @@ def __deepcopy__(self, memo: dict) -> 'UnsetType':
return self


UNSET = UnsetType()
UNSET: UnsetType = UnsetType()

MaybeSetType = TypeVar('MaybeSetType')
MaybeSet = Union[UnsetType, MaybeSetType]


class JSONEncoder(json.JSONEncoder):
Expand Down
6 changes: 3 additions & 3 deletions pjrpc/common/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
"""

import typing
from typing import Any, Dict, Optional, Type, Union
from typing import Any, Dict, Optional, Type

from pjrpc.common.typedefs import Json

from .common import UNSET, UnsetType
from .common import UNSET, MaybeSet


class BaseError(Exception):
Expand Down Expand Up @@ -97,7 +97,7 @@ def from_json(cls, json_data: 'Json') -> 'JsonRpcError':
def get_error_cls(cls, code: int, default: Type['JsonRpcError']) -> Type['JsonRpcError']:
return type(cls).__errors_mapping__.get(code, default)

def __init__(self, code: Optional[int] = None, message: Optional[str] = None, data: Union[UnsetType, Any] = UNSET):
def __init__(self, code: Optional[int] = None, message: Optional[str] = None, data: MaybeSet[Any] = UNSET):
assert code or self.code, "code is not provided"
assert message or self.message, "message is not provided"

Expand Down
16 changes: 8 additions & 8 deletions pjrpc/common/v20.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
import abc
import itertools as it
import operator as op
from typing import Any, Dict, Iterable, Iterator, List, Optional, Set, Tuple, Type, Union
from typing import Any, Dict, Iterable, Iterator, List, Optional, Set, Tuple, Type

from pjrpc.common.typedefs import Json, JsonRpcParams, JsonRpcRequestId

from .common import UNSET, UnsetType
from .common import UNSET, MaybeSet, UnsetType
from .exceptions import DeserializationError, IdentityError, JsonRpcError


Expand Down Expand Up @@ -75,7 +75,7 @@ def result(self) -> Any:

@property
@abc.abstractmethod
def error(self) -> Union[UnsetType, JsonRpcError]:
def error(self) -> MaybeSet[JsonRpcError]:
pass

@property
Expand Down Expand Up @@ -157,8 +157,8 @@ def from_json(cls, json_data: Json, error_cls: Type[JsonRpcError] = JsonRpcError
def __init__(
self,
id: Optional[JsonRpcRequestId],
result: Union[UnsetType, Any] = UNSET,
error: Union[UnsetType, JsonRpcError] = UNSET,
result: MaybeSet[Any] = UNSET,
error: MaybeSet[JsonRpcError] = UNSET,
):
assert result is not UNSET or error is not UNSET, "result or error argument must be provided"
assert result is UNSET or error is UNSET, "result and error arguments are mutually exclusive"
Expand Down Expand Up @@ -205,7 +205,7 @@ def result(self) -> Any:
return self._result

@property
def error(self) -> Union[UnsetType, JsonRpcError]:
def error(self) -> MaybeSet[JsonRpcError]:
"""
Response error. If the response has succeeded returns :py:data:`pjrpc.common.common.UNSET`.
"""
Expand Down Expand Up @@ -437,7 +437,7 @@ def from_json(cls, json_data: Json, error_cls: Type[JsonRpcError] = JsonRpcError

return cls(*(Response.from_json(item) for item in json_data))

def __init__(self, *responses: Response, error: Union[UnsetType, JsonRpcError] = UNSET, strict: bool = True):
def __init__(self, *responses: Response, error: MaybeSet[JsonRpcError] = UNSET, strict: bool = True):
self._responses: List[Response] = []
self._ids: Set[JsonRpcRequestId] = set()
self._error = error
Expand Down Expand Up @@ -479,7 +479,7 @@ def __eq__(self, other: Any) -> bool:
)

@property
def error(self) -> Union[UnsetType, JsonRpcError]:
def error(self) -> MaybeSet[JsonRpcError]:
"""
Response error. If the response has succeeded returns :py:data:`pjrpc.common.common.UNSET`.
"""
Expand Down
19 changes: 10 additions & 9 deletions pjrpc/server/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
from typing import Type, Union, ValuesView, cast

import pjrpc
from pjrpc.common import UNSET, AbstractResponse, BatchRequest, BatchResponse, Request, Response, UnsetType, v20
from pjrpc.common import UNSET, AbstractResponse, BatchRequest, BatchResponse, MaybeSet, Request, Response, UnsetType
from pjrpc.common import v20
from pjrpc.common.typedefs import JsonRpcParams, MethodType
from pjrpc.server import utils
from pjrpc.server.typedefs import AsyncErrorHandlerType, AsyncMiddlewareType, ErrorHandlerType, MiddlewareType
Expand Down Expand Up @@ -382,7 +383,7 @@ def dispatch(self, request_text: str, context: Optional[Any] = None) -> Optional

logger.getChild('request').debug("request received: %s", request_text)

response: Union[AbstractResponse, UnsetType]
response: MaybeSet[AbstractResponse]
try:
request_json = self._json_loader(request_text, cls=self._json_decoder)
request: Union[Request, BatchRequest]
Expand Down Expand Up @@ -416,9 +417,9 @@ def dispatch(self, request_text: str, context: Optional[Any] = None) -> Optional

return None

def _handle_request(self, request: Request, context: Optional[Any]) -> Union[UnsetType, Response]:
def _handle_request(self, request: Request, context: Optional[Any]) -> MaybeSet[Response]:
try:
HandlerType = Callable[[Request, Optional[Any]], Union[UnsetType, Response]]
HandlerType = Callable[[Request, Optional[Any]], MaybeSet[Response]]
handler: HandlerType = self._handle_rpc_request

for middleware in reversed(self._middlewares):
Expand All @@ -442,7 +443,7 @@ def _handle_request(self, request: Request, context: Optional[Any]) -> Union[Uns

return self._response_class(id=request.id, error=error)

def _handle_rpc_request(self, request: Request, context: Optional[Any]) -> Union[UnsetType, Response]:
def _handle_rpc_request(self, request: Request, context: Optional[Any]) -> MaybeSet[Response]:
result = self._handle_rpc_method(request.method, request.params, context)
if request.id is None:
return UNSET
Expand Down Expand Up @@ -518,7 +519,7 @@ async def dispatch(self, request_text: str, context: Optional[Any] = None) -> Op

logger.getChild('request').debug("request received: %s", request_text)

response: Union[AbstractResponse, UnsetType]
response: MaybeSet[AbstractResponse]
try:
request_json = self._json_loader(request_text, cls=self._json_decoder)
request: Union[Request, BatchRequest]
Expand Down Expand Up @@ -554,9 +555,9 @@ async def dispatch(self, request_text: str, context: Optional[Any] = None) -> Op

return None

async def _handle_request(self, request: Request, context: Optional[Any]) -> Union[UnsetType, Response]:
async def _handle_request(self, request: Request, context: Optional[Any]) -> MaybeSet[Response]:
try:
HandlerType = Callable[[Request, Optional[Any]], Awaitable[Union[UnsetType, Response]]]
HandlerType = Callable[[Request, Optional[Any]], Awaitable[MaybeSet[Response]]]
handler: HandlerType = self._handle_rpc_request

for middleware in reversed(self._middlewares):
Expand All @@ -580,7 +581,7 @@ async def _handle_request(self, request: Request, context: Optional[Any]) -> Uni

return self._response_class(id=request.id, error=error)

async def _handle_rpc_request(self, request: Request, context: Optional[Any]) -> Union[UnsetType, Response]:
async def _handle_rpc_request(self, request: Request, context: Optional[Any]) -> MaybeSet[Response]:
result = await self._handle_rpc_method(request.method, request.params, context)
if request.id is None:
return UNSET
Expand Down
Loading

0 comments on commit 0f21f4d

Please sign in to comment.