Skip to content

Throw exception in WaitForResourceAsync and WaitForResourceHealthyAsync when resource does not exist #8468

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
24 changes: 24 additions & 0 deletions src/Aspire.Hosting/ApplicationModel/ResourceNotificationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,18 @@ public Task WaitForResourceAsync(string resourceName, string? targetState = null
Justification = "targetState(s) parameters are mutually exclusive.")]
public async Task<string> WaitForResourceAsync(string resourceName, IEnumerable<string> targetStates, CancellationToken cancellationToken = default)
{
var appModel = _serviceProvider.GetService<DistributedApplicationModel>();

if (appModel is not null)
{
var resourceExist = appModel.Resources.Any(resource => resource.Name.Equals(resourceName, StringComparisons.ResourceName));

if (!resourceExist)
{
throw new InvalidOperationException($"Resource with name '{resourceName}' not found.");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this only be done if DefaultWaitBehaviour == WaitBehavior.StopOnResourceUnavailable, as it is potentially possible that the resource could show up later. (Perhaps if WaitBehavior is something else, it is worth logging something to highlight that the resoruce doesn't exist, even if it doesn't blow up completely)

}
}

if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Waiting for resource '{Name}' to enter one of the target state: {TargetStates}", resourceName, string.Join(", ", targetStates));
Expand Down Expand Up @@ -415,6 +427,18 @@ public async Task<ResourceEvent> WaitForResourceAsync(string resourceName, Func<

private async Task<ResourceEvent> WaitForResourceCoreAsync(string resourceName, Func<ResourceEvent, bool> predicate, CancellationToken cancellationToken = default)
{
var appModel = _serviceProvider.GetService<DistributedApplicationModel>();

if (appModel is not null)
{
var resourceExist = appModel.Resources.Any(resource => resource.Name.Equals(resourceName, StringComparisons.ResourceName));

if (!resourceExist)
{
throw new InvalidOperationException($"Resource with name '{resourceName}' not found.");
}
}

using var watchCts = CancellationTokenSource.CreateLinkedTokenSource(_disposing.Token, cancellationToken);
var watchToken = watchCts.Token;
await foreach (var resourceEvent in WatchAsync(watchToken).ConfigureAwait(false))
Expand Down
55 changes: 55 additions & 0 deletions tests/Aspire.Hosting.Tests/ResourceNotificationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.

using Aspire.Hosting.Tests.Utils;
using Aspire.Hosting.Utils;
using Microsoft.AspNetCore.InternalTesting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
Expand Down Expand Up @@ -399,6 +402,58 @@ public async Task PublishLogsTraceStateDetailsCorrectly()
Assert.Contains(logs, l => l.Level == LogLevel.Trace && l.Message.Contains("Resource resource1/resource1 update published:") && l.Message.Contains("ExitCode = 0"));
}

[Fact]
public async Task WaitForResourceHealthyAsyncShouldThrowsIfResourceNameDoesNotExist()
{
var resource = new CustomResource("resource1");
using var builder = TestDistributedApplicationBuilder.Create();
builder.AddResource(resource);
using var app = builder.Build();

await app.StartAsync();
var rns = app.Services.GetRequiredService<ResourceNotificationService>();

var exception = await Assert.ThrowsAsync<InvalidOperationException>(async () =>
{
await rns.WaitForResourceHealthyAsync("notexist", default);
}).DefaultTimeout();

Assert.Equal($"Resource with name 'notexist' not found.", exception.Message);
}

[Fact]
public async Task WaitForResourceAsyncShouldThrowsIfResourceNameDoesNotExist()
{
var resource = new CustomResource("resource1");
using var builder = TestDistributedApplicationBuilder.Create();
builder.AddResource(resource);
using var app = builder.Build();

await app.StartAsync();
var rns = app.Services.GetRequiredService<ResourceNotificationService>();

var exception1 = await Assert.ThrowsAsync<InvalidOperationException>(async () =>
{
await rns.WaitForResourceAsync("notexist", "Healthy", default);
}).DefaultTimeout();

Assert.Equal($"Resource with name 'notexist' not found.", exception1.Message);

var exception2 = await Assert.ThrowsAsync<InvalidOperationException>(async () =>
{
await rns.WaitForResourceAsync("notexist", @event => @event.Snapshot.HealthStatus == HealthStatus.Healthy, default);
}).DefaultTimeout();

Assert.Equal($"Resource with name 'notexist' not found.", exception2.Message);

var exception3 = await Assert.ThrowsAsync<InvalidOperationException>(async () =>
{
await rns.WaitForResourceAsync("notexist", ["state1", "state2"], default);
}).DefaultTimeout();

Assert.Equal($"Resource with name 'notexist' not found.", exception3.Message);
}

private sealed class CustomResource(string name) : Resource(name),
IResourceWithEnvironment,
IResourceWithConnectionString,
Expand Down
Loading