// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Agents.AI.Workflows;
using Microsoft.DurableTask;
using Microsoft.DurableTask.Client;
namespace Microsoft.Agents.AI.DurableTask.Workflows;
///
/// Provides a durable task-based implementation of for running
/// workflows as durable orchestrations.
///
internal sealed class DurableWorkflowClient : IWorkflowClient
{
private readonly DurableTaskClient _client;
///
/// Initializes a new instance of the class.
///
/// The durable task client for orchestration operations.
/// Thrown when is null.
public DurableWorkflowClient(DurableTaskClient client)
{
ArgumentNullException.ThrowIfNull(client);
this._client = client;
}
///
public async ValueTask RunAsync(
Workflow workflow,
TInput input,
string? runId = null,
CancellationToken cancellationToken = default)
where TInput : notnull
{
ArgumentNullException.ThrowIfNull(workflow);
if (string.IsNullOrEmpty(workflow.Name))
{
throw new ArgumentException("Workflow must have a valid Name property.", nameof(workflow));
}
DurableWorkflowInput workflowInput = new() { Input = input };
string instanceId = await this._client.ScheduleNewOrchestrationInstanceAsync(
orchestratorName: WorkflowNamingHelper.ToOrchestrationFunctionName(workflow.Name),
input: workflowInput,
options: runId is not null ? new StartOrchestrationOptions(runId) : null,
cancellation: cancellationToken).ConfigureAwait(false);
return new DurableWorkflowRun(this._client, instanceId, workflow.Name);
}
///
public ValueTask RunAsync(
Workflow workflow,
string input,
string? runId = null,
CancellationToken cancellationToken = default)
=> this.RunAsync(workflow, input, runId, cancellationToken);
///
public async ValueTask StreamAsync(
Workflow workflow,
TInput input,
string? runId = null,
CancellationToken cancellationToken = default)
where TInput : notnull
{
ArgumentNullException.ThrowIfNull(workflow);
if (string.IsNullOrEmpty(workflow.Name))
{
throw new ArgumentException("Workflow must have a valid Name property.", nameof(workflow));
}
DurableWorkflowInput workflowInput = new() { Input = input };
string instanceId = await this._client.ScheduleNewOrchestrationInstanceAsync(
orchestratorName: WorkflowNamingHelper.ToOrchestrationFunctionName(workflow.Name),
input: workflowInput,
options: runId is not null ? new StartOrchestrationOptions(runId) : null,
cancellation: cancellationToken).ConfigureAwait(false);
return new DurableStreamingWorkflowRun(this._client, instanceId, workflow);
}
///
public ValueTask StreamAsync(
Workflow workflow,
string input,
string? runId = null,
CancellationToken cancellationToken = default)
=> this.StreamAsync(workflow, input, runId, cancellationToken);
}