Skip to content

context vars #216

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion custom_metric/activity.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import threading
import time

from temporalio import activity
from custom_metric.shared import user_id


@activity.defn
def print_and_sleep():
print("In the activity.")
print(f"In the activity. in thread {threading.current_thread().name}")
print(f"User ID: {user_id.get()} in activity {activity.info().activity_id}")
time.sleep(1)
4 changes: 4 additions & 0 deletions custom_metric/shared.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from contextvars import ContextVar
from typing import Optional

user_id: ContextVar[Optional[str]] = ContextVar("user_id", default=None)
10 changes: 8 additions & 2 deletions custom_metric/worker.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
from concurrent.futures import ThreadPoolExecutor
import threading

from temporalio import activity
from temporalio.client import Client
Expand All @@ -13,12 +14,14 @@

from custom_metric.activity import print_and_sleep
from custom_metric.workflow import StartTwoActivitiesWorkflow
from custom_metric.shared import user_id


class SimpleWorkerInterceptor(Interceptor):
def intercept_activity(
self, next: ActivityInboundInterceptor
) -> ActivityInboundInterceptor:
user_id.set(activity.info().activity_id) # Set a user ID for the activity context
return CustomScheduleToStartInterceptor(next)


Expand All @@ -32,6 +35,9 @@ async def execute_activity(self, input: ExecuteActivityInput):
# Could do the original schedule time instead of current attempt
# schedule_to_start_second_option = activity.info().started_time - activity.info().scheduled_time

# print the thread name for debugging
print(f"In the activity interceptor. in thread {threading.current_thread().name}")

meter = activity.metric_meter()
histogram = meter.create_histogram_timedelta(
"custom_activity_schedule_to_start_latency",
Expand Down Expand Up @@ -60,8 +66,8 @@ async def main():
activities=[print_and_sleep],
# only one activity executor with two concurrently scheduled activities
# to force a nontrivial schedule to start times
activity_executor=ThreadPoolExecutor(1),
max_concurrent_activities=1,
activity_executor=ThreadPoolExecutor(10),
max_concurrent_activities=10,
)

await worker.run()
Expand Down
18 changes: 17 additions & 1 deletion custom_metric/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,21 @@ async def run(self):
print_and_sleep,
start_to_close_timeout=timedelta(seconds=5),
)
await asyncio.gather(activity1, activity2)
activity3 = workflow.execute_activity(
print_and_sleep,
start_to_close_timeout=timedelta(seconds=5),
)
activity4 = workflow.execute_activity(
print_and_sleep,
start_to_close_timeout=timedelta(seconds=5),
)
activity5 = workflow.execute_activity(
print_and_sleep,
start_to_close_timeout=timedelta(seconds=5),
)
activity6 = workflow.execute_activity(
print_and_sleep,
start_to_close_timeout=timedelta(seconds=5),
)
await asyncio.gather(activity1, activity2, activity3, activity4, activity5, activity6)
return None
Loading