Skip to content
69 changes: 41 additions & 28 deletions src/Aspire.Hosting/Dcp/KubernetesService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,8 @@ public Task<T> DeleteAsync<T>(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))
Expand Down Expand Up @@ -459,7 +460,8 @@ private async Task<TResult> ExecuteWithRetry<TResult>(
string resourceType,
Func<DcpKubernetesClient, CancellationToken, Task<TResult>> operation,
Func<Exception, bool> isRetryable,
CancellationToken cancellationToken)
CancellationToken cancellationToken,
bool timeoutEachAttempt = false)
{
using var activity = ProfilingTelemetry.StartDcpKubernetesApi(configuration, operationType, resourceType);
var retryCount = 0;
Expand Down Expand Up @@ -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.
Expand All @@ -520,34 +527,40 @@ private static ResiliencePipeline CreateKubernetesCallResiliencePipeline(
TimeSpan retryDuration,
Func<Exception, bool> 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<TimeoutRejectedException>()
: 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()
Expand Down
28 changes: 24 additions & 4 deletions src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,17 @@ public static async IAsyncEnumerable<T> CreateAsync<T>(Func<T?, CancellationToke
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(restartInterval);

var enumerable = await enumerableFactory(lastValue, cts.Token).ConfigureAwait(false);
IAsyncEnumerable<T> 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
Expand All @@ -42,7 +52,7 @@ public static async IAsyncEnumerable<T> CreateAsync<T>(Func<T?, CancellationToke
break;
}
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
catch (OperationCanceledException ex) when (ex.CancellationToken == cts.Token && cts.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
// If the restart token threw a cancellation exception, we should resume the outer loop to get a new enumerable if necessary
// If the main token is cancelled, we should just bubble up the exception
Expand Down Expand Up @@ -82,7 +92,17 @@ public static async IAsyncEnumerable<T> CreateAsync<T>(Func<T?, CancellationToke
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(restartInterval);

var enumerable = await enumerableFactory(lastValue, cts.Token).ConfigureAwait(false);
IAsyncEnumerable<T> 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
Expand All @@ -98,7 +118,7 @@ public static async IAsyncEnumerable<T> CreateAsync<T>(Func<T?, CancellationToke
break;
}
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
catch (OperationCanceledException ex) when (ex.CancellationToken == cts.Token && cts.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
// If the restart token threw a cancellation exception, we should resume the outer loop to get a new enumerable if necessary
// If the main token is cancelled, we should just bubble up the exception
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ await auto.RunCommandAsync(
counter,
TimeSpan.FromSeconds(120));
await auto.SourceAspireBundleEnvironmentAsync(counter);
if (strategy.LocalArchiveHiveLabel == "local")
{
await auto.ConfigureLocalHiveAsync(counter);
}
break;

case CliInstallMode.InstallScript:
Expand Down Expand Up @@ -431,6 +435,10 @@ await auto.RunCommandAsync(
counter,
TimeSpan.FromSeconds(120));
await auto.SourceAspireCliEnvironmentAsync(counter);
if (strategy.LocalArchiveHiveLabel == "local")
{
await auto.ConfigureLocalHiveAsync(counter);
}
break;

case CliInstallMode.InstallScript:
Expand Down
45 changes: 45 additions & 0 deletions tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliInstallStrategyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,29 @@ public void GetLocalArchiveInstallCommand_FormatsCorrectly()
Assert.Equal("/opt/aspire-scripts/get-aspire-cli-pr.sh --local-dir '/tmp/cli-archives'", command);
}

[Fact]
public void GetLocalArchiveInstallCommandFromCurrentRef_AllowsHiveAutoDetection()
{
using var environment = new EnvironmentVariableScope(("GITHUB_SHA", "0123456789abcdef0123456789abcdef01234567"));

var command = AspireCliShellCommandHelpers.GetLocalArchiveInstallCommandFromCurrentRef("/tmp/cli-archives");

Assert.Equal(
"curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/0123456789abcdef0123456789abcdef01234567/eng/scripts/get-aspire-cli-pr.sh | bash -s -- --local-dir '/tmp/cli-archives'",
command);
}

[Fact]
public void GetConfigureLocalHiveCommands_OverridesCliIdentity()
{
Assert.Equal(
[
"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 && 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()
{
Expand Down Expand Up @@ -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()
{
Expand Down
13 changes: 13 additions & 0 deletions tests/Aspire.Cli.EndToEnd.Tests/NewChannelNuGetConfigTests.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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<string>();

Assert.Contains(packageSources, source => source.Replace('\\', '/').EndsWith($"/hives/{expectedHiveLabel}/packages", StringComparison.Ordinal));
}
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand All @@ -259,10 +258,24 @@ await page.EvaluateAsync("""

await bottomButton.ClickAsync();
Assert.True(await page.EvaluateAsync<bool>("() => window.__hiddenOnClick"));
Assert.True(await page.EvaluateAsync<bool>("""
() => {
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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
38 changes: 38 additions & 0 deletions tests/Aspire.Hosting.Tests/Dcp/KubernetesServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Container>(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<OperationCanceledException>(() => 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.
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -431,6 +467,7 @@ public static async Task<TestDcpApiServer> 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
{
Expand Down Expand Up @@ -487,6 +524,7 @@ private sealed class ResponseState
{
public bool BlockWatchResponses;
public int RequestCount;
public int WatchRequestCount;
public TaskCompletionSource<bool> RequestCancellationObserved { get; } =
new(TaskCreationOptions.RunContinuationsAsynchronously);
public long ResponseDelayTicks;
Expand Down
Loading
Loading