Skip to content

Commit

Permalink
Autoformat all files using ruff
Browse files Browse the repository at this point in the history
Signed-off-by: Bernd Verst <[email protected]>
  • Loading branch information
berndverst committed Jan 18, 2024
1 parent 9bf91ca commit 8f51088
Show file tree
Hide file tree
Showing 139 changed files with 4,646 additions and 3,936 deletions.
16 changes: 8 additions & 8 deletions dapr/actor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@


__all__ = [
'ActorInterface',
'ActorProxy',
'ActorProxyFactory',
'ActorId',
'Actor',
'ActorRuntime',
'Remindable',
'actormethod',
"ActorInterface",
"ActorProxy",
"ActorProxyFactory",
"ActorId",
"Actor",
"ActorRuntime",
"Remindable",
"actormethod",
]
3 changes: 3 additions & 0 deletions dapr/actor/actor_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ async def do_actor_method1(self, param):
async def do_actor_method2(self, param):
...
"""

...


Expand All @@ -51,8 +52,10 @@ async def do_actor_call(self, param):
Args:
name (str, optional): the name of actor method.
"""

def wrapper(funcobj):
funcobj.__actormethod__ = name
funcobj.__isabstractmethod__ = True
return funcobj

return wrapper
71 changes: 42 additions & 29 deletions dapr/actor/client/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,17 @@
from dapr.conf import settings

# Actor factory Callable type hint.
ACTOR_FACTORY_CALLBACK = Callable[[ActorInterface, str, str], 'ActorProxy']
ACTOR_FACTORY_CALLBACK = Callable[[ActorInterface, str, str], "ActorProxy"]


class ActorFactoryBase(ABC):
@abstractmethod
def create(
self, actor_type: str, actor_id: ActorId,
actor_interface: Optional[Type[ActorInterface]] = None) -> 'ActorProxy':
self,
actor_type: str,
actor_id: ActorId,
actor_interface: Optional[Type[ActorInterface]] = None,
) -> "ActorProxy":
...


