| File: ApplicationModel\ConcurrentValueResolver.cs | Web Access |
| Project: src\src\Aspire.Hosting\Aspire.Hosting.csproj (Aspire.Hosting) |
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.ExceptionServices; namespace Aspire.Hosting.ApplicationModel; /// <summary> /// Resolves the values that make up a combined value concurrently. /// </summary> /// <remarks> /// Reading values one at a time hides later blockers. For example, an expression that uses two parameters /// without values would only report the second parameter as unresolved after the first one is set. Starting /// every read up front lets each pending value report itself at the same time. /// </remarks> internal static class ConcurrentValueResolver { /// <summary> /// Resolves every source concurrently and returns the results in source order. /// </summary> /// <remarks> /// When a read fails, pending reads are canceled and no more reads are started because the combined /// value can no longer be produced. /// The exception thrown is the lowest-index failure that wasn't caused by that cancellation, so when several /// reads fail independently the reported error doesn't depend on which one failed first. A read that observes /// the cancellation before reaching its own failure throws <see cref="OperationCanceledException"/> instead, /// so its failure never occurs and can't be reported. /// Exceptions from cancellation callbacks do not replace the read failure. /// </remarks> public static async ValueTask<TResult[]> ResolveAllAsync<TResult>( int count, Func<int, CancellationToken, ValueTask<TResult>> resolve, CancellationToken cancellationToken) { var results = new TResult[count]; if (count == 0) { return results; } if (count == 1) { results[0] = await resolve(0, cancellationToken).ConfigureAwait(false); return results; } using var failureCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var reads = new Task<ReadResult<TResult>>[count]; var startedCount = 0; for (; startedCount < reads.Length && !failureCts.IsCancellationRequested; startedCount++) { reads[startedCount] = ReadAsync(startedCount, resolve, failureCts); } // Every started read must be awaited before failureCts is disposed, even after a failure is found. ExceptionDispatchInfo? firstFailure = null; ExceptionDispatchInfo? firstCanceledRead = null; for (var i = 0; i < startedCount; i++) { var read = await reads[i].ConfigureAwait(false); if (read.Failure is null) { results[i] = read.Value; } else if (read.IsFault) { firstFailure ??= read.Failure; } else { firstCanceledRead ??= read.Failure; } } // When the caller's token is canceled, no read caused the cancellation, so the // lowest-index cancellation exception is reported instead. (firstFailure ?? firstCanceledRead)?.Throw(); if (startedCount < reads.Length) { // Caller cancellation can stop the loop without any started read reporting an error. cancellationToken.ThrowIfCancellationRequested(); } return results; } private static async Task<ReadResult<TResult>> ReadAsync<TResult>( int index, Func<int, CancellationToken, ValueTask<TResult>> resolve, CancellationTokenSource failureCts) { try { return new(await resolve(index, failureCts.Token).ConfigureAwait(false), Failure: null, IsFault: false); } catch (Exception ex) { // Cancellation observed after a sibling failed (or after the caller canceled) is a side effect, // not a fault. Any other exception is an independent fault even when it arrives after cancellation // was requested, for example from a provider that ignores the token while running a callback. // Classifying by exception type rather than by timing keeps the lowest-index fault as the // reported error regardless of which fault happens first. var isFault = ex is not OperationCanceledException || !failureCts.IsCancellationRequested; try { failureCts.Cancel(); } catch (AggregateException) { // Cancellation is best-effort. Report the read failure, not errors from canceling sibling reads. // Revisit reporting callback errors separately if user feedback shows they are needed for diagnostics. } return new(default!, ExceptionDispatchInfo.Capture(ex), isFault); } } private readonly record struct ReadResult<TResult>(TResult Value, ExceptionDispatchInfo? Failure, bool IsFault); }