-
Notifications
You must be signed in to change notification settings - Fork 3
Add ActivityContext #26
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import asyncio | ||
from concurrent.futures.thread import ThreadPoolExecutor | ||
from typing import Callable, Any | ||
|
||
from cadence import Client | ||
from cadence._internal.type_utils import get_fn_parameters | ||
from cadence.activity import ActivityInfo, ActivityContext | ||
from cadence.api.v1.common_pb2 import Payload | ||
|
||
|
||
class _Context(ActivityContext): | ||
def __init__(self, client: Client, info: ActivityInfo, activity_fn: Callable[[Any], Any]): | ||
self._client = client | ||
self._info = info | ||
self._activity_fn = activity_fn | ||
|
||
async def execute(self, payload: Payload) -> Any: | ||
params = await self._to_params(payload) | ||
with self._activate(): | ||
return await self._activity_fn(*params) | ||
|
||
async def _to_params(self, payload: Payload) -> list[Any]: | ||
type_hints = get_fn_parameters(self._activity_fn) | ||
return await self._client.data_converter.from_data(payload, type_hints) | ||
|
||
def client(self) -> Client: | ||
return self._client | ||
|
||
def info(self) -> ActivityInfo: | ||
return self._info | ||
|
||
class _SyncContext(_Context): | ||
def __init__(self, client: Client, info: ActivityInfo, activity_fn: Callable[[Any], Any], executor: ThreadPoolExecutor): | ||
super().__init__(client, info, activity_fn) | ||
self._executor = executor | ||
|
||
async def execute(self, payload: Payload) -> Any: | ||
params = await self._to_params(payload) | ||
loop = asyncio.get_running_loop() | ||
return await loop.run_in_executor(self._executor, self._run, params) | ||
|
||
def _run(self, args: list[Any]) -> Any: | ||
with self._activate(): | ||
return self._activity_fn(*args) | ||
|
||
def client(self) -> Client: | ||
raise RuntimeError("client is only supported in async activities") | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
from abc import ABC, abstractmethod | ||
from contextlib import contextmanager | ||
from contextvars import ContextVar | ||
from dataclasses import dataclass | ||
from datetime import timedelta, datetime | ||
from typing import Iterator | ||
|
||
from cadence import Client | ||
|
||
|
||
@dataclass(frozen=True) | ||
class ActivityInfo: | ||
task_token: bytes | ||
workflow_type: str | ||
workflow_domain: str | ||
workflow_id: str | ||
workflow_run_id: str | ||
activity_id: str | ||
activity_type: str | ||
task_list: str | ||
heartbeat_timeout: timedelta | ||
scheduled_timestamp: datetime | ||
started_timestamp: datetime | ||
start_to_close_timeout: timedelta | ||
attempt: int | ||
|
||
def client() -> Client: | ||
return ActivityContext.get().client() | ||
|
||
def in_activity() -> bool: | ||
return ActivityContext.is_set() | ||
|
||
def info() -> ActivityInfo: | ||
return ActivityContext.get().info() | ||
|
||
|
||
|
||
class ActivityContext(ABC): | ||
_var: ContextVar['ActivityContext'] = ContextVar("activity") | ||
|
||
@abstractmethod | ||
def info(self) -> ActivityInfo: | ||
... | ||
|
||
@abstractmethod | ||
def client(self) -> Client: | ||
... | ||
|
||
@contextmanager | ||
def _activate(self) -> Iterator[None]: | ||
token = ActivityContext._var.set(self) | ||
yield None | ||
ActivityContext._var.reset(token) | ||
|
||
@staticmethod | ||
def is_set() -> bool: | ||
return ActivityContext._var.get(None) is not None | ||
|
||
@staticmethod | ||
def get() -> 'ActivityContext': | ||
return ActivityContext._var.get() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: store in self._activity_fn_args_type_hints to avoid unnecessary evaluations.