Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 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
33 changes: 33 additions & 0 deletions src/Aspire.Hosting/ApplicationModel/ResourceNotificationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,39 @@ public async Task<ResourceEvent> WaitForResourceHealthyAsync(string resourceName
cancellationToken).ConfigureAwait(false);
}

/// <summary>
/// Waits for a resource to be ready.
/// </summary>
/// <param name="resourceName">The name of the resource.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A task.</returns>
Copy link
Preview

Copilot AI Aug 6, 2025

Choose a reason for hiding this comment

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

The return value documentation is incomplete. It should specify that it returns 'A task that completes with a ResourceEvent when the resource is ready.' to be consistent with the WaitForResourceHealthyAsync method documentation.

Suggested change
/// <returns>A task.</returns>
/// <returns>A task that completes with a ResourceEvent when the resource is ready.</returns>

Copilot uses AI. Check for mistakes.

/// <remarks>
/// <para>
/// This method returns a task that will complete when the resource's ResourceReadyEvent
/// is present and its associated EventTask has completed. This allows developers using
/// the lower-level API to fine-tune what lifecycle event they wait for.
/// </para>
/// <para>
/// If the resource doesn't have a ResourceReadyEvent or if the EventTask doesn't complete
Copy link
Member

Choose a reason for hiding this comment

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

@copilot this paragraph is incorrect. There should always be a ResourceReadyEvent. However we should probably remove this remarks section because it is referring to the ResourceReadyEvent internal field, not the class. Instead simply have a paragraph in remarks that notes that this method returns a task that completes when all subscriptions to the ResourceReadyEvent have completed (if any). If any throw an exception, this method will throw an exception. If none are present this method will return immediately.

Also add a paragraph that notes that this method does not explicitly wait for the resource to be healthy and that it can be used independently of or together with the WaitForResourceHealthyAsync method.

Add a matching comment to the remarks for the WaitForResourceHealthyAsync method.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Updated the documentation as requested. The WaitForResourceReadyAsync remarks now correctly explain that it completes when all subscriptions to the ResourceReadyEvent have completed, and added relationship notes to both WaitForResourceHealthyAsync method overloads. Commit: a71af20

/// before <paramref name="cancellationToken"/> is signaled, this method will throw
/// <see cref="OperationCanceledException"/>.
/// </para>
/// </remarks>
public async Task<ResourceEvent> WaitForResourceReadyAsync(string resourceName, CancellationToken cancellationToken = default)
{
_logger.LogDebug("Waiting for resource '{Name}' to be ready.", resourceName);

// First wait for the ResourceReadyEvent to be present
var resourceEvent = await WaitForResourceCoreAsync(resourceName, re => re.Snapshot.ResourceReadyEvent is not null, cancellationToken: cancellationToken).ConfigureAwait(false);

// Then await the EventTask to complete
await resourceEvent.Snapshot.ResourceReadyEvent!.EventTask.WaitAsync(cancellationToken).ConfigureAwait(false);

_logger.LogDebug("Finished waiting for resource '{Name}' to be ready.", resourceName);

return resourceEvent;
}

/// <summary>
/// Waits for a resource to become healthy.
/// </summary>
Expand Down
157 changes: 156 additions & 1 deletion tests/Aspire.Hosting.Tests/ResourceNotificationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@
// 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.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;

namespace Aspire.Hosting.Tests;

