Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
026c572
Creation of DTS example and passing of completionToken
RyanLettieri Jan 22, 2025
136a3d0
Adressing review feedback
RyanLettieri Jan 22, 2025
6df1064
Reverting dapr readme
RyanLettieri Jan 22, 2025
f731c0d
Adding accessTokenManager class for refreshing credential token
RyanLettieri Jan 24, 2025
eb98416
Adding comments to the example
RyanLettieri Jan 24, 2025
0de338d
Adding in requirement for azure-identity
RyanLettieri Jan 24, 2025
6050771
Moving dts logic into its own module
RyanLettieri Jan 28, 2025
f4f98ee
Fixing whitesapce
RyanLettieri Jan 28, 2025
ea837d0
Updating dts client to refresh token
RyanLettieri Jan 29, 2025
f8d79d3
Cleaning up construction of dts objects and improving examples
RyanLettieri Jan 29, 2025
1e67651
Migrating shared access token logic to new grpc class
RyanLettieri Feb 4, 2025
6b1bfd2
Adding log statements to access_token_manager
RyanLettieri Feb 5, 2025
bd56a35
breaking for loop when setting interceptors
RyanLettieri Feb 5, 2025
efc0146
Removing changes to client.py and adding additional steps to readme.md
RyanLettieri Feb 7, 2025
3fd0b08
Refactoring client and worker to pass around interceptors
RyanLettieri Feb 11, 2025
4260d02
Fixing import for DefaultClientInterceptorImpl
RyanLettieri Feb 11, 2025
ec4617c
Adressing round 1 of feedback
RyanLettieri Feb 11, 2025
ed733ea
Fixing interceptor issue
RyanLettieri Feb 12, 2025
99f62d7
Moving some files around to remove dependencies
RyanLettieri Feb 12, 2025
f9d55ab
Adressing more feedback
RyanLettieri Feb 12, 2025
ba1ac4f
More review feedback
RyanLettieri Feb 12, 2025
2c251ea
Passing token credential as an argument rather than 2 strings
RyanLettieri Feb 13, 2025
9c65176
More review feedback for token passing
RyanLettieri Feb 13, 2025
877dabb
Addressing None comment and using correct metadata
RyanLettieri Feb 13, 2025
b39ffad
Updating unit tests
RyanLettieri Feb 13, 2025
33c8b11
Fixing the type for the unit test
RyanLettieri Feb 13, 2025
1da819e
Fixing grpc calls
RyanLettieri Feb 13, 2025
f690264
Merge branch 'main' into durabletask-scheduler
RyanLettieri Feb 13, 2025
6142220
Fix linter errors and update documentation
cgillum Feb 14, 2025
58f4f93
Specifying version reqiuirement for pyproject.toml
RyanLettieri Feb 18, 2025
d82c1b7
Updating README
RyanLettieri Feb 18, 2025
b3a099e
Adding comment for credential type
RyanLettieri Feb 18, 2025
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
1 change: 1 addition & 0 deletions durabletask/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ def __init__(self, *,
log_handler: Optional[logging.Handler] = None,
log_formatter: Optional[logging.Formatter] = None,
secure_channel: bool = False):
self._metadata = metadata
channel = shared.get_grpc_channel(host_address, metadata, secure_channel=secure_channel)
self._stub = stubs.TaskHubSidecarServiceStub(channel)
self._logger = shared.get_logger("client", log_handler, log_formatter)
Expand Down
11 changes: 5 additions & 6 deletions examples/dts/dts_activity_sequence.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import os
from azure.identity import DefaultAzureCredential

"""End-to-end sample that demonstrates how to configure an orchestrator
that calls an activity function in a sequence and prints the outputs."""
import os
from durabletask import client, task
from externalpackages.durabletaskscheduler.durabletask_scheduler_worker import DurableTaskSchedulerWorker
from externalpackages.durabletaskscheduler.durabletask_scheduler_client import DurableTaskSchedulerClient
from externalpackages.durabletaskscheduler.access_token_manager import AccessTokenManager