Expand All @@ -44,32 +47,36 @@ class ActorProxyFactory(ActorFactoryBase):
"""

def __init__(
self,
message_serializer=DefaultJSONSerializer(),
http_timeout_seconds: int = settings.DAPR_HTTP_TIMEOUT_SECONDS):
self,
message_serializer=DefaultJSONSerializer(),
http_timeout_seconds: int = settings.DAPR_HTTP_TIMEOUT_SECONDS,
):
# TODO: support serializer for state store later
self._dapr_client = DaprActorHttpClient(message_serializer, timeout=http_timeout_seconds)
self._message_serializer = message_serializer

def create(
self, actor_type: str, actor_id: ActorId,
actor_interface: Optional[Type[ActorInterface]] = None) -> 'ActorProxy':
self,
actor_type: str,
actor_id: ActorId,
actor_interface: Optional[Type[ActorInterface]] = None,
) -> "ActorProxy":
return ActorProxy(
self._dapr_client, actor_type, actor_id,
actor_interface, self._message_serializer)
self._dapr_client, actor_type, actor_id, actor_interface, self._message_serializer
)


class CallableProxy:
def __init__(
self, proxy: 'ActorProxy', attr_call_type: Dict[str, Any],
message_serializer: Serializer):
self, proxy: "ActorProxy", attr_call_type: Dict[str, Any], message_serializer: Serializer
):
self._proxy = proxy
self._attr_call_type = attr_call_type
self._message_serializer = message_serializer

async def __call__(self, *args, **kwargs) -> Any:
if len(args) > 1:
raise ValueError('does not support multiple arguments')
raise ValueError("does not support multiple arguments")

bytes_data = None
if len(args) > 0:
Expand All @@ -78,9 +85,9 @@ async def __call__(self, *args, **kwargs) -> Any:
else:
bytes_data = self._message_serializer.serialize(args[0])

rtnval = await self._proxy.invoke_method(self._attr_call_type['actor_method'], bytes_data)
rtnval = await self._proxy.invoke_method(self._attr_call_type["actor_method"], bytes_data)

return self._message_serializer.deserialize(rtnval, self._attr_call_type['return_types'])
return self._message_serializer.deserialize(rtnval, self._attr_call_type["return_types"])


class ActorProxy:
Expand All @@ -94,11 +101,13 @@ class ActorProxy:
_default_proxy_factory = ActorProxyFactory()

def __init__(
self, client: DaprActorClientBase,
actor_type: str,
actor_id: ActorId,
actor_interface: Optional[Type[ActorInterface]],
message_serializer: Serializer):
self,
client: DaprActorClientBase,
actor_type: str,
actor_id: ActorId,
actor_interface: Optional[Type[ActorInterface]],
message_serializer: Serializer,
):
self._dapr_client = client
self._actor_id = actor_id
self._actor_type = actor_type
Expand All @@ -120,10 +129,12 @@ def actor_type(self) -> str:

@classmethod
def create(
cls,
actor_type: str, actor_id: ActorId,
actor_interface: Optional[Type[ActorInterface]] = None,
actor_proxy_factory: Optional[ActorFactoryBase] = None) -> 'ActorProxy':
cls,
actor_type: str,
actor_id: ActorId,
actor_interface: Optional[Type[ActorInterface]] = None,
actor_proxy_factory: Optional[ActorFactoryBase] = None,
) -> "ActorProxy":
"""Creates ActorProxy client to call actor.
Args:
Expand Down Expand Up @@ -157,10 +168,11 @@ async def invoke_method(self, method: str, raw_body: Optional[bytes] = None) ->
"""

if raw_body is not None and not isinstance(raw_body, bytes):
raise ValueError(f'raw_body {type(raw_body)} is not bytes type')
raise ValueError(f"raw_body {type(raw_body)} is not bytes type")

return await self._dapr_client.invoke_method(
self._actor_type, str(self._actor_id), method, raw_body)
self._actor_type, str(self._actor_id), method, raw_body
)

def __getattr__(self, name: str) -> CallableProxy:
"""Enables RPC style actor method invocation.
Expand All @@ -177,17 +189,18 @@ def __getattr__(self, name: str) -> CallableProxy:
AttributeError: method is not defined in Actor interface.
"""
if not self._actor_interface:
raise ValueError('actor_interface is not set. use invoke method.')
raise ValueError("actor_interface is not set. use invoke method.")

if name not in self._dispatchable_attr:
get_dispatchable_attrs_from_interface(self._actor_interface, self._dispatchable_attr)

attr_call_type = self._dispatchable_attr.get(name)
if attr_call_type is None:
raise AttributeError(f'{self._actor_interface.__class__} has no attribute {name}')
raise AttributeError(f"{self._actor_interface.__class__} has no attribute {name}")

if name not in self._callable_proxies:
self._callable_proxies[name] = CallableProxy(
self, attr_call_type, self._message_serializer)
self, attr_call_type, self._message_serializer
)

return self._callable_proxies[name]
1 change: 1 addition & 0 deletions dapr/actor/runtime/_call_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ class ActorCallType(Enum):
:class:`ActorMethodContext` includes :class:`ActorCallType` passing to
:meth:`Actor._on_pre_actor_method` and :meth:`Actor._on_post_actor_method`
"""

