Skip to content
Merged
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
8 changes: 3 additions & 5 deletions src/Dapr.Workflow/Client/WorkflowGrpcClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,9 @@ public override async Task<string> ScheduleNewWorkflowAsync(string workflowName,
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.NotFound)
{
return null;
}
catch (Exception ex)
{
logger.LogError(ex, "Error getting workflow metadata for instance '{InstanceId}'", instanceId);
// A missing instance is represented as null metadata. Every other gRPC failure (e.g. a transient
// Unavailable/Unknown from the runtime) is allowed to propagate so callers can distinguish a
// genuine "not found" from a transport/runtime error rather than seeing an identical null result.
return null;
}
}
Expand Down
15 changes: 10 additions & 5 deletions src/Dapr.Workflow/DaprWorkflowClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,14 @@ public Task<string> ScheduleNewWorkflowAsync(
/// </param>
/// <param name="cancellation">Token to cancel the retrieval operation.</param>
/// <returns>
/// A <see cref="WorkflowState"/> if the workflow instance exists, or <c>null</c> if the instance does not
/// exist or an error occurs retrieving the metadata.
/// This method never throws.
/// A <see cref="WorkflowState"/> describing the instance. If the instance does not exist, the returned
/// state reports <see cref="WorkflowState.Exists"/> as <c>false</c> rather than throwing.
/// </returns>
/// <exception cref="ArgumentException">Thrown if <paramref name="instanceId"/> is null or empty.</exception>
/// <exception cref="RpcException">
/// Thrown for gRPC failures other than <see cref="StatusCode.NotFound"/> (e.g. a transient runtime or
/// transport error), so callers can distinguish a genuinely missing workflow from an error retrieving it.
/// </exception>
public async Task<WorkflowState> GetWorkflowStateAsync(
string instanceId,
bool getInputsAndOutputs = true,
Expand All @@ -140,9 +144,10 @@ public async Task<WorkflowState> GetWorkflowStateAsync(
var metadata = await _innerClient.GetWorkflowMetadataAsync(instanceId, getInputsAndOutputs, cancellation);
return new WorkflowState(metadata);
}
catch (RpcException)
catch (RpcException ex) when (ex.StatusCode == StatusCode.NotFound)
{
// If the state doesn't exist, we typically get an `RpcException`, so this wraps this and just returns null
// A missing instance surfaces as a NotFound RpcException; represent it as a non-existent state.
// Any other RpcException propagates so the caller can handle the error.
return new WorkflowState(null);
}
}
Expand Down
96 changes: 96 additions & 0 deletions test/Dapr.IntegrationTest.Workflow/GetWorkflowStateTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// ------------------------------------------------------------------------
// Copyright 2025 The Dapr Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------

using Dapr.Testcontainers.Common;
using Dapr.Testcontainers.Harnesses;
using Dapr.Workflow;
using Dapr.Workflow.Registration;
using Grpc.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Dapr.IntegrationTest.Workflow;

/// <summary>
/// Verifies the two distinct error surfaces of <see cref="DaprWorkflowClient.GetWorkflowStateAsync"/>.
/// </summary>
/// <remarks>
/// Modeled off a repro that showed a transient, non-<see cref="StatusCode.NotFound"/> gRPC error being
/// swallowed into an <c>Exists == false</c> <see cref="WorkflowState"/> — making it indistinguishable from a
/// workflow that genuinely does not exist. The client now only treats <see cref="StatusCode.NotFound"/> as
/// "does not exist"; every other gRPC failure propagates so the caller can handle it. This test proves both
/// surfaces end-to-end over real gRPC:
/// <list type="number">
/// <item>a never-created instance queried against a real sidecar returns <c>Exists == false</c> and does not throw;</item>
/// <item>a transport-level failure (a client pointed at an unreachable endpoint) surfaces as an <see cref="RpcException"/>.</item>
/// </list>
/// </remarks>
public sealed class GetWorkflowStateTests
{
[Fact]
public async Task GetWorkflowStateAsync_ShouldReturnNotExists_ForMissingWorkflow_AndPropagate_OnTransportError()
{
var componentsDir = TestDirectoryManager.CreateTestDirectory("workflow-components");

await using var environment = await DaprTestEnvironment.CreateWithPooledNetworkAsync(needsActorState: true, cancellationToken: TestContext.Current.CancellationToken);
await environment.StartAsync(TestContext.Current.CancellationToken);

var harness = new DaprHarnessBuilder(componentsDir)
.WithEnvironment(environment)
.BuildWorkflow();
await using var testApp = await DaprHarnessBuilder.ForHarness(harness)
.ConfigureServices(builder =>
{
builder.Services.AddDaprWorkflowBuilder(
configureRuntime: opt => opt.RegisterWorkflow<NoopWorkflow>(),
configureClient: (sp, clientBuilder) =>
{
var config = sp.GetRequiredService<IConfiguration>();
var grpcEndpoint = config["DAPR_GRPC_ENDPOINT"];
if (!string.IsNullOrEmpty(grpcEndpoint))
clientBuilder.UseGrpcEndpoint(grpcEndpoint);
});
})
.BuildAndStartAsync();

using var scope = testApp.CreateScope();
var daprWorkflowClient = scope.ServiceProvider.GetRequiredService<DaprWorkflowClient>();

// 1) A workflow that was never created. The runtime reports "not found", which the client maps to a
// concrete WorkflowState with Exists == false — no exception, exactly as the repro's baseline showed.
var missing = await daprWorkflowClient.GetWorkflowStateAsync(
"never-created-" + Guid.NewGuid().ToString("N"),
cancellation: TestContext.Current.CancellationToken);

Assert.NotNull(missing);
Assert.False(missing.Exists);
Assert.Equal(WorkflowRuntimeStatus.Unknown, missing.RuntimeStatus);

// 2) A non-NotFound gRPC failure must reach the caller instead of being swallowed into the same
// Exists == false surface. We reproduce that deterministically with a client pointed at an
// unreachable endpoint: the call fails at the transport layer (StatusCode other than NotFound),
// and GetWorkflowStateAsync lets that RpcException propagate.
await using var unreachableClient = new DaprWorkflowClientBuilder()
.UseGrpcEndpoint("http://127.0.0.1:9999")
.Build();

var ex = await Assert.ThrowsAsync<RpcException>(() =>
unreachableClient.GetWorkflowStateAsync("any-instance", cancellation: TestContext.Current.CancellationToken));
Assert.NotEqual(StatusCode.NotFound, ex.StatusCode);
}

private sealed class NoopWorkflow : Workflow<object?, object?>
{
public override Task<object?> RunAsync(WorkflowContext context, object? input) => Task.FromResult<object?>(null);
}
}
16 changes: 15 additions & 1 deletion test/Dapr.Workflow.Test/DaprWorkflowClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public async Task GetWorkflowStateAsync_ShouldReflectNotExists_WhenInnerReturnsN
}

[Fact]
public async Task GetWorkflowStateAsync_ShouldReflectNotExists_WhenInnerThrowsRpcException()
public async Task GetWorkflowStateAsync_ShouldReflectNotExists_WhenInnerThrowsNotFoundRpcException()
{
var inner = new CapturingWorkflowClient
{
Expand All @@ -113,6 +113,20 @@ public async Task GetWorkflowStateAsync_ShouldReflectNotExists_WhenInnerThrowsRp
Assert.False(state.Exists);
}

[Fact]
public async Task GetWorkflowStateAsync_ShouldRethrow_WhenInnerThrowsNonNotFoundRpcException()
{
var inner = new CapturingWorkflowClient
{
GetWorkflowMetadataException = new RpcException(new Status(StatusCode.Unavailable, "sidecar down"))
};
var client = new DaprWorkflowClient(inner);

var ex = await Assert.ThrowsAsync<RpcException>(() =>
client.GetWorkflowStateAsync("i", cancellation: TestContext.Current.CancellationToken));
Assert.Equal(StatusCode.Unavailable, ex.StatusCode);
}

[Fact]
public async Task GetWorkflowStateAsync_ShouldReturnWorkflowState_WhenInnerReturnsMetadata()
{
Expand Down
Loading