def hello(ctx: task.ActivityContext, name: str) -> str:
Expand Down Expand Up @@ -52,18 +51,18 @@ def sequence(ctx: task.OrchestrationContext, _):
arm_scope = "https://durabletask.io/.default"
token_manager = AccessTokenManager(scope = arm_scope)

metaData: list[tuple[str, str]] = [
meta_data: list[tuple[str, str]] = [
("taskhub", taskhub_name)
]

# configure and start the worker
with DurableTaskSchedulerWorker(host_address=endpoint, metadata=metaData, secure_channel=True, access_token_manager=token_manager) as w:
with DurableTaskSchedulerWorker(host_address=endpoint, metadata=meta_data, secure_channel=True, access_token_manager=token_manager) as w:
w.add_orchestrator(sequence)
w.add_activity(hello)
w.start()

# Construct the client and run the orchestrations
c = client.TaskHubGrpcClient(host_address=endpoint, metadata=metaData, secure_channel=True)
c = DurableTaskSchedulerClient(host_address=endpoint, metadata=meta_data, secure_channel=True, access_token_manager=token_manager)
instance_id = c.schedule_new_orchestration(sequence)
state = c.wait_for_orchestration_completion(instance_id, timeout=45)
if state and state.runtime_status == client.OrchestrationStatus.COMPLETED:
Expand Down
99 changes: 99 additions & 0 deletions examples/dts/dts_fanout_fanin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""End-to-end sample that demonstrates how to configure an orchestrator
that a dynamic number activity functions in parallel, waits for them all
to complete, and prints an aggregate summary of the outputs."""
import random
import time
import os
from durabletask import client, task
from durabletask import client, task
from externalpackages.durabletaskscheduler.durabletask_scheduler_worker import DurableTaskSchedulerWorker
from externalpackages.durabletaskscheduler.durabletask_scheduler_client import DurableTaskSchedulerClient
from externalpackages.durabletaskscheduler.access_token_manager import AccessTokenManager


def get_work_items(ctx: task.ActivityContext, _) -> list[str]:
"""Activity function that returns a list of work items"""
# return a random number of work items
count = random.randint(2, 10)
print(f'generating {count} work items...')
return [f'work item {i}' for i in range(count)]


def process_work_item(ctx: task.ActivityContext, item: str) -> int:
"""Activity function that returns a result for a given work item"""
print(f'processing work item: {item}')

# simulate some work that takes a variable amount of time
time.sleep(random.random() * 5)

# return a result for the given work item, which is also a random number in this case
return random.randint(0, 10)


def orchestrator(ctx: task.OrchestrationContext, _):
"""Orchestrator function that calls the 'get_work_items' and 'process_work_item'
activity functions in parallel, waits for them all to complete, and prints
an aggregate summary of the outputs"""

work_items: list[str] = yield ctx.call_activity(get_work_items)

# execute the work-items in parallel and wait for them all to return
tasks = [ctx.call_activity(process_work_item, input=item) for item in work_items]
results: list[int] = yield task.when_all(tasks)

# return an aggregate summary of the results
return {
'work_items': work_items,
'results': results,
'total': sum(results),
}


# Read the environment variable
taskhub_name = os.getenv("TASKHUB")

# Check if the variable exists
if taskhub_name:
print(f"The value of TASKHUB is: {taskhub_name}")
else:
print("TASKHUB is not set. Please set the TASKHUB environment variable to the name of the taskhub you wish to use")
print("If you are using windows powershell, run the following: $env:TASKHUB=\"<taskhubname>\"")
print("If you are using bash, run the following: export TASKHUB=\"<taskhubname>\"")
exit()

# Read the environment variable
endpoint = os.getenv("ENDPOINT")

# Check if the variable exists
if endpoint:
print(f"The value of ENDPOINT is: {endpoint}")
else:
print("ENDPOINT is not set. Please set the ENDPOINT environment variable to the endpoint of the scheduler")
print("If you are using windows powershell, run the following: $env:ENDPOINT=\"<schedulerEndpoint>\"")
print("If you are using bash, run the following: export ENDPOINT=\"<schedulerEndpoint>\"")
exit()

# Define the scope for Azure Resource Manager (ARM)
arm_scope = "https://durabletask.io/.default"
token_manager = AccessTokenManager(scope = arm_scope)

meta_data: list[tuple[str, str]] = [
("taskhub", taskhub_name)
]


# configure and start the worker
with DurableTaskSchedulerWorker(host_address=endpoint, metadata=meta_data, secure_channel=True, access_token_manager=token_manager) as w:
w.add_orchestrator(orchestrator)
w.add_activity(process_work_item)
w.add_activity(get_work_items)
w.start()

# create a client, start an orchestration, and wait for it to finish
c = DurableTaskSchedulerClient(host_address=endpoint, metadata=meta_data, secure_channel=True, access_token_manager=token_manager)
instance_id = c.schedule_new_orchestration(orchestrator)
state = c.wait_for_orchestration_completion(instance_id, timeout=30)
if state and state.runtime_status == client.OrchestrationStatus.COMPLETED:
print(f'Orchestration completed! Result: {state.serialized_output}')
elif state:
print(f'Orchestration failed: {state.failure_details}')
Original file line number Diff line number Diff line change
@@ -1,6 +1,64 @@
from durabletask import TaskHubGrpcClient
from durabletask.client import TaskHubGrpcClient
from externalpackages.durabletaskscheduler.access_token_manager import AccessTokenManager

class DurableTaskSchedulerClient(TaskHubGrpcClient):
def __init__(self, *args, **kwargs):
def __init__(self, *args, access_token_manager: AccessTokenManager, **kwargs):
# Initialize the base class
super().__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self._access_token_manager = access_token_manager
self.__update_metadata_with_token()

def __update_metadata_with_token(self):
"""
Add or update the `authorization` key in the metadata with the current access token.
"""
if self._access_token_manager is not None:
token = self._access_token_manager.get_access_token()

# Check if "authorization" already exists in the metadata
updated = False
for i, (key, _) in enumerate(self._metadata):
if key == "authorization":
self._metadata[i] = ("authorization", token)
updated = True
break

# If not updated, add a new entry
if not updated:
self._metadata.append(("authorization", token))

def schedule_new_orchestration(self, *args, **kwargs) -> str:
self.__update_metadata_with_token()
return super().schedule_new_orchestration(*args, **kwargs)

def get_orchestration_state(self, *args, **kwargs):
self.__update_metadata_with_token()
super().get_orchestration_state(*args, **kwargs)

def wait_for_orchestration_start(self, *args, **kwargs):
self.__update_metadata_with_token()
super().wait_for_orchestration_start(*args, **kwargs)

def wait_for_orchestration_completion(self, *args, **kwargs):
self.__update_metadata_with_token()
super().wait_for_orchestration_completion(*args, **kwargs)

def raise_orchestration_event(self, *args, **kwargs):
self.__update_metadata_with_token()
super().raise_orchestration_event(*args, **kwargs)

def terminate_orchestration(self, *args, **kwargs):
self.__update_metadata_with_token()
super().terminate_orchestration(*args, **kwargs)

def suspend_orchestration(self, *args, **kwargs):
self.__update_metadata_with_token()
super().suspend_orchestration(*args, **kwargs)

def resume_orchestration(self, *args, **kwargs):
self.__update_metadata_with_token()
super().resume_orchestration(*args, **kwargs)

def purge_orchestration(self, *args, **kwargs):
self.__update_metadata_with_token()
super().purge_orchestration(*args, **kwargs)
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from externalpackages.durabletaskscheduler.access_token_manager import AccessTokenManager

class DurableTaskSchedulerWorker(TaskHubGrpcWorker):
def __init__(self, *args, access_token_manager: AccessTokenManager = None, **kwargs):
def __init__(self, *args, access_token_manager: AccessTokenManager, **kwargs):
# Initialize the base class
super().__init__(*args, **kwargs)
self._access_token_manager = access_token_manager
Expand Down
Loading