# Specifies that the method invoked is an actor interface method for a given client request.
actor_interface_method = 0
# Specifies that the method invoked is a timer callback method.
Expand Down
34 changes: 20 additions & 14 deletions dapr/actor/runtime/_reminder_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,13 @@ class ActorReminderData:
"""

def __init__(
self, reminder_name: str, state: Optional[bytes],
due_time: timedelta, period: timedelta, ttl: Optional[timedelta] = None):
self,
reminder_name: str,
state: Optional[bytes],
due_time: timedelta,
period: timedelta,
ttl: Optional[timedelta] = None,
):
"""Creates new :class:`ActorReminderData` instance.
Args:
Expand All @@ -52,7 +57,7 @@ def __init__(
self._ttl = ttl

if not isinstance(state, bytes):
raise ValueError(f'only bytes are allowed for state: {type(state)}')
raise ValueError(f"only bytes are allowed for state: {type(state)}")

self._state = state

Expand Down Expand Up @@ -87,26 +92,27 @@ def as_dict(self) -> Dict[str, Any]:
if self._state is not None:
encoded_state = base64.b64encode(self._state)
reminderDict: Dict[str, Any] = {
'reminderName': self._reminder_name,
'dueTime': self._due_time,
'period': self._period,
'data': encoded_state.decode("utf-8")
"reminderName": self._reminder_name,
"dueTime": self._due_time,
"period": self._period,
"data": encoded_state.decode("utf-8"),
}

if self._ttl is not None:
reminderDict.update({'ttl': self._ttl})
reminderDict.update({"ttl": self._ttl})

return reminderDict

@classmethod
def from_dict(cls, reminder_name: str, obj: Dict[str, Any]) -> 'ActorReminderData':
def from_dict(cls, reminder_name: str, obj: Dict[str, Any]) -> "ActorReminderData":
"""Creates :class:`ActorReminderData` object from dict object."""
b64encoded_state = obj.get('data')
b64encoded_state = obj.get("data")
state_bytes = None
if b64encoded_state is not None and len(b64encoded_state) > 0:
state_bytes = base64.b64decode(b64encoded_state)
if 'ttl' in obj:
return ActorReminderData(reminder_name, state_bytes, obj['dueTime'], obj['period'],
obj['ttl'])
if "ttl" in obj:
return ActorReminderData(
reminder_name, state_bytes, obj["dueTime"], obj["period"], obj["ttl"]
)
else:
return ActorReminderData(reminder_name, state_bytes, obj['dueTime'], obj['period'])
return ActorReminderData(reminder_name, state_bytes, obj["dueTime"], obj["period"])
34 changes: 18 additions & 16 deletions dapr/actor/runtime/_state_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@

# Mapping StateChangeKind to Dapr State Operation
_MAP_CHANGE_KIND_TO_OPERATION = {
StateChangeKind.remove: b'delete',
StateChangeKind.add: b'upsert',
StateChangeKind.update: b'upsert',
StateChangeKind.remove: b"delete",
StateChangeKind.add: b"upsert",
StateChangeKind.update: b"upsert",
}


Expand All @@ -34,16 +34,18 @@ class StateProvider:
This provides the decorator methods to load and save states and check the existence of states.
"""

def __init__(
self,
actor_client: DaprActorClientBase,
state_serializer: Serializer = DefaultJSONSerializer()):
self,
actor_client: DaprActorClientBase,
state_serializer: Serializer = DefaultJSONSerializer(),
):
self._state_client = actor_client
self._state_serializer = state_serializer

async def try_load_state(
self, actor_type: str, actor_id: str,
state_name: str, state_type: Type[Any] = object) -> Tuple[bool, Any]:
self, actor_type: str, actor_id: str, state_name: str, state_type: Type[Any] = object
) -> Tuple[bool, Any]:
raw_state_value = await self._state_client.get_state(actor_type, actor_id, state_name)
if (not raw_state_value) or len(raw_state_value) == 0:
return (False, None)
Expand All @@ -55,8 +57,8 @@ async def contains_state(self, actor_type: str, actor_id: str, state_name: str)
return (raw_state_value is not None) and len(raw_state_value) > 0

async def save_state(
self, actor_type: str, actor_id: str,
state_changes: List[ActorStateChange]) -> None:
self, actor_type: str, actor_id: str, state_changes: List[ActorStateChange]
) -> None:
"""
Transactional state update request body:
[
Expand All @@ -77,24 +79,24 @@ async def save_state(
"""

json_output = io.BytesIO()
json_output.write(b'[')
json_output.write(b"[")
first_state = True
for state in state_changes:
if not first_state:
json_output.write(b',')
operation = _MAP_CHANGE_KIND_TO_OPERATION.get(state.change_kind) or b''
json_output.write(b",")
operation = _MAP_CHANGE_KIND_TO_OPERATION.get(state.change_kind) or b""
json_output.write(b'{"operation":"')
json_output.write(operation)
json_output.write(b'","request":{"key":"')
json_output.write(state.state_name.encode('utf-8'))
json_output.write(state.state_name.encode("utf-8"))
json_output.write(b'"')
if state.value is not None:
serialized = self._state_serializer.serialize(state.value)
json_output.write(b',"value":')
json_output.write(serialized)
json_output.write(b'}}')
json_output.write(b"}}")
first_state = False
json_output.write(b']')
json_output.write(b"]")
data = json_output.getvalue()
json_output.close()
await self._state_client.save_state_transactionally(actor_type, actor_id, data)
22 changes: 13 additions & 9 deletions dapr/actor/runtime/_timer_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,14 @@ class ActorTimerData:
"""

def __init__(
self, timer_name: str,
callback: TIMER_CALLBACK, state: Any,
due_time: timedelta, period: timedelta,
ttl: Optional[timedelta] = None):
self,
timer_name: str,
callback: TIMER_CALLBACK,
state: Any,
due_time: timedelta,
period: timedelta,
ttl: Optional[timedelta] = None,
):
"""Create new :class:`ActorTimerData` instance.
Args:
Expand Down Expand Up @@ -93,13 +97,13 @@ def as_dict(self) -> Dict[str, Any]:
"""

timerDict: Dict[str, Any] = {
'callback': self._callback,
'data': self._state,
'dueTime': self._due_time,
'period': self._period
"callback": self._callback,
"data": self._state,
"dueTime": self._due_time,
"period": self._period,
}

if self._ttl:
timerDict.update({'ttl': self._ttl})
timerDict.update({"ttl": self._ttl})

return timerDict
Loading

0 comments on commit 8f51088

Please sign in to comment.