diff --git a/src/Aspire.Hosting/Dcp/KubernetesService.cs b/src/Aspire.Hosting/Dcp/KubernetesService.cs index 433575b050f..91caebd1de4 100644 --- a/src/Aspire.Hosting/Dcp/KubernetesService.cs +++ b/src/Aspire.Hosting/Dcp/KubernetesService.cs @@ -299,7 +299,8 @@ public Task DeleteAsync(string name, string? namespaceParameter = null, Ca #pragma warning restore CS0618 // Type or member is obsolete }, RetryOnConnectivityAndConflictErrors, - restartCancellationToken); + restartCancellationToken, + timeoutEachAttempt: true); }; await foreach (var item in PeriodicRestartAsyncEnumerable.CreateAsync(innerWatchFactory, restartInterval: TimeSpan.FromMinutes(5), cancellationToken: cancellationToken).ConfigureAwait(false)) @@ -459,7 +460,8 @@ private async Task ExecuteWithRetry( string resourceType, Func> operation, Func isRetryable, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + bool timeoutEachAttempt = false) { using var activity = ProfilingTelemetry.StartDcpKubernetesApi(configuration, operationType, resourceType); var retryCount = 0; @@ -493,7 +495,12 @@ async ValueTask EnsureKubernetesClientAsync(CancellationToken cancellationToken) ? MaxRetryDuration : KubernetesInitializationTimeout; - var resiliencePipeline = CreateKubernetesCallResiliencePipeline(retryDuration, isRetryable, activity, () => retryCount++); + var resiliencePipeline = CreateKubernetesCallResiliencePipeline( + retryDuration, + isRetryable, + activity, + () => retryCount++, + timeoutEachAttempt); return await resiliencePipeline.ExecuteAsync(async (cancellationToken) => { // Keep connection establishment inside the retry loop so kubeconfig read failures remain retryable. @@ -520,34 +527,40 @@ private static ResiliencePipeline CreateKubernetesCallResiliencePipeline( TimeSpan retryDuration, Func isRetryable, ProfilingTelemetry.ActivityScope activity, - Action recordRetry) + Action recordRetry, + bool timeoutEachAttempt = false) { - var resiliencePipeline = new ResiliencePipelineBuilder() - .AddTimeout(new TimeoutStrategyOptions + var timeoutOptions = new TimeoutStrategyOptions + { + Timeout = retryDuration, + OnTimeout = (_) => { - Timeout = retryDuration, - OnTimeout = (_) => - { - activity.AddKubernetesApiTimeout(); - return ValueTask.CompletedTask; - } - }) - .AddRetry(new RetryStrategyOptions() + activity.AddKubernetesApiTimeout(); + return ValueTask.CompletedTask; + } + }; + var retryOptions = new RetryStrategyOptions + { + ShouldHandle = timeoutEachAttempt + ? new PredicateBuilder().Handle(isRetryable).Handle() + : new PredicateBuilder().Handle(isRetryable), + BackoffType = DelayBackoffType.Exponential, + MaxRetryAttempts = int.MaxValue, + Delay = s_initialRetryDelay, + MaxDelay = TimeSpan.FromSeconds(5), + OnRetry = (retry) => { - ShouldHandle = new PredicateBuilder().Handle(isRetryable), - BackoffType = DelayBackoffType.Exponential, - MaxRetryAttempts = int.MaxValue, - Delay = s_initialRetryDelay, - MaxDelay = TimeSpan.FromSeconds(5), - OnRetry = (retry) => - { - recordRetry(); - activity.AddKubernetesApiRetry(retry.AttemptNumber, retry.RetryDelay, retry.Outcome.Exception); - return ValueTask.CompletedTask; - } - }) - .Build(); - return resiliencePipeline; + recordRetry(); + activity.AddKubernetesApiRetry(retry.AttemptNumber, retry.RetryDelay, retry.Outcome.Exception); + return ValueTask.CompletedTask; + } + }; + + // Regular API calls have one total retry budget. Watches instead retry a stalled connection + // after each timeout until their outer periodic-restart token is canceled. + return timeoutEachAttempt + ? new ResiliencePipelineBuilder().AddRetry(retryOptions).AddTimeout(timeoutOptions).Build() + : new ResiliencePipelineBuilder().AddTimeout(timeoutOptions).AddRetry(retryOptions).Build(); } private ResiliencePipeline CreateReadKubeconfigResiliencePipeline() diff --git a/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs b/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs index 51c72ef36dd..5d3591904f2 100644 --- a/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs +++ b/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs @@ -26,7 +26,17 @@ public static async IAsyncEnumerable CreateAsync(Func enumerable; + try + { + enumerable = await enumerableFactory(lastValue, cts.Token).ConfigureAwait(false); + } + catch (OperationCanceledException ex) when (ex.CancellationToken == cts.Token && cts.IsCancellationRequested && !cancellationToken.IsCancellationRequested) + { + // The restart interval can expire while the factory is still establishing a streaming + // connection. Start a fresh factory call just as we do when enumeration is canceled. + continue; + } var enumerator = enumerable.GetAsyncEnumerator(cts.Token); try @@ -42,7 +52,7 @@ public static async IAsyncEnumerable CreateAsync(Func CreateAsync(Func enumerable; + try + { + enumerable = await enumerableFactory(lastValue, cts.Token).ConfigureAwait(false); + } + catch (OperationCanceledException ex) when (ex.CancellationToken == cts.Token && cts.IsCancellationRequested && !cancellationToken.IsCancellationRequested) + { + // The restart interval can expire while the factory is still establishing a streaming + // connection. Start a fresh factory call just as we do when enumeration is canceled. + continue; + } var enumerator = enumerable.GetAsyncEnumerator(cts.Token); try @@ -98,7 +118,7 @@ public static async IAsyncEnumerable CreateAsync(Func/dev/null | head -1 | sed 's/.*Aspire\\.Hosting\\.//;s/\\.nupkg//') && aspire config set sdk.version \"$SDK_VER\" -g && export ASPIRE_CLI_CHANNEL=local ASPIRE_CLI_VERSION=\"$SDK_VER\" ASPIRE_CLI_PACKAGES=\"$HOME/.aspire/hives/local/packages\"" + ], + AspireCliShellCommandHelpers.GetConfigureLocalHiveCommands()); + } + [Fact] public void GetRecordAspireCliVersionCommand_IsBestEffort() { @@ -786,6 +809,28 @@ public void FromLocalArchive_ExtractsExpectedVersionFromNupkg() } } + [Theory] + [InlineData("14.0.0-pr.20466.ga2bed197", "pr-20466")] + [InlineData("13.3.0-pr.1234.a1b2c3d4", "pr-1234")] + [InlineData("14.0.0-pr.20466.xyz", "local")] + [InlineData("14.0.0-ci", "local")] + public void FromLocalArchive_SelectsHiveMatchingPackageVersion(string version, string expectedHiveLabel) + { + var tempDir = Directory.CreateTempSubdirectory("cli-archives-test"); + try + { + File.WriteAllText(Path.Combine(tempDir.FullName, $"Aspire.Cli.{version}.nupkg"), ""); + + var strategy = CliInstallStrategy.FromLocalArchive(tempDir.FullName); + + Assert.Equal(expectedHiveLabel, strategy.LocalArchiveHiveLabel); + } + finally + { + tempDir.Delete(recursive: true); + } + } + [Fact] public void FromLocalArchive_IgnoresRidSpecificCliNupkg() { diff --git a/tests/Aspire.Cli.EndToEnd.Tests/NewChannelNuGetConfigTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/NewChannelNuGetConfigTests.cs index 6fb860e8482..e70eb0da75d 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/NewChannelNuGetConfigTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/NewChannelNuGetConfigTests.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Xml.Linq; using Aspire.Cli.EndToEnd.Tests.Helpers; using Hex1b.Automation; using Xunit; @@ -66,6 +67,18 @@ public async Task AspireNew_CreatesNuGetConfig_BasedOnChannel(string? channel, b { Assert.True(File.Exists(nugetConfigPath), $"Expected nuget.config to be created for channel '{channel ?? "(default)"}' at: {nugetConfigPath}"); + + if (channel is null && strategy.Mode is CliInstallMode.LocalArchive) + { + var expectedHiveLabel = strategy.LocalArchiveHiveLabel; + var packageSources = XDocument.Load(nugetConfigPath) + .Descendants("packageSources") + .Elements("add") + .Select(element => (string?)element.Attribute("value")) + .OfType(); + + Assert.Contains(packageSources, source => source.Replace('\\', '/').EndsWith($"/hives/{expectedHiveLabel}/packages", StringComparison.Ordinal)); + } } else { diff --git a/tests/Aspire.Dashboard.Tests/Integration/Playwright/DashboardInteractionsTests.cs b/tests/Aspire.Dashboard.Tests/Integration/Playwright/DashboardInteractionsTests.cs index 05e96943082..499aa25b413 100644 --- a/tests/Aspire.Dashboard.Tests/Integration/Playwright/DashboardInteractionsTests.cs +++ b/tests/Aspire.Dashboard.Tests/Integration/Playwright/DashboardInteractionsTests.cs @@ -242,15 +242,14 @@ await RunTestAsync(async page => var bottomButton = page.Locator(".scroll-to-bottom"); await Assertions.Expect(bottomButton).ToBeVisibleAsync(); + // Headless browsers can skip every intermediate compositor frame under load. Capture the native + // smooth-scroll request, then dispatch scrollend explicitly so the content-growth behavior is deterministic. await page.EvaluateAsync(""" () => { const region = document.getElementById('scroll-region'); - const initialBottom = region.scrollHeight - region.clientHeight; - window.__grewDuringScroll = false; - region.addEventListener('scroll', () => { - window.__grewDuringScroll = region.scrollTop > 0 && region.scrollTop < initialBottom; - region.querySelector('.scroll-content').style.height = '4000px'; - }, { once: true }); + region.scrollTo = options => { + window.__scrollToBottomRequest = options; + }; document.querySelector('.scroll-to-bottom').addEventListener('click', event => { window.__hiddenOnClick = event.currentTarget.hidden; }, { once: true }); @@ -259,10 +258,24 @@ await page.EvaluateAsync(""" await bottomButton.ClickAsync(); Assert.True(await page.EvaluateAsync("() => window.__hiddenOnClick")); + Assert.True(await page.EvaluateAsync(""" + () => { + const region = document.getElementById('scroll-region'); + return window.__scrollToBottomRequest.behavior === 'smooth' && + window.__scrollToBottomRequest.top === region.scrollHeight; + } + """)); + await page.EvaluateAsync(""" + () => { + const region = document.getElementById('scroll-region'); + region.querySelector('.scroll-content').style.height = '4000px'; + region.dispatchEvent(new Event('scrollend')); + } + """); await page.WaitForFunctionAsync(""" () => { const region = document.getElementById('scroll-region'); - return window.__grewDuringScroll && region.scrollHeight >= 4000 && + return region.scrollHeight >= 4000 && Math.abs(region.scrollHeight - region.clientHeight - region.scrollTop) < 1; } """).DefaultTimeout(); diff --git a/tests/Aspire.Deployment.EndToEnd.Tests/Helpers/DeploymentE2EAutomatorHelpers.cs b/tests/Aspire.Deployment.EndToEnd.Tests/Helpers/DeploymentE2EAutomatorHelpers.cs index 740630f2b6c..6e3ce650107 100644 --- a/tests/Aspire.Deployment.EndToEnd.Tests/Helpers/DeploymentE2EAutomatorHelpers.cs +++ b/tests/Aspire.Deployment.EndToEnd.Tests/Helpers/DeploymentE2EAutomatorHelpers.cs @@ -76,6 +76,10 @@ await auto.RunCommandAsync( counter, TimeSpan.FromSeconds(120)); await auto.SourceAspireEnvironmentAsync(counter, includeBundlePath); + if (strategy.LocalArchiveHiveLabel == "local") + { + await auto.ConfigureLocalHiveAsync(counter); + } break; case CliInstallMode.InstallScript: diff --git a/tests/Aspire.Hosting.Tests/Dcp/KubernetesServiceTests.cs b/tests/Aspire.Hosting.Tests/Dcp/KubernetesServiceTests.cs index 751f38e921f..e69b449bd7d 100644 --- a/tests/Aspire.Hosting.Tests/Dcp/KubernetesServiceTests.cs +++ b/tests/Aspire.Hosting.Tests/Dcp/KubernetesServiceTests.cs @@ -167,6 +167,34 @@ public async Task WatchAsync_DoesNotMarkApiReady_WhileHttpResponseIsPending() } } + [Fact] + public async Task WatchAsync_RemainsActiveBeyondApiRetryTimeout() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(20)); + using var watchCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token); + + var (service, kubeconfigPath, fileSystem) = CreateService( + maxRetryDuration: TimeSpan.FromMilliseconds(100), + kubernetesInitializationTimeout: TimeSpan.FromMilliseconds(250)); + using var disposableFileSystem = fileSystem; + using var disposableService = service; + + await using var server = await TestDcpApiServer.StartAsync(cts.Token); + server.BlockWatchResponses(); + WriteKubeconfig(kubeconfigPath, server.Port); + + await using var watchEnumerator = service.WatchAsync(cancellationToken: watchCts.Token).GetAsyncEnumerator(); + var watchTask = watchEnumerator.MoveNextAsync().AsTask(); + await server.WaitForWatchRequestAsync(cts.Token); + + await server.WaitForWatchRequestCountAsync(2, cts.Token); + Assert.False(watchTask.IsCompleted); + + watchCts.Cancel(); + await server.WaitForRequestCancellationAsync(cts.Token); + await Assert.ThrowsAnyAsync(() => watchTask); + } + // Verifies that establishing the connection survives a partially-written kubeconfig: when the file exists // but DCP has only flushed part of it (so it does not yet parse as a valid kubeconfig), the read is retried // and the operation succeeds once the complete, valid kubeconfig is written. @@ -403,6 +431,14 @@ public Task WaitForWatchRequestAsync(CancellationToken cancellationToken) return _responseState.WatchRequestArrived.Task.WaitAsync(cancellationToken); } + public async Task WaitForWatchRequestCountAsync(int expectedCount, CancellationToken cancellationToken) + { + while (Volatile.Read(ref _responseState.WatchRequestCount) < expectedCount) + { + await Task.Delay(TimeSpan.FromMilliseconds(10), cancellationToken); + } + } + public Task WaitForRequestCancellationAsync(CancellationToken cancellationToken) { return _responseState.RequestCancellationObserved.Task.WaitAsync(cancellationToken); @@ -431,6 +467,7 @@ public static async Task StartAsync( && string.Equals(watchValues.ToString(), "true", StringComparison.OrdinalIgnoreCase); if (isWatchRequest && Volatile.Read(ref responseState.BlockWatchResponses)) { + Interlocked.Increment(ref responseState.WatchRequestCount); responseState.WatchRequestArrived.TrySetResult(true); try { @@ -487,6 +524,7 @@ private sealed class ResponseState { public bool BlockWatchResponses; public int RequestCount; + public int WatchRequestCount; public TaskCompletionSource RequestCancellationObserved { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public long ResponseDelayTicks; diff --git a/tests/Aspire.Hosting.Tests/Utils/PeriodicRestartAsyncEnumerableTests.cs b/tests/Aspire.Hosting.Tests/Utils/PeriodicRestartAsyncEnumerableTests.cs index 2d8c0685c06..f48d2c6704b 100644 --- a/tests/Aspire.Hosting.Tests/Utils/PeriodicRestartAsyncEnumerableTests.cs +++ b/tests/Aspire.Hosting.Tests/Utils/PeriodicRestartAsyncEnumerableTests.cs @@ -56,6 +56,184 @@ await Assert.ThrowsAnyAsync(async () => Assert.True(s_activeRunningEnumerables == 0, "expected all enumerables to be ended after cancellation"); } + [Fact] + public async Task FactoryIsRecreatedWhenRestartTokenExpires() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + var secondFactoryCall = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var factoryCallCount = 0; + + async Task> InnerFactory(int? lastValue, CancellationToken cancellationToken) + { + if (Interlocked.Increment(ref factoryCallCount) == 2) + { + secondFactoryCall.SetResult(); + } + + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + return CountingAsyncEnumerable(0, TimeSpan.Zero, cancellationToken); + } + + await using var enumerator = PeriodicRestartAsyncEnumerable + .CreateAsync(InnerFactory, restartInterval: TimeSpan.FromMilliseconds(100), cancellationToken: cts.Token) + .GetAsyncEnumerator(); + var moveNextTask = enumerator.MoveNextAsync().AsTask(); + + await secondFactoryCall.Task.WaitAsync(cts.Token); + cts.Cancel(); + + await Assert.ThrowsAnyAsync(() => moveNextTask); + } + + [Fact] + public async Task ClassFactoryIsRecreatedWhenRestartTokenExpires() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + var secondFactoryCall = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var factoryCallCount = 0; + + async Task> InnerFactory(string? lastValue, CancellationToken cancellationToken) + { + if (Interlocked.Increment(ref factoryCallCount) == 2) + { + secondFactoryCall.SetResult(); + } + + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + return EmptyStringAsyncEnumerable(); + } + + await using var enumerator = PeriodicRestartAsyncEnumerable + .CreateAsync(InnerFactory, restartInterval: TimeSpan.FromMilliseconds(100), cancellationToken: cts.Token) + .GetAsyncEnumerator(); + var moveNextTask = enumerator.MoveNextAsync().AsTask(); + + await secondFactoryCall.Task.WaitAsync(cts.Token); + cts.Cancel(); + + await Assert.ThrowsAnyAsync(() => moveNextTask); + } + + [Fact] + public async Task FactoryCancellationFromIndependentTokenAfterRestartExpirationIsPropagated() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + using var factoryCts = new CancellationTokenSource(); + factoryCts.Cancel(); + var factoryCallCount = 0; + + var enumerable = PeriodicRestartAsyncEnumerable.CreateAsync( + async (_, restartToken) => + { + Assert.Equal(1, Interlocked.Increment(ref factoryCallCount)); + + var restartTokenCancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var registration = restartToken.Register(restartTokenCancelled.SetResult); + await restartTokenCancelled.Task.WaitAsync(cts.Token); + + factoryCts.Token.ThrowIfCancellationRequested(); + return CountingAsyncEnumerable(0, TimeSpan.Zero, restartToken); + }, + restartInterval: TimeSpan.FromMilliseconds(100), + cancellationToken: cts.Token); + await using var enumerator = enumerable.GetAsyncEnumerator(); + + var exception = await Assert.ThrowsAsync( + async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(cts.Token)); + + Assert.Equal(factoryCts.Token, exception.CancellationToken); + Assert.Equal(1, factoryCallCount); + } + + [Fact] + public async Task ClassFactoryCancellationFromIndependentTokenAfterRestartExpirationIsPropagated() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + using var factoryCts = new CancellationTokenSource(); + factoryCts.Cancel(); + var factoryCallCount = 0; + + var enumerable = PeriodicRestartAsyncEnumerable.CreateAsync( + async (_, restartToken) => + { + Assert.Equal(1, Interlocked.Increment(ref factoryCallCount)); + + var restartTokenCancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var registration = restartToken.Register(restartTokenCancelled.SetResult); + await restartTokenCancelled.Task.WaitAsync(cts.Token); + + factoryCts.Token.ThrowIfCancellationRequested(); + return EmptyStringAsyncEnumerable(); + }, + restartInterval: TimeSpan.FromMilliseconds(100), + cancellationToken: cts.Token); + await using var enumerator = enumerable.GetAsyncEnumerator(); + + var exception = await Assert.ThrowsAsync( + async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(cts.Token)); + + Assert.Equal(factoryCts.Token, exception.CancellationToken); + Assert.Equal(1, factoryCallCount); + } + + [Fact] + public async Task EnumeratorCancellationFromIndependentTokenAfterRestartExpirationIsPropagated() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + using var enumeratorCts = new CancellationTokenSource(); + enumeratorCts.Cancel(); + var factoryCallCount = 0; + var disposeCount = 0; + + Task> InnerFactory(int? lastValue, CancellationToken restartToken) + { + Assert.Equal(1, Interlocked.Increment(ref factoryCallCount)); + return Task.FromResult(ThrowAfterCancellationAsync(0, restartToken, enumeratorCts.Token, () => Interlocked.Increment(ref disposeCount))); + } + + var enumerable = PeriodicRestartAsyncEnumerable.CreateAsync( + InnerFactory, + restartInterval: TimeSpan.FromMilliseconds(100), + cancellationToken: cts.Token); + await using var enumerator = enumerable.GetAsyncEnumerator(); + + var exception = await Assert.ThrowsAsync( + async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(cts.Token)); + + Assert.Equal(enumeratorCts.Token, exception.CancellationToken); + Assert.Equal(1, factoryCallCount); + Assert.Equal(1, disposeCount); + } + + [Fact] + public async Task ClassEnumeratorCancellationFromIndependentTokenAfterRestartExpirationIsPropagated() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + using var enumeratorCts = new CancellationTokenSource(); + enumeratorCts.Cancel(); + var factoryCallCount = 0; + var disposeCount = 0; + + Task> InnerFactory(string? lastValue, CancellationToken restartToken) + { + Assert.Equal(1, Interlocked.Increment(ref factoryCallCount)); + return Task.FromResult(ThrowAfterCancellationAsync(string.Empty, restartToken, enumeratorCts.Token, () => Interlocked.Increment(ref disposeCount))); + } + + var enumerable = PeriodicRestartAsyncEnumerable.CreateAsync( + InnerFactory, + restartInterval: TimeSpan.FromMilliseconds(100), + cancellationToken: cts.Token); + await using var enumerator = enumerable.GetAsyncEnumerator(); + + var exception = await Assert.ThrowsAsync( + async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(cts.Token)); + + Assert.Equal(enumeratorCts.Token, exception.CancellationToken); + Assert.Equal(1, factoryCallCount); + Assert.Equal(1, disposeCount); + } + static async IAsyncEnumerable CountingAsyncEnumerable(int start, TimeSpan delay, [EnumeratorCancellation] CancellationToken cancellationToken) { var value = start; @@ -68,6 +246,33 @@ static async IAsyncEnumerable CountingAsyncEnumerable(int start, TimeSpan d cancellationToken.ThrowIfCancellationRequested(); } + static async IAsyncEnumerable EmptyStringAsyncEnumerable() + { + await Task.Yield(); + yield break; + } + + static async IAsyncEnumerable ThrowAfterCancellationAsync( + T value, + [EnumeratorCancellation] CancellationToken restartToken, + CancellationToken exceptionToken, + Action onDispose) + { + var restartTokenCancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var registration = restartToken.Register(restartTokenCancelled.SetResult); + + try + { + await restartTokenCancelled.Task; + exceptionToken.ThrowIfCancellationRequested(); + yield return value; + } + finally + { + onDispose(); + } + } + static async IAsyncEnumerable RefCountingAsyncEnumerable(int start, TimeSpan delay, [EnumeratorCancellation] CancellationToken cancellationToken) { Interlocked.Increment(ref s_totalEnumerablesRun); diff --git a/tests/Aspire.Templates.Tests/TemplateTestsBase.cs b/tests/Aspire.Templates.Tests/TemplateTestsBase.cs index 478c9866ccf..76f1a8b1802 100644 --- a/tests/Aspire.Templates.Tests/TemplateTestsBase.cs +++ b/tests/Aspire.Templates.Tests/TemplateTestsBase.cs @@ -203,7 +203,7 @@ private static async Task CheckDashboardHasResourcesActualAsync(W await Task.Delay(500); // _testOutput.WriteLine($"Checking for rows again"); - var rowsLocator = dashboardPageWrapper.Page.Locator("//tr[@class='fluent-data-grid-row hover resource-row']"); + var rowsLocator = dashboardPageWrapper.Page.Locator(".main-grid tr.resource-row"); var allRows = await rowsLocator.AllAsync(); // _testOutput.WriteLine($"found rows#: {allRows.Count}"); if (allRows.Count == 0) @@ -215,7 +215,7 @@ private static async Task CheckDashboardHasResourcesActualAsync(W foreach (var rowLoc in allRows) { // get the cells - var cellLocs = await rowLoc.Locator("//td[@role='gridcell']").AllAsync(); + var cellLocs = await rowLoc.Locator("[role='gridcell']").AllAsync(); // is the resource name expected? var resourceNameCell = cellLocs[0]; diff --git a/tests/Shared/CliInstallStrategy.cs b/tests/Shared/CliInstallStrategy.cs index 87f27c0d571..a6c1ce2e511 100644 --- a/tests/Shared/CliInstallStrategy.cs +++ b/tests/Shared/CliInstallStrategy.cs @@ -67,7 +67,9 @@ internal static class AspireCliShellCommandHelpers private static readonly string[] s_configureLocalHiveCommands = [ "aspire config set channel local -g", - "SDK_VER=$(ls ~/.aspire/hives/local/packages/Aspire.Hosting.*.nupkg 2>/dev/null | head -1 | sed 's/.*Aspire\\.Hosting\\.//;s/\\.nupkg//') && aspire config set sdk.version \"$SDK_VER\" -g" + // The CLI identity takes precedence over user configuration. Override all identity fields so + // archive builds stamped as daily still scaffold projects from the local package directory. + "SDK_VER=$(ls ~/.aspire/hives/local/packages/Aspire.Hosting.*.nupkg 2>/dev/null | head -1 | sed 's/.*Aspire\\.Hosting\\.//;s/\\.nupkg//') && aspire config set sdk.version \"$SDK_VER\" -g && export ASPIRE_CLI_CHANNEL=local ASPIRE_CLI_VERSION=\"$SDK_VER\" ASPIRE_CLI_PACKAGES=\"$HOME/.aspire/hives/local/packages\"" ]; internal static string GetPrepareAspireEnvironmentCommand() @@ -269,6 +271,22 @@ internal sealed class CliInstallStrategy /// public string? ExpectedVersion { get; } + /// + /// Gets the package hive label selected by the local-archive installer. + /// + public string LocalArchiveHiveLabel + { + get + { + if (Mode != CliInstallMode.LocalArchive) + { + throw new InvalidOperationException($"{nameof(LocalArchiveHiveLabel)} is only available for {nameof(CliInstallMode.LocalArchive)} strategies."); + } + + return CliPackageDiscovery.GetHiveLabel(ExpectedVersion); + } + } + /// /// Gets whether the Docker dotnet tool install command needs the generated NuGet.config for internal/prerelease feeds. /// diff --git a/tests/Shared/CliPackageDiscovery.cs b/tests/Shared/CliPackageDiscovery.cs index 8ef301a8502..b0684c4d208 100644 --- a/tests/Shared/CliPackageDiscovery.cs +++ b/tests/Shared/CliPackageDiscovery.cs @@ -19,6 +19,16 @@ internal static bool IsValidVersion(string version) return VersionPattern().IsMatch(version); } + internal static string GetHiveLabel(string? version) + { + if (version is not null && PullRequestVersionPattern().Match(version) is { Success: true } match) + { + return $"pr-{match.Groups[1].Value}"; + } + + return "local"; + } + internal static CliPackageInfo FindAspireCliPointerPackage(string packageDirectory) { return TryFindAspireCliPointerPackage(packageDirectory) @@ -96,6 +106,9 @@ private static string GetAvailableAspireCliPackageNames(string packageDirectory) [GeneratedRegex(@"^[0-9A-Za-z.\-]+$")] private static partial Regex VersionPattern(); + [GeneratedRegex(@"-pr\.([0-9]+)\.[0-9a-g]+$")] + private static partial Regex PullRequestVersionPattern(); + [GeneratedRegex(@"^Aspire\.Cli\.(win|linux|linux-musl|osx)-(x64|arm64)\.", RegexOptions.IgnoreCase)] private static partial Regex RidSpecificPackagePattern(); }