< Summary - AsyncResponse (Release / net8.0+net10.0 / unit+integration)

Information
Class: AsyncResponse.DurableFlowService<TFlow, TInput>
Assembly: AsyncResponse.Core
File(s): /home/runner/work/AsyncResponse/AsyncResponse/src/AsyncResponse.Core/DurableFlows.cs
Line coverage
100%
Covered lines: 77
Uncovered lines: 0
Coverable lines: 77
Total lines: 139
Line coverage: 100%
Branch coverage
100%
Covered branches: 8
Total branches: 8
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
StartAsync()100%22100%
ResumeAsync()100%22100%
GetStateAsync()100%11100%
EnsureIdempotentStart<TFlow, TInput>(...)100%44100%

File(s)

/home/runner/work/AsyncResponse/AsyncResponse/src/AsyncResponse.Core/DurableFlows.cs

#LineLine coverage
 1using Microsoft.Extensions.DependencyInjection;
 2using Microsoft.Extensions.Logging;
 3using System.Diagnostics.CodeAnalysis;
 4
 5namespace AsyncResponse;
 6
 7/// <inheritdoc cref="IDurableFlows" />
 8internal sealed class DurableFlowService : IDurableFlows
 9{
 10    private readonly IServiceScopeFactory _scopeFactory;
 11    private readonly IAsyncResponseBuilder _builder;
 12    private readonly AsyncResponseContextPropagation _propagation;
 13    private readonly DurableFlowOptions _options;
 14    private readonly ILogger<DurableFlowService> _logger;
 15
 16    /// <summary>Creates the durable-flows starter.</summary>
 317    public DurableFlowService(
 318        IServiceScopeFactory scopeFactory,
 319        IAsyncResponseBuilder builder,
 320        AsyncResponseContextPropagation propagation,
 321        DurableFlowOptions options,
 322        ILogger<DurableFlowService> logger)
 23    {
 324        _scopeFactory = scopeFactory;
 325        _builder = builder;
 326        _propagation = propagation;
 327        _options = options;
 328        FlowStateConcurrency.ValidateOptions(_options);
 329        _logger = logger;
 330    }
 31
 32    /// <inheritdoc />
 33    public async Task<string> StartAsync<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors |
 34        TInput input,
 35        string? flowId = null,
 36        CancellationToken cancellationToken = default)
 37        where TFlow : class, IDurableFlow<TInput>
 38    {
 339        ArgumentNullException.ThrowIfNull(input);
 340        cancellationToken.ThrowIfCancellationRequested();
 341        if (flowId is null)
 342            flowId = $"flow-{AsyncResponseContext.GenerateCorrelationId()}";
 43        else
 344            ArgumentException.ThrowIfNullOrWhiteSpace(flowId);
 45
 346        await using var scope = _scopeFactory.CreateAsyncScope();
 347        var store = scope.ServiceProvider.GetRequiredService<IFlowStateStore>();
 48
 349        var now = DateTime.UtcNow;
 350        var inputJson = AsyncResponseJson.Serialize(input);
 351        var state = new FlowState
 352        {
 353            FlowId = flowId,
 354            FlowTypeName = typeof(TFlow).FullName,
 355            InputTypeName = typeof(TInput).FullName,
 356            InputJson = inputJson,
 357            Status = FlowRunStatus.Running,
 358            LastMessage = "Flow started.",
 359            CreatedAtUtc = now,
 360            UpdatedAtUtc = now,
 361            Context = _propagation.Capture()
 362        };
 63
 364        if (await FlowStateConcurrency.TryCreateAsync(
 365                store,
 366                flowId,
 367                state,
 368                _options.StateExpiry,
 369                cancellationToken).ConfigureAwait(false))
 70        {
 371            _logger.LogInformation("Started durable flow {FlowId} ({FlowType}).", flowId, typeof(TFlow).Name);
 72        }
 73        else
 74        {
 375            var existing = await store.LoadAsync(flowId, cancellationToken).ConfigureAwait(false)
 376                ?? throw new InvalidOperationException(
 377                    $"Durable flow '{flowId}' already exists but its ledger is expired or unreadable.");
 378            EnsureIdempotentStart<TFlow, TInput>(existing, inputJson, flowId);
 79
 80            // A semantically identical retry re-enqueues the existing run; completed steps skip.
 381            _logger.LogInformation("Durable flow {FlowId} already exists; re-enqueueing instead of creating a duplicate.
 82        }
 83
 384        var id = flowId;
 385        await _builder.EnqueueWorkerAsync<IDurableFlowExecutor>(
 386            executor => executor.ExecuteAsync(id),
 387            cancellationToken).ConfigureAwait(false);
 388        return flowId;
 389    }
 90
 91    /// <inheritdoc />
 92    public async Task ResumeAsync(string flowId, CancellationToken cancellationToken = default)
 93    {
 394        ArgumentException.ThrowIfNullOrWhiteSpace(flowId);
 95
 396        await using var scope = _scopeFactory.CreateAsyncScope();
 397        var store = scope.ServiceProvider.GetRequiredService<IFlowStateStore>();
 98
 399        var state = await store.LoadAsync(flowId, cancellationToken).ConfigureAwait(false)
 3100            ?? throw new InvalidOperationException($"No flow state found for '{flowId}' (unknown, expired, or unreadable
 101
 3102        if (state.Status != FlowRunStatus.Running)
 103        {
 3104            _logger.LogDebug("Durable flow {FlowId} is already {Status}; ignoring resume.", flowId, state.Status);
 3105            return;
 106        }
 107
 2108        var id = flowId;
 2109        await _builder.EnqueueWorkerAsync<IDurableFlowExecutor>(
 2110            executor => executor.ExecuteAsync(id),
 2111            cancellationToken).ConfigureAwait(false);
 3112    }
 113
 114    /// <inheritdoc />
 115    public async Task<FlowState?> GetStateAsync(string flowId, CancellationToken cancellationToken = default)
 116    {
 3117        ArgumentException.ThrowIfNullOrWhiteSpace(flowId);
 118
 3119        await using var scope = _scopeFactory.CreateAsyncScope();
 3120        var store = scope.ServiceProvider.GetRequiredService<IFlowStateStore>();
 3121        return await store.LoadAsync(flowId, cancellationToken).ConfigureAwait(false);
 3122    }
 123
 124    private static void EnsureIdempotentStart<TFlow, TInput>(
 125        FlowState existing,
 126        string requestedInputJson,
 127        string flowId)
 128    {
 3129        var sameFlowType = string.Equals(existing.FlowTypeName, typeof(TFlow).FullName, StringComparison.Ordinal);
 3130        var sameInputType = string.Equals(existing.InputTypeName, typeof(TInput).FullName, StringComparison.Ordinal);
 3131        if (sameFlowType && sameInputType && FlowStateJson.JsonEquivalent(existing.InputJson, requestedInputJson))
 3132            return;
 133
 3134        throw new InvalidOperationException(
 3135            $"Durable flow id '{flowId}' is already bound to a different flow type or input. " +
 3136            "Idempotent retries must use the same TFlow, TInput, and semantically identical input value.");
 137    }
 138
 139}