public class ResourceNotificationTests
public class ResourceNotificationTests(ITestOutputHelper outputHelper)
{
[Fact]
public void InitialStateCanBeSpecified()
Expand Down Expand Up @@ -526,6 +528,159 @@ await notificationService.PublishUpdateAsync(resource, snapshot => snapshot with
Assert.Equal("Starting", value.Snapshot.State?.Text);
}

[Fact]
public async Task WaitForResourceReadyAsync_ReturnsWhenResourceReadyEventIsPresent()
{
var resource = new CustomResource("myResource");
var notificationService = ResourceNotificationServiceTestHelpers.Create();

// Create a completed task for the ResourceReadyEvent
var completedTask = Task.CompletedTask;
var resourceReadyEvent = new EventSnapshot(completedTask);

var waitTask = notificationService.WaitForResourceReadyAsync("myResource");

// Publish an update with a ResourceReadyEvent
await notificationService.PublishUpdateAsync(resource, snapshot => snapshot with
{
ResourceReadyEvent = resourceReadyEvent
}).DefaultTimeout();

var result = await waitTask.DefaultTimeout();

Assert.Equal(resource, result.Resource);
Assert.Equal("myResource", result.ResourceId);
Assert.NotNull(result.Snapshot.ResourceReadyEvent);
}

[Fact]
public async Task WaitForResourceReadyAsync_WaitsForEventTaskToComplete()
{
var resource = new CustomResource("myResource");
var notificationService = ResourceNotificationServiceTestHelpers.Create();

// Create a task completion source to control when the EventTask completes
var tcs = new TaskCompletionSource();
var resourceReadyEvent = new EventSnapshot(tcs.Task);

var waitTask = notificationService.WaitForResourceReadyAsync("myResource");

// Publish an update with a ResourceReadyEvent that hasn't completed yet
await notificationService.PublishUpdateAsync(resource, snapshot => snapshot with
{
ResourceReadyEvent = resourceReadyEvent
}).DefaultTimeout();

// Wait should not complete yet since the EventTask hasn't completed
await Task.Delay(100);
Assert.False(waitTask.IsCompleted);

// Complete the EventTask
tcs.SetResult();

// Now the wait should complete
var result = await waitTask.DefaultTimeout();

Assert.Equal(resource, result.Resource);
Assert.Equal("myResource", result.ResourceId);
Assert.NotNull(result.Snapshot.ResourceReadyEvent);
}

[Fact]
public async Task WaitForResourceReadyAsync_ThrowsOperationCanceledExceptionWhenCanceled()
{
var notificationService = ResourceNotificationServiceTestHelpers.Create();

using var cts = new CancellationTokenSource();
var waitTask = notificationService.WaitForResourceReadyAsync("myResource", cts.Token);

cts.Cancel();

await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
await waitTask;
}).DefaultTimeout();
}

[Fact]
public async Task WaitForResourceReadyAsync_ThrowsOperationCanceledExceptionWhenEventTaskIsCanceled()
{
var resource = new CustomResource("myResource");
var notificationService = ResourceNotificationServiceTestHelpers.Create();

// Create a canceled task for the ResourceReadyEvent
using var eventCts = new CancellationTokenSource();
eventCts.Cancel();
var canceledTask = Task.FromCanceled(eventCts.Token);
var resourceReadyEvent = new EventSnapshot(canceledTask);

var waitTask = notificationService.WaitForResourceReadyAsync("myResource");

// Publish an update with a ResourceReadyEvent that has a canceled task
await notificationService.PublishUpdateAsync(resource, snapshot => snapshot with
{
ResourceReadyEvent = resourceReadyEvent
}).DefaultTimeout();

await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
await waitTask;
}).DefaultTimeout();
}

[Fact]
public async Task WaitForResourceReadyAsync_ReturnsImmediatelyWhenResourceReadyEventAlreadyPresent()
{
var resource = new CustomResource("myResource");
var notificationService = ResourceNotificationServiceTestHelpers.Create();

// Create a completed task for the ResourceReadyEvent
var completedTask = Task.CompletedTask;
var resourceReadyEvent = new EventSnapshot(completedTask);

// Publish the ResourceReadyEvent first
await notificationService.PublishUpdateAsync(resource, snapshot => snapshot with
{
ResourceReadyEvent = resourceReadyEvent
}).DefaultTimeout();

// Wait should complete immediately since the event is already present and completed
var waitTask = notificationService.WaitForResourceReadyAsync("myResource");
var result = await waitTask.DefaultTimeout();

Assert.True(waitTask.IsCompletedSuccessfully);
Assert.Equal(resource, result.Resource);
Assert.Equal("myResource", result.ResourceId);
Assert.NotNull(result.Snapshot.ResourceReadyEvent);
}

[Fact]
public async Task WaitForResourceReadyAsync_EndToEnd()
{
using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(outputHelper);

var ready = false;

var cache = builder.AddRedis("cache")
.OnResourceReady((red, e, ct) =>
{
ready = true;
return Task.CompletedTask;
});

var app = builder.Build();

await app.StartAsync();

var resourceNotification = app.Services.GetRequiredService<ResourceNotificationService>();

// expected this to not complete until the OnResourceReady callback completes
await resourceNotification.WaitForResourceReadyAsync(cache.Resource.Name);
Assert.True(ready, "Resource should be ready after waiting.");

await app.StopAsync();
}

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