Skip to content

Commit

Permalink
Add ruff auto fix (#657)
Browse files Browse the repository at this point in the history
* Add ruff

Signed-off-by: Bernd Verst <[email protected]>

* Autoformat all files using ruff

Signed-off-by: Bernd Verst <[email protected]>

* Run ruff check on CI

Signed-off-by: Bernd Verst <[email protected]>

* fix up type checker exemption

Signed-off-by: Bernd Verst <[email protected]>

---------

Signed-off-by: Bernd Verst <[email protected]>
Co-authored-by: Bernd Verst <[email protected]>
  • Loading branch information
litan1106 and berndverst authored Jan 19, 2024
1 parent 593eb07 commit 9660735
Show file tree
Hide file tree
Showing 146 changed files with 4,725 additions and 3,956 deletions.
31 changes: 28 additions & 3 deletions .github/workflows/build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,35 @@ on:
merge_group:

jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python 3.9
uses: actions/setup-python@v5
with:
python-version: 3.9
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel tox
- name: Run Autoformatter
run: |
tox -e ruff
statusResult=$(git status -u --porcelain)
if [ -z $statusResult ]
then
exit 0
else
echo "Source files are not formatted correctly. Run 'tox -e ruff' to autoformat."
exit 1
fi
- name: Run Linter
run: |
tox -e flake8
build:
needs: lint
runs-on: ubuntu-latest
strategy:
fail-fast: false
Expand All @@ -36,9 +64,6 @@ jobs:
run: |
python -m pip install --upgrade pip
pip install setuptools wheel tox
- name: Run Linter
run: |
tox -e flake8
- name: Check Typing
run: |
tox -e type
Expand Down
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,19 +96,25 @@ pip3 install -r dev-requirements.txt
tox -e flake8
```

5. Run unit-test
5. Run autofix

```bash
tox -e ruff
```

6. Run unit-test

```bash
tox -e py311
```

6. Run type check
7. Run type check

```bash
tox -e type
```

7. Run examples
8. Run examples

```bash
tox -e examples
Expand Down
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"])
Loading

0 comments on commit 9660735

Please sign in to comment.