// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Text.Json;
using Aspire.Cli.Backchannel;
using Aspire.Cli.Commands;
using Aspire.Cli.Interaction;
using Aspire.Cli.Layout;
using Aspire.Cli.Projects;
using Aspire.Cli.Resources;
using Aspire.Cli.Telemetry;
using Aspire.Cli.Tests.TestServices;
using Aspire.Cli.Tests.Utils;
using Aspire.Shared;
using Aspire.Hosting;
using Aspire.Hosting.Backchannel;
using Aspire.Hosting.Utils;
using Aspire.Tests;
using Microsoft.AspNetCore.InternalTesting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Time.Testing;
using StreamJsonRpc;
namespace Aspire.Cli.Tests.Commands;
public class StopCommandTests(ITestOutputHelper outputHelper)
{
[Fact]
public async Task StopCommand_Help_Works()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper);
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop --help");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
}
[Fact]
public async Task StopCommand_RejectsPositionalResourceArgument()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper);
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop myresource");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.NotEqual(CliExitCodes.Success, exitCode);
}
[Theory]
[InlineData(true, true, "AppHost.csproj")]
[InlineData(true, false, "AppHost.cs")]
[InlineData(false, true, "AppHost.csproj")]
[InlineData(false, false, "apphost.ts")]
public async Task StopCommand_WithPid_StopsOnlySelectedConnection(bool explicitPath, bool interactive, string fileName)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "App Host", fileName);
var selected = CreateConnection(appHostPath, int.MaxValue - 1, isInScope: false);
var sibling = CreateConnection(appHostPath, int.MaxValue - 2, isInScope: false);
selected.AppHostInfo = new AppHostInformation { AppHostPath = appHostPath, ProcessId = int.MaxValue - 1, CliProcessId = int.MaxValue - 3 };
sibling.AppHostInfo = new AppHostInformation { AppHostPath = appHostPath, ProcessId = int.MaxValue - 2, CliProcessId = int.MaxValue - 3 };
selected.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
sibling.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 2);
monitor.AddConnection(selected.SocketPath, selected);
monitor.AddConnection(sibling.SocketPath, sibling);
var processFactory = new TestProcessExecutionFactory();
var services = CreateInstanceStopServices(workspace, monitor, interactionService, processFactory, interactive);
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var arguments = new List<string> { "stop", "--pid", selected.AppHostInfo.ProcessId.ToString(CultureInfo.InvariantCulture), "--nologo" };
if (explicitPath)
{
arguments.AddRange(["--apphost", appHostPath]);
}
if (!interactive)
{
arguments.Add("--non-interactive");
}
var exitCode = await command.Parse(arguments.ToArray()).InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
Assert.Equal(1, selected.StopAppHostCallCount);
Assert.Equal(0, sibling.StopAppHostCallCount);
Assert.False(File.Exists(selected.SocketPath));
Assert.True(File.Exists(sibling.SocketPath));
Assert.Empty(processFactory.CreatedExecutions);
Assert.Equal(1, monitor.ScanCallCount);
Assert.False(monitor.LastPruneOrphanedSockets);
Assert.Empty(interactionService.DisplayedErrors);
}
[Theory]
[InlineData("missing", false)]
[InlineData("missing", true)]
[InlineData("pid", false)]
[InlineData("pid", true)]
[InlineData("path", true)]
[InlineData("directory", true)]
[InlineData("cli", false)]
[InlineData("metadata", false)]
[InlineData("ambiguous", false)]
public async Task StopCommand_WithPid_NoExactMatchStopsNothing(string mismatch, bool explicitPath)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var connection = CreateConnection(appHostPath, int.MaxValue - 1);
connection.AppHostInfo = new AppHostInformation { AppHostPath = appHostPath, ProcessId = int.MaxValue - 1, CliProcessId = int.MaxValue - 3 };
var sibling = CreateConnection(appHostPath, mismatch == "ambiguous" ? int.MaxValue - 1 : int.MaxValue - 2);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
sibling.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 2);
monitor.AddConnection(connection.SocketPath, connection);
monitor.AddConnection(sibling.SocketPath, sibling);
var pid = mismatch switch
{
"missing" or "cli" => int.MaxValue - 3,
"pid" => int.MaxValue,
_ => int.MaxValue - 1
};
if (mismatch == "missing")
{
monitor.ClearConnections();
}
if (mismatch == "metadata")
{
connection.AppHostInfo = null;
}
var requestedPath = mismatch switch
{
"path" => Path.Combine(workspace.WorkspaceRoot.FullName, "Other", "AppHost.csproj"),
"directory" => Path.GetDirectoryName(appHostPath)!,
_ => appHostPath
};
var processFactory = new TestProcessExecutionFactory();
var services = CreateInstanceStopServices(workspace, monitor, interactionService, processFactory, interactive: false);
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var arguments = new List<string> { "stop", "--pid", pid.ToString(CultureInfo.InvariantCulture), "--non-interactive", "--nologo" };
if (explicitPath)
{
arguments.AddRange(["--apphost", requestedPath]);
}
var exitCode = await command.Parse(arguments.ToArray()).InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToFindProject, exitCode);
Assert.Equal(0, connection.StopAppHostCallCount);
Assert.Equal(0, sibling.StopAppHostCallCount);
Assert.True(File.Exists(connection.SocketPath));
Assert.True(File.Exists(sibling.SocketPath));
Assert.Empty(processFactory.CreatedExecutions);
Assert.Equal(1, monitor.ScanCallCount);
Assert.False(monitor.LastPruneOrphanedSockets);
Assert.Empty(interactionService.DisplayedSuccess);
var expectedError = mismatch == "ambiguous"
? string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AmbiguousAppHostPid, pid)
: explicitPath
? string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostNotRunningAtPathWithPid, requestedPath, pid)
: string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostNotRunningWithPid, pid);
Assert.Equal(expectedError, Assert.Single(interactionService.DisplayedErrors));
}
[Theory]
[InlineData("stop --pid 0")]
[InlineData("stop --pid -1")]
[InlineData("stop --pid 1 --all")]
[InlineData("stop --pid 1 --force")]
[InlineData("stop --pid 1 --volumes")]
[InlineData("stop --pid 1 --force --volumes")]
[InlineData("stop --pid 1 --all --force")]
public async Task StopCommand_WithInvalidPidOptions_DoesNotScanOrStop(string commandLine)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = CreateConnection(Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost.cs"), 1);
monitor.AddConnection(connection.SocketPath, connection);
var processFactory = new TestProcessExecutionFactory();
var services = CreateInstanceStopServices(workspace, monitor, interactionService, processFactory, interactive: false);
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse(commandLine).InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.InvalidCommand, exitCode);
Assert.Equal(0, monitor.ScanCallCount);
Assert.Equal(0, connection.StopAppHostCallCount);
Assert.Empty(processFactory.CreatedExecutions);
Assert.Single(interactionService.DisplayedErrors);
}
[Theory]
[InlineData("stop --pid")]
[InlineData("stop --pid abc")]
[InlineData("stop --pid 1.5")]
[InlineData("stop --pid 2147483648")]
public async Task StopCommand_WithMalformedPid_FailsParsing(string commandLine)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper);
using var provider = services.BuildServiceProvider();
var result = provider.GetRequiredService<RootCommand>().Parse(commandLine);
Assert.NotEmpty(result.Errors);
Assert.NotEqual(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task StopCommand_WithPid_FailedRpcDoesNotFallBack(bool disconnect)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost.csproj");
var selected = CreateConnection(appHostPath, int.MaxValue - 1);
var sibling = CreateConnection(appHostPath, int.MaxValue - 2);
selected.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
sibling.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 2);
selected.StopAppHostHandler = _ => disconnect
? throw new IOException("The selected connection was lost.")
: Task.FromResult(false);
monitor.AddConnection(selected.SocketPath, selected);
monitor.AddConnection(sibling.SocketPath, sibling);
var processFactory = new TestProcessExecutionFactory();
var services = CreateInstanceStopServices(workspace, monitor, interactionService, processFactory, interactive: false);
using var provider = services.BuildServiceProvider();
var result = provider.GetRequiredService<RootCommand>().Parse($"stop --pid {int.MaxValue - 1}");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
Assert.Equal(1, selected.StopAppHostCallCount);
Assert.Equal(0, sibling.StopAppHostCallCount);
Assert.True(File.Exists(selected.SocketPath));
Assert.True(File.Exists(sibling.SocketPath));
Assert.Equal(1, monitor.ScanCallCount);
Assert.Empty(processFactory.CreatedExecutions);
Assert.Empty(interactionService.DisplayedSuccess);
Assert.Single(interactionService.DisplayedErrors);
}
[Fact]
public async Task StopCommand_WithPid_DoesNotRebindAfterSelection()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost.cs");
var selected = CreateConnection(appHostPath, int.MaxValue - 1);
var replacement = CreateConnection(appHostPath, int.MaxValue - 1);
selected.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
replacement.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 2);
monitor.AddConnection(selected.SocketPath, selected);
var identifier = string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostIdentifierWithProcessId, "AppHost.cs", int.MaxValue - 1);
interactionService.ShowStatusCallback = message =>
{
if (message == string.Format(CultureInfo.CurrentCulture, StopCommandStrings.StoppingAppHost, identifier))
{
monitor.ClearConnections();
monitor.AddConnection(replacement.SocketPath, replacement);
}
};
var processFactory = new TestProcessExecutionFactory();
var services = CreateInstanceStopServices(workspace, monitor, interactionService, processFactory, interactive: false);
using var provider = services.BuildServiceProvider();
var exitCode = await provider.GetRequiredService<RootCommand>()
.Parse($"stop --pid {int.MaxValue - 1}").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
Assert.Same(replacement, Assert.Single(monitor.Connections));
Assert.Equal(1, selected.StopAppHostCallCount);
Assert.Equal(0, replacement.StopAppHostCallCount);
Assert.False(File.Exists(selected.SocketPath));
Assert.True(File.Exists(replacement.SocketPath));
Assert.Equal(1, monitor.ScanCallCount);
}
[Theory]
[InlineData("stop")]
[InlineData("stop --all")]
public async Task StopCommand_WithoutPid_StillStopsSameProjectInstances(string commandLine)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost.cs");
var first = CreateConnection(appHostPath, int.MaxValue - 1);
var second = CreateConnection(appHostPath, int.MaxValue - 2);
first.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
second.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 2);
monitor.AddConnection(first.SocketPath, first);
monitor.AddConnection(second.SocketPath, second);
var processFactory = new TestProcessExecutionFactory();
var services = CreateInstanceStopServices(workspace, monitor, interactionService, processFactory, interactive: true);
using var provider = services.BuildServiceProvider();
var exitCode = await provider.GetRequiredService<RootCommand>().Parse(commandLine).InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
Assert.False(File.Exists(first.SocketPath));
Assert.False(File.Exists(second.SocketPath));
Assert.Equal(commandLine == "stop" ? 3 : 2, interactionService.DisplayedSuccess.Count);
Assert.True(monitor.LastPruneOrphanedSockets);
}
[Fact]
public async Task StopCommand_WithInvalidExplicitAppHost_ReturnsFailedToFindProject()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.ProjectLocatorFactory = _ => new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
throw new ProjectLocatorException("Project file does not exist.", ProjectLocatorFailureReason.ProjectFileDoesntExist)
};
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop --apphost missing-directory");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToFindProject, exitCode);
}
[Fact]
public async Task StopCommand_WithExplicitAppHost_UsesProjectLocatorResolution()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var projectLocatorInvoked = false;
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("some-directory");
var resolvedProjectFile = new FileInfo(Path.Combine(workspace.WorkspaceRoot.FullName, "Resolved.AppHost", "Resolved.AppHost.csproj"));
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.ProjectLocatorFactory = _ => new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (projectFile, _, _, _) =>
{
projectLocatorInvoked = true;
return Task.FromResult(new AppHostProjectSearchResult(resolvedProjectFile, [resolvedProjectFile]));
}
};
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse($"stop --apphost \"{appHostDirectory.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.True(projectLocatorInvoked);
Assert.Equal(CliExitCodes.Success, exitCode);
var displayedMessage = Assert.Single(interactionService.DisplayedMessages);
Assert.Equal(
string.Format(SharedCommandStrings.AppHostNotRunningAtPath, Path.Combine("Resolved.AppHost", "Resolved.AppHost.csproj")),
displayedMessage.Message);
}
[Fact]
public async Task StopCommand_AllIncludesEachAppHostPathInMessages()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var statusMessages = new ConcurrentQueue<string>();
interactionService.ShowStatusCallback = statusMessages.Enqueue;
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath1 = Path.Combine(workspace.WorkspaceRoot.FullName, "App1", "AppHost.cs");
var appHostPath2 = Path.Combine(workspace.WorkspaceRoot.FullName, "App2", "AppHost.cs");
monitor.AddConnection("socket.hash1", CreateConnection(appHostPath1, int.MaxValue - 1));
monitor.AddConnection("socket.hash2", CreateConnection(appHostPath2, int.MaxValue - 2));
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop --all");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
var expectedPath1 = Path.Combine("App1", "AppHost.cs");
var expectedPath2 = Path.Combine("App2", "AppHost.cs");
var displayedText = GetDisplayedText(interactionService, statusMessages);
Assert.Contains(displayedText, message => message.Contains(expectedPath1, StringComparison.Ordinal));
Assert.Contains(displayedText, message => message.Contains(expectedPath2, StringComparison.Ordinal));
}
[Fact]
public async Task StopCommand_AllIncludesProcessIdWhenAppHostPathsCollide()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var statusMessages = new ConcurrentQueue<string>();
interactionService.ShowStatusCallback = statusMessages.Enqueue;
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "App1", "App1.AppHost", "App1.AppHost.csproj");
var processId1 = int.MaxValue - 3;
var processId2 = int.MaxValue - 4;
monitor.AddConnection("socket.hash1", CreateConnection(appHostPath, processId1));
monitor.AddConnection("socket.hash2", CreateConnection(appHostPath, processId2));
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop --all");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
var expectedPath = "App1.AppHost.csproj";
var expectedIdentifier1 = string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostIdentifierWithProcessId, expectedPath, processId1);
var expectedIdentifier2 = string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostIdentifierWithProcessId, expectedPath, processId2);
var displayedText = GetDisplayedText(interactionService, statusMessages);
Assert.Contains(displayedText, message => message.Contains(expectedIdentifier1, StringComparison.Ordinal));
Assert.Contains(displayedText, message => message.Contains(expectedIdentifier2, StringComparison.Ordinal));
}
[Fact]
public async Task StopCommand_SingleAppHostIncludesIdentifierInStatusAndSuccessMessages()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var statusMessages = new ConcurrentQueue<string>();
interactionService.ShowStatusCallback = statusMessages.Enqueue;
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "App1", "App1.AppHost", "App1.AppHost.csproj");
var connection = CreateConnection(appHostPath, int.MaxValue - 5);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 5);
monitor.AddConnection(connection.SocketPath, connection);
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
var expectedPath = Path.Combine("App1", "App1.AppHost", "App1.AppHost.csproj");
Assert.Contains(statusMessages, message => message == string.Format(CultureInfo.CurrentCulture, StopCommandStrings.StoppingAppHost, expectedPath));
Assert.Contains(interactionService.DisplayedSuccess, message => message == string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostStoppedSuccessfully, expectedPath));
}
[Fact]
public async Task StopCommand_WithoutAppHost_DoesNotStopNestedLinkedWorktreeInstance()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
Directory.CreateDirectory(Path.Combine(workspace.WorkspaceRoot.FullName, ".git"));
var worktreeRoot = Directory.CreateDirectory(Path.Combine(workspace.WorkspaceRoot.FullName, ".worktrees", "feature")).FullName;
TestGitWorktree.WriteLinkedWorktreeMetadata(
worktreeRoot,
Path.Combine(workspace.WorkspaceRoot.FullName, ".git"));
var interactionService = new TestInteractionService();
var statusMessages = new ConcurrentQueue<string>();
interactionService.ShowStatusCallback = statusMessages.Enqueue;
var primaryAppHost = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var nestedAppHost = Path.Combine(worktreeRoot, "AppHost.csproj");
Assert.True(AuxiliaryBackchannelMonitor.IsAppHostInScopeOfDirectory(primaryAppHost, workspace.WorkspaceRoot.FullName));
Assert.False(AuxiliaryBackchannelMonitor.IsAppHostInScopeOfDirectory(nestedAppHost, workspace.WorkspaceRoot.FullName));
var monitor = new TestAuxiliaryBackchannelMonitor();
var primaryConnection = CreateConnection(
primaryAppHost,
int.MaxValue - 7,
isInScope: AuxiliaryBackchannelMonitor.IsAppHostInScopeOfDirectory(primaryAppHost, workspace.WorkspaceRoot.FullName));
primaryConnection.SocketPath = CreateMatchingSocketFile(primaryAppHost, workspace, 7);
var nestedConnection = CreateConnection(
nestedAppHost,
int.MaxValue - 8,
isInScope: AuxiliaryBackchannelMonitor.IsAppHostInScopeOfDirectory(nestedAppHost, workspace.WorkspaceRoot.FullName));
nestedConnection.SocketPath = CreateMatchingSocketFile(nestedAppHost, workspace, 8);
monitor.AddConnection(primaryConnection.SocketPath, primaryConnection);
monitor.AddConnection(nestedConnection.SocketPath, nestedConnection);
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
options.CliHostEnvironmentFactory = _ => TestHelpers.CreateNonInteractiveHostEnvironment();
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
var expectedPath = Path.Combine("AppHost", "AppHost.csproj");
Assert.Contains(statusMessages, message => message == string.Format(CultureInfo.CurrentCulture, StopCommandStrings.StoppingAppHost, expectedPath));
Assert.False(File.Exists(primaryConnection.SocketPath));
Assert.True(File.Exists(nestedConnection.SocketPath));
}
[Fact]
public async Task StopCommand_WithExplicitAppHostFileDoesNotUseProjectLocatorBeforeSocketLookup()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
throw new InvalidOperationException("Explicit file stop should not require project validation.")
};
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.ProjectLocatorFactory = _ => projectLocator;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse($"stop --apphost \"{appHostFile.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
var displayedMessage = Assert.Single(interactionService.DisplayedMessages);
Assert.Equal(
string.Format(SharedCommandStrings.AppHostNotRunningAtPath, Path.Combine("AppHost", "AppHost.csproj")),
displayedMessage.Message);
}
[Fact]
public async Task StopCommand_SingleAppHostInDifferentWorktreeWithoutOverrideDoesNotPromptOrStop()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var commonGitDirectory = Path.Combine(workspace.WorkspaceRoot.FullName, ".git");
Directory.CreateDirectory(commonGitDirectory);
var worktreeRoot = Directory.CreateDirectory(Path.Combine(workspace.WorkspaceRoot.FullName, ".worktrees", "feature")).FullName;
TestGitWorktree.WriteLinkedWorktreeMetadata(worktreeRoot, commonGitDirectory);
var interactionService = new TestInteractionService();
interactionService.PromptForSelectionCallback = (_, _, _, _) =>
throw new InvalidOperationException("AppHosts in another worktree must not be offered by aspire stop without --apphost or --all.");
var statusMessages = new ConcurrentQueue<string>();
interactionService.ShowStatusCallback = statusMessages.Enqueue;
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(worktreeRoot, "App1", "App1.AppHost", "App1.AppHost.csproj");
var connection = CreateConnection(appHostPath, int.MaxValue - 6, isInScope: false);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 6);
monitor.AddConnection(connection.SocketPath, connection);
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
options.CliHostEnvironmentFactory = _ => TestHelpers.CreateInteractiveHostEnvironment();
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToFindProject, exitCode);
Assert.Equal([SharedCommandStrings.ScanningForRunningAppHosts], statusMessages);
Assert.Empty(interactionService.DisplayedSuccess);
// The AppHost is running, just not in this worktree, so the message must not say
// "start one first" and must name the flags that can reach across worktrees.
Assert.Equal(SharedCommandStrings.AppHostNotRunningInCurrentWorktree, Assert.Single(interactionService.DisplayedErrors));
Assert.True(File.Exists(connection.SocketPath));
}
[Fact]
public async Task StopCommand_SingleAppHostOutsideWorkingDirectoryInSameWorktreePromptsAndStops()
{
// Regression coverage for `aspire stop` run from a sibling directory (repo/tests) while the
// AppHost lives elsewhere in the same checkout. Scope hides it from the direct match, but
// it is still the user's own worktree, so it must be offered.
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var statusMessages = new ConcurrentQueue<string>();
interactionService.ShowStatusCallback = statusMessages.Enqueue;
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "App1", "App1.AppHost", "App1.AppHost.csproj");
var connection = CreateConnection(appHostPath, int.MaxValue - 6, isInScope: false);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 6);
monitor.AddConnection(connection.SocketPath, connection);
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
options.CliHostEnvironmentFactory = _ => TestHelpers.CreateInteractiveHostEnvironment();
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
Assert.Collection(
interactionService.DisplayedMessages.Select(message => message.Message),
message => Assert.Equal(SharedCommandStrings.NoInScopeAppHostsShowingAll, message),
message => Assert.Equal(string.Format(CultureInfo.CurrentCulture, StopCommandStrings.FoundRunningAppHost, appHostPath), message),
message => Assert.Equal(string.Format(CultureInfo.CurrentCulture, StopCommandStrings.SendingStopSignal, appHostPath), message),
message => Assert.Equal(string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownMayContinue, "--wait"), message));
Assert.Contains(statusMessages, message => message == string.Format(CultureInfo.CurrentCulture, StopCommandStrings.StoppingAppHost, appHostPath));
Assert.False(File.Exists(connection.SocketPath));
}
[Fact]
public async Task StopCommand_AllEmitsProfilingActivities()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var stoppedActivities = new ConcurrentQueue<Activity>();
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath1 = Path.Combine(workspace.WorkspaceRoot.FullName, "App1", "App1.AppHost.csproj");
var appHostPath2 = Path.Combine(workspace.WorkspaceRoot.FullName, "App2", "App2.AppHost.csproj");
var processId1 = int.MaxValue - 7;
var processId2 = int.MaxValue - 8;
monitor.AddConnection("socket.hash1", CreateConnection(appHostPath1, processId1));
monitor.AddConnection("socket.hash2", CreateConnection(appHostPath2, processId2));
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
options.ConfigurationCallback += config =>
{
config[KnownConfigNames.ProfilingEnabled] = "true";
};
});
using var provider = services.BuildServiceProvider();
var profilingTelemetry = provider.GetRequiredService<ProfilingTelemetry>();
using var listener = ActivityListenerHelper.Create(profilingTelemetry.ActivitySource, onActivityStopped: stoppedActivities.Enqueue);
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop --all");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
var stopCommandActivity = Assert.Single(stoppedActivities, activity => activity.OperationName == ProfilingTelemetry.Activities.StopCommand);
Assert.Equal(true, stopCommandActivity.GetTagItem(ProfilingTelemetry.Tags.AppHostStopAll));
Assert.Equal(2, stopCommandActivity.GetTagItem(ProfilingTelemetry.Tags.AppHostStopCount));
Assert.Equal(CliExitCodes.Success, stopCommandActivity.GetTagItem(TelemetryConstants.Tags.ProcessExitCode));
var stopAppHostActivities = stoppedActivities.Where(activity => activity.OperationName == ProfilingTelemetry.Activities.StopAppHost).ToArray();
Assert.Equal(2, stopAppHostActivities.Length);
var expectedProcessIds = new[] { processId1, processId2 }.Order().ToArray();
Assert.Equal(
expectedProcessIds,
stopAppHostActivities
.Select(activity => Assert.IsType<int>(activity.GetTagItem(TelemetryConstants.Tags.ProcessPid)))
.Order()
.ToArray());
Assert.All(stopAppHostActivities, activity => Assert.Equal(CliExitCodes.Success, activity.GetTagItem(TelemetryConstants.Tags.ProcessExitCode)));
}
[Theory]
[InlineData("stop")]
[InlineData("stop --all")]
public async Task StopCommand_NoRunningAppHosts_ReturnsSuccess(string commandLine)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
options.CliHostEnvironmentFactory = _ => TestHelpers.CreateInteractiveHostEnvironment();
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse(commandLine);
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
var displayedMessage = Assert.Single(interactionService.DisplayedMessages);
Assert.Equal(SharedCommandStrings.AppHostNotRunning, displayedMessage.Message);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task StopCommand_ForceInvokesDcpCleanupForResolvedAppHost(bool deleteVolumes)
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var expectedWorkloadId = AppHostWorkloadId.Create(appHostFile);
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
throw new InvalidOperationException("Explicit file force stop should not require project validation.")
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var volumesOption = deleteVolumes ? " --volumes" : string.Empty;
var result = command.Parse($"stop --force{volumesOption} --apphost \"{appHostFile.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
AssertDcpCleanupInvocation(processFactory, expectedWorkloadId, deleteVolumes);
Assert.Contains(interactionService.DisplayedMessages, message => message.Message == string.Format(SharedCommandStrings.AppHostNotRunningAtPath, Path.Combine("AppHost", "AppHost.csproj")));
Assert.Contains(interactionService.DisplayedSuccess, message => message == string.Format(CultureInfo.CurrentCulture, StopCommandStrings.PersistentResourcesCleaned, appHostFile.Name));
}
[Fact]
public async Task StopCommand_ForceInvokesDcpCleanupFromDiscoveredLayoutWhenBundleUnavailable()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var expectedWorkloadId = AppHostWorkloadId.Create(appHostFile);
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
Task.FromResult(new AppHostProjectSearchResult(appHostFile, [appHostFile]))
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
}, useBundleLayout: false);
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse($"stop --force --apphost \"{appHostFile.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
AssertDcpCleanupInvocation(processFactory, expectedWorkloadId);
}
[Fact]
public async Task StopCommand_ForceWithoutAppHostUsesRunningAppHostPathBeforeProjectDiscovery()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var runningAppHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("RunningAppHost");
var runningAppHostFile = new FileInfo(Path.Combine(runningAppHostDirectory.FullName, "Running.AppHost.csproj"));
await File.WriteAllTextAsync(runningAppHostFile.FullName, "<Project />");
var discoveredAppHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("DiscoveredAppHost");
var discoveredAppHostFile = new FileInfo(Path.Combine(discoveredAppHostDirectory.FullName, "Discovered.AppHost.csproj"));
await File.WriteAllTextAsync(discoveredAppHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var expectedWorkloadId = AppHostWorkloadId.Create(runningAppHostFile);
var projectLocatorInvoked = false;
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = CreateConnection(runningAppHostFile.FullName, int.MaxValue - 11);
connection.SocketPath = CreateMatchingSocketFile(runningAppHostFile.FullName, workspace, 11);
monitor.AddConnection(connection.SocketPath, connection);
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
{
projectLocatorInvoked = true;
return Task.FromResult(new AppHostProjectSearchResult(discoveredAppHostFile, [discoveredAppHostFile]));
}
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
options.CliHostEnvironmentFactory = _ => TestHelpers.CreateNonInteractiveHostEnvironment();
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop --force");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
Assert.False(projectLocatorInvoked);
AssertDcpCleanupInvocation(processFactory, expectedWorkloadId);
var expectedStoppedMessage = string.Format(
CultureInfo.CurrentCulture,
StopCommandStrings.AppHostStoppedSuccessfully,
Path.Combine("RunningAppHost", "Running.AppHost.csproj"));
Assert.Equal(1, interactionService.DisplayedSuccess.Count(message => message == expectedStoppedMessage));
}
[Fact]
public async Task StopCommand_ForceWithExplicitAppHostFileCleansUpWithoutProjectValidation()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var expectedWorkloadId = AppHostWorkloadId.Create(appHostFile);
var processFactory = new TestProcessExecutionFactory();
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
throw new InvalidOperationException("Explicit file force stop should not require project validation.")
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse($"stop --force --apphost \"{appHostFile.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
AssertDcpCleanupInvocation(processFactory, expectedWorkloadId);
}
[Fact]
public async Task StopCommand_ForceNonInteractiveWithoutRunningAppHostFallsBackToProjectDiscovery()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var expectedWorkloadId = AppHostWorkloadId.Create(appHostFile);
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
Task.FromResult(new AppHostProjectSearchResult(appHostFile, [appHostFile]))
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
options.AuxiliaryBackchannelMonitorFactory = _ => new TestAuxiliaryBackchannelMonitor();
options.CliHostEnvironmentFactory = _ => TestHelpers.CreateNonInteractiveHostEnvironment();
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop --force");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
AssertDcpCleanupInvocation(processFactory, expectedWorkloadId);
Assert.Empty(interactionService.DisplayedErrors);
Assert.Contains(interactionService.DisplayedMessages, message => message.Message == SharedCommandStrings.AppHostNotRunning);
}
[Fact]
public async Task StopCommand_ForceNonInteractiveWithOnlyOutOfScopeAppHostsFallsBackToProjectDiscovery()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var expectedWorkloadId = AppHostWorkloadId.Create(appHostFile);
var monitor = new TestAuxiliaryBackchannelMonitor();
var outOfScopeAppHostFile = Path.Combine(workspace.WorkspaceRoot.FullName, "OtherWorkspace", "Other.AppHost.csproj");
monitor.AddConnection("socket.hash1", CreateConnection(outOfScopeAppHostFile, int.MaxValue - 12, isInScope: false));
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
Task.FromResult(new AppHostProjectSearchResult(appHostFile, [appHostFile]))
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
options.CliHostEnvironmentFactory = _ => TestHelpers.CreateNonInteractiveHostEnvironment();
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop --force");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
AssertDcpCleanupInvocation(processFactory, expectedWorkloadId);
Assert.Empty(interactionService.DisplayedErrors);
Assert.Contains(interactionService.DisplayedMessages, message => message.Message == SharedCommandStrings.AppHostNotRunning);
}
[Fact]
public async Task StopCommand_ForceReturnsFailureWhenDcpCleanupFails()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory
{
DefaultExitCode = 42,
AttemptCallback = (_, _) => (42, "cleanup failed")
};
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
Task.FromResult(new AppHostProjectSearchResult(appHostFile, [appHostFile]))
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse($"stop --force --apphost \"{appHostFile.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
Assert.Contains(interactionService.DisplayedErrors, error => error.Contains("cleanup failed", StringComparison.Ordinal));
}
[Theory]
[InlineData(false, "13.4.0", "persistent resource cleanup")]
[InlineData(true, "13.5.0", "persistent volume cleanup")]
public async Task StopCommand_ForceWarnsAndCleansUpForUnsupportedNonBundleAppHost(
bool deleteVolumes,
string aspireHostingVersion,
string expectedWarning)
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var expectedWorkloadId = AppHostWorkloadId.Create(appHostFile);
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
Task.FromResult(new AppHostProjectSearchResult(appHostFile, [appHostFile]))
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
options.DotNetCliRunnerFactory = _ => new TestDotNetCliRunner
{
GetProjectItemsAndPropertiesAsyncCallbackWithTargets = (_, _, _, _, _, _) =>
(0, CreateAppHostInfoJson(aspireHostingVersion, isUsingCliBundle: false))
};
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var volumesOption = deleteVolumes ? " --volumes" : string.Empty;
var result = command.Parse($"stop --force{volumesOption} --apphost \"{appHostFile.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
AssertDcpCleanupInvocation(processFactory, expectedWorkloadId, deleteVolumes);
Assert.Contains(interactionService.DisplayedMessages, message =>
message.Emoji.Equals(KnownEmojis.PoliceCarLight) &&
message.Message.Contains(expectedWarning, StringComparison.Ordinal));
}
[Fact]
public async Task StopCommand_ForceWarnsAndCleansUpWhenAppHostVersionCannotBeDetermined()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var expectedWorkloadId = AppHostWorkloadId.Create(appHostFile);
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
Task.FromResult(new AppHostProjectSearchResult(appHostFile, [appHostFile]))
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
options.DotNetCliRunnerFactory = _ => new TestDotNetCliRunner
{
GetProjectItemsAndPropertiesAsyncCallbackWithTargets = (_, _, _, _, _, _) =>
(0, CreateAppHostInfoJson(aspireHostingVersion: null, isUsingCliBundle: false))
};
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse($"stop --force --apphost \"{appHostFile.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
AssertDcpCleanupInvocation(processFactory, expectedWorkloadId);
Assert.Contains(interactionService.DisplayedMessages, message =>
message.Emoji.Equals(KnownEmojis.PoliceCarLight) &&
message.Message.Contains("an unknown version", StringComparison.Ordinal));
}
[Fact]
public async Task StopCommand_ForceWarnsAndCleansUpWhenAppHostInfoCannotBeInspected()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var expectedWorkloadId = AppHostWorkloadId.Create(appHostFile);
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
Task.FromResult(new AppHostProjectSearchResult(appHostFile, [appHostFile]))
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
options.DotNetCliRunnerFactory = _ => new TestDotNetCliRunner
{
GetProjectItemsAndPropertiesAsyncCallbackWithTargets = (_, _, _, _, _, _) => (1, null)
};
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse($"stop --force --apphost \"{appHostFile.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
AssertDcpCleanupInvocation(processFactory, expectedWorkloadId);
Assert.Contains(interactionService.DisplayedMessages, message =>
message.Emoji.Equals(KnownEmojis.PoliceCarLight) &&
message.Message.Contains("Could not inspect the AppHost project", StringComparison.Ordinal));
}
[Fact]
public async Task StopCommand_ForceSkipsCompatibilityWarningForGuestAppHost()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "apphost.ts"));
await File.WriteAllTextAsync(appHostFile.FullName, "");
var processFactory = new TestProcessExecutionFactory();
var expectedWorkloadId = AppHostWorkloadId.Create(appHostFile);
var appHostInfoInspected = false;
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
Task.FromResult(new AppHostProjectSearchResult(appHostFile, [appHostFile]))
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
options.DotNetCliRunnerFactory = _ => new TestDotNetCliRunner
{
GetProjectItemsAndPropertiesAsyncCallbackWithTargets = (_, _, _, _, _, _) =>
{
appHostInfoInspected = true;
return (1, null);
}
};
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse($"stop --force --apphost \"{appHostFile.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
AssertDcpCleanupInvocation(processFactory, expectedWorkloadId);
Assert.False(appHostInfoInspected);
var displayedMessage = Assert.Single(interactionService.DisplayedMessages);
Assert.Equal(
string.Format(SharedCommandStrings.AppHostNotRunningAtPath, Path.Combine("AppHost", "apphost.ts")),
displayedMessage.Message);
}
[Fact]
public async Task StopCommand_ForceAllowsUnsupportedVersionWhenAppHostUsesCliBundle()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var expectedWorkloadId = AppHostWorkloadId.Create(appHostFile);
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
Task.FromResult(new AppHostProjectSearchResult(appHostFile, [appHostFile]))
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
options.DotNetCliRunnerFactory = _ => new TestDotNetCliRunner
{
GetProjectItemsAndPropertiesAsyncCallbackWithTargets = (_, _, _, _, _, _) =>
(0, CreateAppHostInfoJson(aspireHostingVersion: "13.4.0", isUsingCliBundle: true))
};
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse($"stop --force --apphost \"{appHostFile.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
AssertDcpCleanupInvocation(processFactory, expectedWorkloadId);
}
[Fact]
public async Task StopCommand_ForceReturnsCleanupFailureWhenDcpCannotStart()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
processFactory.CreateExecutionCallback = (args, env, _, options) =>
new TestProcessExecution(
"dcp",
args,
env,
options,
(_, _, _) => Task.FromResult((0, (string?)null)),
() => processFactory.AttemptCount)
{
StartReturnValue = false
};
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
Task.FromResult(new AppHostProjectSearchResult(appHostFile, [appHostFile]))
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse($"stop --force --apphost \"{appHostFile.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
Assert.Single(processFactory.CreatedExecutions);
var error = Assert.Single(interactionService.DisplayedErrors);
Assert.Contains("Failed to clean up persistent resources", error, StringComparison.Ordinal);
Assert.Contains("Failed to start process:", error, StringComparison.Ordinal);
}
[Fact]
public async Task StopCommand_ForceReturnsCleanupFailureWhenBundleLayoutCannotBeAcquired()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
Task.FromResult(new AppHostProjectSearchResult(appHostFile, [appHostFile]))
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
options.BundleServiceFactory = _ => new TestBundleService(isBundle: true)
{
EnsureExtractedException = new InvalidOperationException("Bundle extraction failed.")
};
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse($"stop --force --apphost \"{appHostFile.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
Assert.Empty(processFactory.CreatedExecutions);
var error = Assert.Single(interactionService.DisplayedErrors);
Assert.Contains("Failed to clean up persistent resources", error, StringComparison.Ordinal);
Assert.Contains("Bundle extraction failed.", error, StringComparison.Ordinal);
}
[Fact]
public async Task StopCommand_ForceReturnsCleanupFailureWhenDcpCleanupThrowsUnexpectedException()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
Task.FromResult(new AppHostProjectSearchResult(appHostFile, [appHostFile]))
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
options.BundleServiceFactory = _ => new TestBundleService(isBundle: true)
{
EnsureExtractedException = new PlatformNotSupportedException("Platform denied cleanup.")
};
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse($"stop --force --apphost \"{appHostFile.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
Assert.Empty(processFactory.CreatedExecutions);
var error = Assert.Single(interactionService.DisplayedErrors);
Assert.Contains("Failed to clean up persistent resources", error, StringComparison.Ordinal);
Assert.Contains("Platform denied cleanup.", error, StringComparison.Ordinal);
}
[Fact]
public async Task StopCommand_ForceReturnsFailureWhenDcpIsUnavailable()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
Task.FromResult(new AppHostProjectSearchResult(appHostFile, [appHostFile]))
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
}, createDcpExecutable: false);
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse($"stop --force --apphost \"{appHostFile.FullName}\"");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
Assert.Empty(processFactory.CreatedExecutions);
Assert.Contains(StopCommandStrings.DcpCleanupUnavailable, interactionService.DisplayedErrors);
}
[Fact]
public async Task StopCommand_ForceReportsUnknownAppHostPathAfterNormalStop()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = new TestAppHostAuxiliaryBackchannel
{
AppHostInfo = null,
IsInScope = true
};
monitor.AddConnection(connection.SocketPath, connection);
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
Task.FromResult(new AppHostProjectSearchResult(null, []))
};
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
options.ProjectLocatorFactory = _ => projectLocator;
options.CliHostEnvironmentFactory = _ => TestHelpers.CreateNonInteractiveHostEnvironment();
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop --force");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToFindProject, exitCode);
Assert.Contains(StopCommandStrings.CouldNotDetermineAppHostPath, interactionService.DisplayedErrors);
}
[Fact]
public async Task StopCommand_ForceUsesStoppedConnectionPathForCleanupWhenProjectDiscoveryFails()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var expectedWorkloadId = AppHostWorkloadId.Create(appHostFile);
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = CreateConnection(appHostFile.FullName, int.MaxValue - 10);
connection.SocketPath = CreateMatchingSocketFile(appHostFile.FullName, workspace, 10);
monitor.AddConnection(connection.SocketPath, connection);
var projectLocator = new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
throw new ProjectLocatorException("Multiple project files found.", ProjectLocatorFailureReason.MultipleProjectFilesFound)
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.ProjectLocatorFactory = _ => projectLocator;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop --force");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
AssertDcpCleanupInvocation(processFactory, expectedWorkloadId);
}
[Fact]
public async Task StopCommand_ForceAndAllAreMutuallyExclusive()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop --force --all");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.InvalidCommand, exitCode);
Assert.Equal(
string.Format(CultureInfo.InvariantCulture, StopCommandStrings.AllAndProjectMutuallyExclusive, "--all", "--force"),
Assert.Single(interactionService.DisplayedErrors));
}
[Fact]
public async Task StopCommand_VolumesRequiresForce()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop --volumes");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.InvalidCommand, exitCode);
Assert.Equal(
string.Format(CultureInfo.InvariantCulture, StopCommandStrings.VolumesRequiresForce, "--volumes", "--force"),
Assert.Single(interactionService.DisplayedErrors));
}
[Fact]
public async Task StopCommand_DeletesSocketFile_AfterSuccessfulStop()
{
// Regression test for https://github.com/microsoft/aspire/issues/17587: 'aspire stop' is the command
// that leaks the socket, so it must delete the socket file once the AppHost has been confirmed stopped.
// Otherwise a later command rediscovers the stale socket and tries to connect to a dead process.
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
// The AppHost is reported with a process id that does not exist, so ProcessShutdownService observes
// termination immediately and the stop reaches the socket-cleanup branch.
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "App1", "App1.AppHost.csproj");
var socketPath = CreateMatchingSocketFile(appHostPath, workspace, 9);
Assert.True(File.Exists(socketPath));
var connection = CreateConnection(appHostPath, int.MaxValue - 9);
connection.SocketPath = socketPath;
var monitor = new TestAuxiliaryBackchannelMonitor();
monitor.AddConnection(socketPath, connection);
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("stop");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
Assert.False(File.Exists(socketPath));
}
[Fact]
public async Task StopCommand_WithoutWait_ReportsOnceThatResourceTeardownMayContinue()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection1 = CreateConnection(Path.Combine(workspace.WorkspaceRoot.FullName, "App1", "AppHost.cs"), int.MaxValue - 1);
var connection2 = CreateConnection(Path.Combine(workspace.WorkspaceRoot.FullName, "App2", "AppHost.cs"), int.MaxValue - 2);
monitor.AddConnection("socket.hash1", connection1);
monitor.AddConnection("socket.hash2", connection2);
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse("stop --all").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
Assert.Equal(0, connection1.StopAppHostAndWaitForResourceCleanupCallCount);
Assert.Equal(0, connection2.StopAppHostAndWaitForResourceCleanupCallCount);
Assert.Equal(
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownMayContinue, "--wait"),
Assert.Single(interactionService.DisplayedMessages, message => message.Emoji.Name == KnownEmojis.Information.Name).Message);
}
[Fact]
public async Task StopCommand_All_ReportsThatResourceTeardownMayContinueForCollectedOrphanedAppHost()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var connection = CreateConnection(appHostPath, int.MaxValue - 1);
// The launching CLI process does not exist, so the AppHost is orphaned.
connection.AppHostInfo = new AppHostInformation { AppHostPath = appHostPath, ProcessId = int.MaxValue - 1, CliProcessId = int.MaxValue - 3 };
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
monitor.AddConnection(connection.SocketPath, connection);
// Like the real monitor, a scan drops connections whose socket file has been deleted.
monitor.ScanAsyncCallback = _ =>
{
if (!File.Exists(connection.SocketPath))
{
monitor.RemoveConnection(connection.SocketPath);
}
return Task.CompletedTask;
};
var services = CreateInstanceStopServices(workspace, monitor, interactionService, new TestProcessExecutionFactory(), interactive: false);
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse("stop --all --non-interactive").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
Assert.Equal(0, connection.StopAppHostAndWaitForResourceCleanupCallCount);
Assert.False(File.Exists(connection.SocketPath));
Assert.Equal(
[
SharedCommandStrings.AppHostNotRunning,
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownMayContinue, "--wait")
],
interactionService.DisplayedMessages.Where(message => message.Emoji.Name == KnownEmojis.Information.Name).Select(message => message.Message));
}
[Fact]
public async Task StopCommand_AllWait_TearsDownResourcesOfOrphanedAppHost()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var connection = CreateConnection(appHostPath, int.MaxValue - 1);
// The launching CLI process does not exist, so the AppHost is orphaned.
connection.AppHostInfo = new AppHostInformation { AppHostPath = appHostPath, ProcessId = int.MaxValue - 1, CliProcessId = int.MaxValue - 3 };
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
monitor.AddConnection(connection.SocketPath, connection);
// Like the real monitor, a scan drops connections whose socket file has been deleted.
monitor.ScanAsyncCallback = _ =>
{
if (!File.Exists(connection.SocketPath))
{
monitor.RemoveConnection(connection.SocketPath);
}
return Task.CompletedTask;
};
Assert.True(OrphanedAppHostCollector.IsOrphaned(connection));
var services = CreateInstanceStopServices(workspace, monitor, interactionService, new TestProcessExecutionFactory(), interactive: false);
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse("stop --all --wait --non-interactive").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
Assert.Equal(1, connection.StopAppHostAndWaitForResourceCleanupCallCount);
Assert.Equal(0, connection.StopAppHostCallCount);
Assert.False(File.Exists(connection.SocketPath));
Assert.Equal(
[
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostStoppedSuccessfully, "AppHost.csproj"),
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourcesTornDown, "AppHost.csproj")
],
interactionService.DisplayedSuccess);
Assert.Empty(interactionService.DisplayedErrors);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task StopCommand_Wait_ReportsSuccessAfterAppHostConfirmsResourceTeardown(bool selectByPid)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var connection = CreateConnection(appHostPath, int.MaxValue - 1);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
monitor.AddConnection(connection.SocketPath, connection);
var services = CreateInstanceStopServices(workspace, monitor, interactionService, new TestProcessExecutionFactory(), interactive: false);
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var commandLine = selectByPid
? $"stop --wait --pid {connection.AppHostInfo!.ProcessId.ToString(CultureInfo.InvariantCulture)} --non-interactive"
: "stop --wait --non-interactive";
var exitCode = await command.Parse(commandLine).InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
Assert.Equal(1, connection.StopAppHostAndWaitForResourceCleanupCallCount);
// The teardown request already stops the AppHost, which may have closed the connection by now.
Assert.Equal(0, connection.StopAppHostCallCount);
var appHostIdentifier = selectByPid
? string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostIdentifierWithProcessId, Path.Combine("AppHost", "AppHost.csproj"), connection.AppHostInfo!.ProcessId)
: Path.Combine("AppHost", "AppHost.csproj");
Assert.Equal(
[
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostStoppedSuccessfully, appHostIdentifier),
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourcesTornDown, appHostIdentifier)
],
interactionService.DisplayedSuccess);
Assert.Empty(interactionService.DisplayedErrors);
Assert.Equal(
[
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.FoundRunningAppHost, appHostIdentifier),
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.SendingStopSignal, appHostIdentifier)
],
interactionService.DisplayedMessages.Select(message => message.Message));
}
[Fact]
public async Task StopCommand_Wait_LetsAppHostStopItselfAfterTeardownBeforeSignalingIt()
{
// After replying, the AppHost waits briefly so that the replies to other `stop --wait` callers sharing its
// cleanup can still be sent, then stops itself. Signaling it as soon as this caller has its reply could close
// another caller's connection first. A real child process stands in for the AppHost: it is killed on the first
// clock read of the exit monitor to simulate the AppHost stopping itself, so a SIGTERM sent before the CLI
// starts observing it shows up in its exit code.
using var appHostProcess = TestProcesses.StartLongRunning();
try
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var timeProvider = new ObservingFakeTimeProvider();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var connection = CreateConnection(appHostPath, appHostProcess.Id);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
monitor.AddConnection(connection.SocketPath, connection);
var appHostIdentifier = Path.Combine("AppHost", "AppHost.csproj");
var stoppingStatus = string.Format(CultureInfo.CurrentCulture, StopCommandStrings.StoppingAppHost, appHostIdentifier);
interactionService.ShowStatusGateAsync = statusText =>
{
if (statusText == stoppingStatus)
{
timeProvider.OnNextUtcNowRead(() =>
{
appHostProcess.Kill();
appHostProcess.WaitForExit();
});
}
return Task.CompletedTask;
};
var services = CreateInstanceStopServices(workspace, monitor, interactionService, new TestProcessExecutionFactory(), interactive: false, options =>
{
options.TimeProvider = timeProvider;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse("stop --wait --non-interactive").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
Assert.True(appHostProcess.HasExited);
if (!OperatingSystem.IsWindows())
{
// 128 + SIGKILL (9): the process was killed by the simulated self-stop, not by a SIGTERM (128 + 15).
Assert.Equal(137, appHostProcess.ExitCode);
}
Assert.Equal(0, connection.StopAppHostCallCount);
Assert.Equal(1, Assert.IsType<TestAppHostSocket>(connection.Socket).TryDeleteCallCount);
Assert.Equal(
[
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostStoppedSuccessfully, appHostIdentifier),
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourcesTornDown, appHostIdentifier)
],
interactionService.DisplayedSuccess);
Assert.Empty(interactionService.DisplayedErrors);
}
finally
{
if (!appHostProcess.HasExited)
{
appHostProcess.Kill(entireProcessTree: true);
await appHostProcess.WaitForExitAsync().DefaultTimeout();
}
}
}
[Theory]
[InlineData("stop --wait --non-interactive", StopCommand.DefaultResourceTeardownTimeoutSeconds)]
[InlineData("stop --wait --timeout 5 --non-interactive", 5)]
[InlineData("stop --wait --timeout 4294967 --non-interactive", StopCommand.MaximumResourceTeardownTimeoutSeconds)]
public async Task StopCommand_Wait_ReportsTimeoutWhenResourceTeardownDoesNotComplete(string commandLine, int expectedTimeoutSeconds)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var timeProvider = new FakeTimeProvider();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var connection = CreateConnection(appHostPath, int.MaxValue - 1);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
connection.StopAppHostAndWaitForResourceCleanupHandler = async cancellationToken =>
{
// Advancing by exactly the expected timeout proves which timeout is in effect: a longer one never fires.
timeProvider.Advance(TimeSpan.FromSeconds(expectedTimeoutSeconds));
await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
return true;
};
monitor.AddConnection(connection.SocketPath, connection);
var services = CreateInstanceStopServices(workspace, monitor, interactionService, new TestProcessExecutionFactory(), interactive: false, options =>
{
options.TimeProvider = timeProvider;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse(commandLine).InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.WaitTimeout, exitCode);
var appHostIdentifier = Path.Combine("AppHost", "AppHost.csproj");
Assert.Equal(
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostStoppedSuccessfully, appHostIdentifier),
Assert.Single(interactionService.DisplayedSuccess));
Assert.Equal(
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownTimedOut, appHostIdentifier, expectedTimeoutSeconds),
Assert.Single(interactionService.DisplayedErrors));
}
[Fact]
public async Task StopCommand_Wait_ReportsTimeoutWhenAppHostRepliesNotConfirmedAfterDeadline()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var timeProvider = new FakeTimeProvider();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var connection = CreateConnection(appHostPath, int.MaxValue - 1);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
connection.StopAppHostAndWaitForResourceCleanupHandler = _ =>
{
// An AppHost that observes the cancellation sent for the expired deadline abandons the cleanup and replies
// that it was not confirmed instead of failing the request.
timeProvider.Advance(TimeSpan.FromSeconds(StopCommand.DefaultResourceTeardownTimeoutSeconds));
return Task.FromResult(false);
};
monitor.AddConnection(connection.SocketPath, connection);
var services = CreateInstanceStopServices(workspace, monitor, interactionService, new TestProcessExecutionFactory(), interactive: false, options =>
{
options.TimeProvider = timeProvider;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse("stop --wait --non-interactive").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.WaitTimeout, exitCode);
var appHostIdentifier = Path.Combine("AppHost", "AppHost.csproj");
Assert.Equal(
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostStoppedSuccessfully, appHostIdentifier),
Assert.Single(interactionService.DisplayedSuccess));
Assert.Equal(
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownTimedOut, appHostIdentifier, StopCommand.DefaultResourceTeardownTimeoutSeconds),
Assert.Single(interactionService.DisplayedErrors));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task StopCommand_Wait_LeavesAppHostRunningWhenTimedOutTeardownContinuesForAnotherCaller(bool selectByPid)
{
// Stands in for an AppHost that keeps running after this caller's wait timed out because another
// `stop --wait` caller is still waiting on the same shared resource cleanup. A real child process is used so
// a regression that signals or kills the AppHost is observable without endangering the test host.
using var appHostProcess = TestProcesses.StartLongRunning();
try
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var timeProvider = new FakeTimeProvider();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var connection = CreateConnection(appHostPath, appHostProcess.Id);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
connection.StopAppHostAndWaitForResourceCleanupHandler = async cancellationToken =>
{
timeProvider.Advance(TimeSpan.FromSeconds(StopCommand.DefaultResourceTeardownTimeoutSeconds));
await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
return true;
};
monitor.AddConnection(connection.SocketPath, connection);
var appHostIdentifier = selectByPid
? string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostIdentifierWithProcessId, Path.Combine("AppHost", "AppHost.csproj"), appHostProcess.Id)
: Path.Combine("AppHost", "AppHost.csproj");
var stoppingStatus = string.Format(CultureInfo.CurrentCulture, StopCommandStrings.StoppingAppHost, appHostIdentifier);
interactionService.ShowStatusGateAsync = statusText =>
{
// The exit monitor polls on the injected clock. Advancing it by the whole monitor window on each read
// lets the window elapse without a real wait, while the process is still alive.
if (statusText == stoppingStatus)
{
timeProvider.AutoAdvanceAmount = TimeSpan.FromSeconds(10);
}
return Task.CompletedTask;
};
var services = CreateInstanceStopServices(workspace, monitor, interactionService, new TestProcessExecutionFactory(), interactive: false, options =>
{
options.TimeProvider = timeProvider;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var commandLine = selectByPid
? $"stop --wait --pid {appHostProcess.Id.ToString(CultureInfo.InvariantCulture)} --non-interactive"
: "stop --wait --non-interactive";
var exitCode = await command.Parse(commandLine).InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
Assert.False(appHostProcess.HasExited);
Assert.Equal(0, connection.StopAppHostCallCount);
Assert.Equal(0, Assert.IsType<TestAppHostSocket>(connection.Socket).TryDeleteCallCount);
Assert.Empty(interactionService.DisplayedSuccess);
Assert.Equal(
[
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownTimedOut, appHostIdentifier, StopCommand.DefaultResourceTeardownTimeoutSeconds),
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostLeftRunningDuringResourceTeardown, appHostIdentifier, "--wait")
],
interactionService.DisplayedErrors);
}
finally
{
if (!appHostProcess.HasExited)
{
appHostProcess.Kill(entireProcessTree: true);
await appHostProcess.WaitForExitAsync().DefaultTimeout();
}
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task StopCommand_Wait_LeavesAppHostRunningWhenTeardownRequestDeliveryIsUncertain(bool selectByPid)
{
// The connection drops after the teardown request may have reached the AppHost, which can then be running a
// resource cleanup shared with another `stop --wait` caller. A real child process is used so a regression that
// signals or kills the AppHost is observable without endangering the test host.
using var appHostProcess = TestProcesses.StartLongRunning();
try
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var timeProvider = new FakeTimeProvider();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var connection = CreateConnection(appHostPath, appHostProcess.Id);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
connection.StopAppHostAndWaitForResourceCleanupHandler = _ => Task.FromException<bool>(new ConnectionLostException());
monitor.AddConnection(connection.SocketPath, connection);
var appHostIdentifier = selectByPid
? string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostIdentifierWithProcessId, Path.Combine("AppHost", "AppHost.csproj"), appHostProcess.Id)
: Path.Combine("AppHost", "AppHost.csproj");
var stoppingStatus = string.Format(CultureInfo.CurrentCulture, StopCommandStrings.StoppingAppHost, appHostIdentifier);
interactionService.ShowStatusGateAsync = statusText =>
{
// The exit monitor polls on the injected clock. Advancing it by the whole monitor window on each read
// lets the window elapse without a real wait, while the process is still alive.
if (statusText == stoppingStatus)
{
timeProvider.AutoAdvanceAmount = TimeSpan.FromSeconds(10);
}
return Task.CompletedTask;
};
var services = CreateInstanceStopServices(workspace, monitor, interactionService, new TestProcessExecutionFactory(), interactive: false, options =>
{
options.TimeProvider = timeProvider;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var commandLine = selectByPid
? $"stop --wait --pid {appHostProcess.Id.ToString(CultureInfo.InvariantCulture)} --non-interactive"
: "stop --wait --non-interactive";
var exitCode = await command.Parse(commandLine).InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
Assert.False(appHostProcess.HasExited);
Assert.Equal(1, connection.StopAppHostAndWaitForResourceCleanupCallCount);
Assert.Equal(0, connection.StopAppHostCallCount);
Assert.Equal(0, Assert.IsType<TestAppHostSocket>(connection.Socket).TryDeleteCallCount);
Assert.Empty(interactionService.DisplayedSuccess);
Assert.Equal(
[
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownNotConfirmed, appHostIdentifier),
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostLeftRunningDuringResourceTeardown, appHostIdentifier, "--wait")
],
interactionService.DisplayedErrors);
}
finally
{
if (!appHostProcess.HasExited)
{
appHostProcess.Kill(entireProcessTree: true);
await appHostProcess.WaitForExitAsync().DefaultTimeout();
}
}
}
[Theory]
[InlineData(nameof(ConnectionLostException))]
[InlineData(nameof(RemoteInvocationException))]
[InlineData(nameof(AppHostRequestNotSentException))]
[InlineData(nameof(TaskCanceledException))]
public async Task StopCommand_Wait_ReportsUnconfirmedTeardownWithoutRequestingStopWhenDeliveryIsUncertain(string failure)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var connection = CreateConnection(appHostPath, int.MaxValue - 1);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
// TaskCanceledException stands for an AppHost that canceled the request itself, for example while shutting
// down: StreamJsonRpc then completes the call as canceled although neither the command nor its deadline was.
connection.StopAppHostAndWaitForResourceCleanupHandler = failure switch
{
nameof(ConnectionLostException) => _ => Task.FromException<bool>(new ConnectionLostException()),
nameof(AppHostRequestNotSentException) => _ => Task.FromException<bool>(
new AppHostRequestNotSentException("The request was not sent.", new ObjectDisposedException("connection"))),
nameof(TaskCanceledException) => _ => Task.FromCanceled<bool>(new CancellationToken(canceled: true)),
_ => _ => Task.FromException<bool>(new RemoteInvocationException("The resource cleanup failed.", errorCode: -32000, errorData: null))
};
monitor.AddConnection(connection.SocketPath, connection);
var services = CreateInstanceStopServices(workspace, monitor, interactionService, new TestProcessExecutionFactory(), interactive: false);
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse("stop --wait --non-interactive").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
Assert.Equal(1, connection.StopAppHostAndWaitForResourceCleanupCallCount);
Assert.Equal(0, connection.StopAppHostCallCount);
Assert.Equal(1, Assert.IsType<TestAppHostSocket>(connection.Socket).TryDeleteCallCount);
var appHostIdentifier = Path.Combine("AppHost", "AppHost.csproj");
Assert.Equal(
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostStoppedSuccessfully, appHostIdentifier),
Assert.Single(interactionService.DisplayedSuccess));
Assert.Equal(
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownNotConfirmed, appHostIdentifier),
Assert.Single(interactionService.DisplayedErrors));
}
[Fact]
public async Task StopCommand_Wait_LeavesAppHostRunningWhenTeardownRequestWasNotSent()
{
// A second `stop --wait` caller whose connection is lost before it sends its teardown request: the request did
// not start a cleanup, but the first caller's request may have, and that caller is still waiting for the
// cleanup to finish. Signaling or killing the AppHost would disconnect that caller before it gets its result,
// so the AppHost is only observed. A real child process makes a regression that signals or kills it observable.
using var appHostProcess = TestProcesses.StartLongRunning();
try
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var timeProvider = new FakeTimeProvider();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var connection = CreateConnection(appHostPath, appHostProcess.Id);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
connection.StopAppHostAndWaitForResourceCleanupHandler = _ => Task.FromException<bool>(
new AppHostRequestNotSentException("The request was not sent.", new ObjectDisposedException("connection")));
monitor.AddConnection(connection.SocketPath, connection);
var appHostIdentifier = Path.Combine("AppHost", "AppHost.csproj");
var stoppingStatus = string.Format(CultureInfo.CurrentCulture, StopCommandStrings.StoppingAppHost, appHostIdentifier);
interactionService.ShowStatusGateAsync = statusText =>
{
// The exit monitor polls on the injected clock. Advancing it by the whole monitor window on each read
// lets the window elapse without a real wait, while the process is still alive.
if (statusText == stoppingStatus)
{
timeProvider.AutoAdvanceAmount = TimeSpan.FromSeconds(10);
}
return Task.CompletedTask;
};
var services = CreateInstanceStopServices(workspace, monitor, interactionService, new TestProcessExecutionFactory(), interactive: false, options =>
{
options.TimeProvider = timeProvider;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse("stop --wait --non-interactive").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
Assert.False(appHostProcess.HasExited);
Assert.Equal(1, connection.StopAppHostAndWaitForResourceCleanupCallCount);
Assert.Equal(0, connection.StopAppHostCallCount);
Assert.Equal(0, Assert.IsType<TestAppHostSocket>(connection.Socket).TryDeleteCallCount);
Assert.Empty(interactionService.DisplayedSuccess);
Assert.Equal(
[
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownNotConfirmed, appHostIdentifier),
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostLeftRunningDuringResourceTeardown, appHostIdentifier, "--wait")
],
interactionService.DisplayedErrors);
}
finally
{
if (!appHostProcess.HasExited)
{
appHostProcess.Kill(entireProcessTree: true);
await appHostProcess.WaitForExitAsync().DefaultTimeout();
}
}
}
[Theory]
[InlineData(nameof(ConnectionLostException))]
[InlineData(nameof(AppHostRequestNotSentException))]
public async Task StopCommand_Wait_ReportsAppHostLeftRunningWhenItsExitCannotBeObserved(string failure)
{
// A connection without AppHost information gives no process to observe. When the AppHost may still be running
// for another caller, the command must not report it as stopped, delete its socket, or let --force clean up
// persistent resources under it.
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = new TestAppHostAuxiliaryBackchannel
{
AppHostInfo = null,
IsInScope = true,
StopAppHostAndWaitForResourceCleanupHandler = failure == nameof(ConnectionLostException)
? _ => Task.FromException<bool>(new ConnectionLostException())
: _ => Task.FromException<bool>(new AppHostRequestNotSentException("The request was not sent.", new ObjectDisposedException("connection")))
};
monitor.AddConnection(connection.SocketPath, connection);
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
options.CliHostEnvironmentFactory = _ => TestHelpers.CreateNonInteractiveHostEnvironment();
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse("stop --wait").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
Assert.Equal(1, connection.StopAppHostAndWaitForResourceCleanupCallCount);
Assert.Equal(0, connection.StopAppHostCallCount);
Assert.Equal(0, Assert.IsType<TestAppHostSocket>(connection.Socket).TryDeleteCallCount);
Assert.Empty(interactionService.DisplayedSuccess);
Assert.Equal(
[
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownNotConfirmed, "Unknown"),
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostLeftRunningDuringResourceTeardown, "Unknown", "--wait")
],
interactionService.DisplayedErrors);
}
[Fact]
public async Task StopCommand_Wait_StopsAppHostWhenItRejectsTeardownRequest()
{
// The AppHost replied that it does not handle the teardown request, so it cannot be running a cleanup shared
// with another caller, and the regular stop must still stop it. A real child process makes the stop observable.
using var appHostProcess = TestProcesses.StartLongRunning();
try
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var connection = CreateConnection(appHostPath, appHostProcess.Id);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
connection.StopAppHostAndWaitForResourceCleanupHandler = _ => Task.FromException<bool>(CreateRemoteMethodNotFoundException());
monitor.AddConnection(connection.SocketPath, connection);
var services = CreateInstanceStopServices(workspace, monitor, interactionService, new TestProcessExecutionFactory(), interactive: false);
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse("stop --wait --non-interactive").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
Assert.True(appHostProcess.HasExited);
Assert.Equal(1, connection.StopAppHostAndWaitForResourceCleanupCallCount);
Assert.Equal(1, Assert.IsType<TestAppHostSocket>(connection.Socket).TryDeleteCallCount);
var appHostIdentifier = Path.Combine("AppHost", "AppHost.csproj");
Assert.Equal(
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostStoppedSuccessfully, appHostIdentifier),
Assert.Single(interactionService.DisplayedSuccess));
Assert.Equal(
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownNotConfirmed, appHostIdentifier),
Assert.Single(interactionService.DisplayedErrors));
}
finally
{
if (!appHostProcess.HasExited)
{
appHostProcess.Kill(entireProcessTree: true);
await appHostProcess.WaitForExitAsync().DefaultTimeout();
}
}
}
[Theory]
[InlineData("stop --timeout 30 --non-interactive")]
[InlineData("stop --wait --timeout 0 --non-interactive")]
[InlineData("stop --wait --timeout -1 --non-interactive")]
[InlineData("stop --wait --timeout 4294968 --non-interactive")]
public async Task StopCommand_InvalidTimeout_FailsWithoutStopping(string commandLine)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var connection = CreateConnection(appHostPath, int.MaxValue - 1);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
monitor.AddConnection(connection.SocketPath, connection);
var services = CreateInstanceStopServices(workspace, monitor, interactionService, new TestProcessExecutionFactory(), interactive: false);
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse(commandLine).InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.InvalidCommand, exitCode);
Assert.Equal(0, connection.StopAppHostCallCount);
Assert.Equal(0, connection.StopAppHostAndWaitForResourceCleanupCallCount);
var expectedError = commandLine.Contains("--wait", StringComparison.Ordinal)
? string.Format(CultureInfo.CurrentCulture, StopCommandStrings.TimeoutInvalid, StopCommand.MaximumResourceTeardownTimeoutSeconds)
: string.Format(CultureInfo.CurrentCulture, StopCommandStrings.TimeoutRequiresWait, "--timeout", "--wait");
Assert.Equal(expectedError, Assert.Single(interactionService.DisplayedErrors));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task StopCommand_AllWait_ExitCodeDoesNotDependOnTeardownCompletionOrder(bool unsupportedReportsFirst)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var firstErrorDisplayed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
interactionService.DisplayErrorCallback = _ => firstErrorDisplayed.TrySetResult();
var monitor = new TestAuxiliaryBackchannelMonitor();
// An AppHost that cannot wait for teardown reports exit code 9; one whose teardown is not confirmed reports 2.
var unsupported = CreateConnection(Path.Combine(workspace.WorkspaceRoot.FullName, "App1", "AppHost.cs"), int.MaxValue - 1);
unsupported.SupportsStopResourceCleanupV1 = false;
var unconfirmed = CreateConnection(Path.Combine(workspace.WorkspaceRoot.FullName, "App2", "AppHost.cs"), int.MaxValue - 2);
// The AppHost that reports second waits until the other one has displayed its error.
if (unsupportedReportsFirst)
{
unconfirmed.StopAppHostAndWaitForResourceCleanupHandler = async _ =>
{
await firstErrorDisplayed.Task;
return false;
};
}
else
{
unconfirmed.StopAppHostAndWaitForResourceCleanupHandler = _ => Task.FromResult(false);
var stoppingUnsupported = string.Format(CultureInfo.CurrentCulture, StopCommandStrings.StoppingAppHost, Path.Combine("App1", "AppHost.cs"));
interactionService.ShowStatusGateAsync = statusText => statusText == stoppingUnsupported ? firstErrorDisplayed.Task : Task.CompletedTask;
}
monitor.AddConnection("socket.hash1", unsupported);
monitor.AddConnection("socket.hash2", unconfirmed);
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse("stop --all --wait").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
var expectedErrors = new[]
{
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownUnsupported, Path.Combine("App1", "AppHost.cs"), "--wait"),
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownNotConfirmed, Path.Combine("App2", "AppHost.cs"))
};
Assert.Equal(unsupportedReportsFirst ? expectedErrors : expectedErrors.Reverse(), interactionService.DisplayedErrors);
}
[Theory]
[InlineData(false, CliExitCodes.AppHostIncompatible)]
[InlineData(true, CliExitCodes.FailedToDotnetRunAppHost)]
public async Task StopCommand_Wait_ReportsUnconfirmedResourceTeardown(bool supportsResourceCleanup, int expectedExitCode)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interactionService = new TestInteractionService();
var monitor = new TestAuxiliaryBackchannelMonitor();
var appHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "AppHost", "AppHost.csproj");
var connection = CreateConnection(appHostPath, int.MaxValue - 1);
connection.SocketPath = CreateMatchingSocketFile(appHostPath, workspace, 1);
connection.SupportsStopResourceCleanupV1 = supportsResourceCleanup;
connection.StopAppHostAndWaitForResourceCleanupHandler = _ => Task.FromResult(false);
monitor.AddConnection(connection.SocketPath, connection);
var services = CreateInstanceStopServices(workspace, monitor, interactionService, new TestProcessExecutionFactory(), interactive: false);
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse("stop --wait --non-interactive").InvokeAsync().DefaultTimeout();
Assert.Equal(expectedExitCode, exitCode);
Assert.Equal(supportsResourceCleanup ? 1 : 0, connection.StopAppHostAndWaitForResourceCleanupCallCount);
var appHostIdentifier = Path.Combine("AppHost", "AppHost.csproj");
var expectedError = supportsResourceCleanup
? string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownNotConfirmed, appHostIdentifier)
: string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownUnsupported, appHostIdentifier, "--wait");
Assert.Equal(expectedError, Assert.Single(interactionService.DisplayedErrors));
}
[Fact]
public async Task StopCommand_ForceWaitStillCleansUpPersistentResourcesWhenTeardownIsNotConfirmed()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = CreateConnection(appHostFile.FullName, int.MaxValue - 12);
connection.SocketPath = CreateMatchingSocketFile(appHostFile.FullName, workspace, 12);
connection.StopAppHostAndWaitForResourceCleanupHandler = _ => Task.FromResult(false);
monitor.AddConnection(connection.SocketPath, connection);
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
options.CliHostEnvironmentFactory = _ => TestHelpers.CreateNonInteractiveHostEnvironment();
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse("stop --force --wait").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
Assert.Equal(1, connection.StopAppHostAndWaitForResourceCleanupCallCount);
AssertDcpCleanupInvocation(processFactory, AppHostWorkloadId.Create(appHostFile));
var appHostIdentifier = Path.Combine("AppHost", "AppHost.csproj");
Assert.Equal(
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownNotConfirmed, appHostIdentifier),
Assert.Single(interactionService.DisplayedErrors));
Assert.Equal(
[
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostStoppedSuccessfully, appHostIdentifier),
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.PersistentResourcesCleaned, appHostFile.Name)
],
interactionService.DisplayedSuccess);
}
[Fact]
public async Task StopCommand_ForceWait_DoesNotCleanUpPersistentResourcesWhenAppHostIsLeftRunning()
{
// The teardown request was not sent, so another `stop --wait` caller may still be waiting on a cleanup and the
// AppHost is left running. Persistent resources must not be cleaned up under a live AppHost, and the command
// must fail. A real child process stands in for the AppHost so a regression that stops it is observable.
using var appHostProcess = TestProcesses.StartLongRunning();
try
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var interactionService = new TestInteractionService();
var appHostDirectory = workspace.WorkspaceRoot.CreateSubdirectory("AppHost");
var appHostFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(appHostFile.FullName, "<Project />");
var processFactory = new TestProcessExecutionFactory();
var timeProvider = new FakeTimeProvider();
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = CreateConnection(appHostFile.FullName, appHostProcess.Id);
connection.SocketPath = CreateMatchingSocketFile(appHostFile.FullName, workspace, 13);
connection.StopAppHostAndWaitForResourceCleanupHandler = _ => Task.FromException<bool>(
new AppHostRequestNotSentException("The request was not sent.", new ObjectDisposedException("connection")));
monitor.AddConnection(connection.SocketPath, connection);
var appHostIdentifier = Path.Combine("AppHost", "AppHost.csproj");
var stoppingStatus = string.Format(CultureInfo.CurrentCulture, StopCommandStrings.StoppingAppHost, appHostIdentifier);
interactionService.ShowStatusGateAsync = statusText =>
{
// The exit monitor polls on the injected clock. Advancing it by the whole monitor window on each read
// lets the window elapse without a real wait, while the process is still alive.
if (statusText == stoppingStatus)
{
timeProvider.AutoAdvanceAmount = TimeSpan.FromSeconds(10);
}
return Task.CompletedTask;
};
var services = CreateStopForceServices(workspace, interactionService, processFactory, options =>
{
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
options.CliHostEnvironmentFactory = _ => TestHelpers.CreateNonInteractiveHostEnvironment();
options.TimeProvider = timeProvider;
});
using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var exitCode = await command.Parse("stop --force --wait").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.FailedToDotnetRunAppHost, exitCode);
Assert.False(appHostProcess.HasExited);
Assert.Equal(1, connection.StopAppHostAndWaitForResourceCleanupCallCount);
Assert.Equal(0, connection.StopAppHostCallCount);
Assert.Empty(processFactory.CreatedExecutions);
Assert.Empty(interactionService.DisplayedSuccess);
Assert.Equal(
[
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownNotConfirmed, appHostIdentifier),
string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostLeftRunningDuringResourceTeardown, appHostIdentifier, "--wait")
],
interactionService.DisplayedErrors);
}
finally
{
if (!appHostProcess.HasExited)
{
appHostProcess.Kill(entireProcessTree: true);
await appHostProcess.WaitForExitAsync().DefaultTimeout();
}
}
}
private IServiceCollection CreateStopForceServices(
TemporaryWorkspace workspace,
TestInteractionService interactionService,
TestProcessExecutionFactory processFactory,
Action<CliServiceCollectionTestOptions>? configure = null,
bool createDcpExecutable = true,
bool useBundleLayout = true)
{
var layoutRoot = workspace.WorkspaceRoot.CreateSubdirectory("layout");
var dcpDirectory = layoutRoot.CreateSubdirectory("dcp");
if (createDcpExecutable)
{
File.WriteAllText(BundleDiscovery.GetDcpExecutablePath(dcpDirectory.FullName), "");
}
var layout = new LayoutConfiguration
{
LayoutPath = layoutRoot.FullName,
Components = new LayoutComponents { Dcp = "dcp" }
};
return CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.DotNetCliExecutionFactoryFactory = _ => processFactory;
options.DotNetCliRunnerFactory = _ => new TestDotNetCliRunner();
if (useBundleLayout)
{
options.BundleServiceFactory = _ => new TestBundleService(isBundle: true) { Layout = layout };
}
else
{
options.BundleServiceFactory = _ => new NullBundleService();
options.LayoutDiscoveryFactory = _ => new FixedLayoutDiscovery(layout);
}
configure?.Invoke(options);
});
}
private static void AssertDcpCleanupInvocation(
TestProcessExecutionFactory processFactory,
string expectedWorkloadId,
bool deleteVolumes = false)
{
string[] expectedArguments = deleteVolumes
? ["cleanup", "--volumes", expectedWorkloadId]
: ["cleanup", expectedWorkloadId];
var execution = Assert.Single(processFactory.CreatedExecutions.OfType<TestProcessExecution>(), execution =>
execution.Arguments.Count > 0 &&
execution.Arguments[0] == "cleanup");
Assert.Equal(expectedArguments, execution.Arguments);
Assert.EndsWith(BundleDiscovery.GetDcpExecutableName(), execution.FileName, StringComparison.Ordinal);
}
private static JsonDocument CreateAppHostInfoJson(string? aspireHostingVersion, bool isUsingCliBundle)
{
var aspireHostingVersionJson = aspireHostingVersion is null ? "null" : $"\"{aspireHostingVersion}\"";
return JsonDocument.Parse($$"""
{
"Properties": {
"IsAspireHost": "true",
"AspireHostingSDKVersion": {{aspireHostingVersionJson}},
"AspireUseCliBundle": "{{(isUsingCliBundle ? "true" : "false")}}"
},
"Items": {}
}
""");
}
private IServiceCollection CreateInstanceStopServices(
TemporaryWorkspace workspace,
TestAuxiliaryBackchannelMonitor monitor,
TestInteractionService interactionService,
TestProcessExecutionFactory processFactory,
bool interactive,
Action<CliServiceCollectionTestOptions>? configure = null)
{
return CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interactionService;
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
options.DotNetCliExecutionFactoryFactory = _ => processFactory;
options.CliHostEnvironmentFactory = _ => interactive
? TestHelpers.CreateInteractiveHostEnvironment()
: TestHelpers.CreateNonInteractiveHostEnvironment();
options.ProjectLocatorFactory = _ => new TestProjectLocator
{
UseOrFindAppHostProjectFileWithBehaviorAsyncCallback = (_, _, _, _) =>
throw new InvalidOperationException("Instance targeting must not discover or validate projects.")
};
configure?.Invoke(options);
});
}
private static TestAppHostAuxiliaryBackchannel CreateConnection(string appHostPath, int processId, bool isInScope = true)
{
return new TestAppHostAuxiliaryBackchannel
{
SocketPath = $"socket.{processId.ToString(CultureInfo.InvariantCulture)}",
IsInScope = isInScope,
AppHostInfo = new AppHostInformation
{
AppHostPath = appHostPath,
ProcessId = processId
}
};
}
// StreamJsonRpc raises RemoteMethodNotFoundException when the AppHost replies that it has no such method, and its
// constructor is not public, so the test creates it the way the library does.
private static RemoteMethodNotFoundException CreateRemoteMethodNotFoundException()
=> (RemoteMethodNotFoundException)Activator.CreateInstance(
typeof(RemoteMethodNotFoundException),
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic,
binder: null,
args: ["The method was not found.", "StopAsync", StreamJsonRpc.Protocol.JsonRpcErrorCode.MethodNotFound, null, null],
culture: null)!;
private static string CreateMatchingSocketFile(string appHostPath, TemporaryWorkspace workspace, int instanceId)
{
var homeDirectory = new DirectoryInfo(Path.Combine(workspace.WorkspaceRoot.FullName, ".home"));
var backchannelsDirectory = Path.Combine(homeDirectory.FullName, ".aspire", "cli", "bch");
Directory.CreateDirectory(backchannelsDirectory);
var resolvedAppHostPath = PathNormalizer.ResolveSymlinks(appHostPath);
var prefix = BackchannelConstants.ComputeSocketPrefix(resolvedAppHostPath, homeDirectory.FullName);
var appHostId = Path.GetFileName(prefix);
var instanceSuffix = instanceId.ToString("000", CultureInfo.InvariantCulture);
var socketPath = Path.Combine(
backchannelsDirectory,
$"{appHostId}a1b2c{instanceSuffix}.{Environment.ProcessId.ToString(CultureInfo.InvariantCulture)}");
File.WriteAllText(socketPath, "");
return socketPath;
}
private static string[] GetDisplayedText(TestInteractionService interactionService, ConcurrentQueue<string> statusMessages)
{
return interactionService.DisplayedMessages.Select(message => message.Message)
.Concat(interactionService.DisplayedSuccess)
.Concat(interactionService.DisplayedErrors)
.Concat(statusMessages)
.ToArray();
}
}