Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions src/Aspire.Cli/Commands/AddCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -212,12 +212,10 @@ await Parallel.ForEachAsync(channels, cancellationToken, async (channel, ct) =>
// which prevents 'dotnet add package' from modifying the project.
if (_features.IsFeatureEnabled(KnownFeatures.RunningInstanceDetectionEnabled, defaultValue: true))
{
var runningInstanceResult = await InteractionService.ShowStatusAsync(
AddCommandStrings.CheckingForRunningInstances,
async () => await project.FindAndStopRunningInstanceAsync(
effectiveAppHostProjectFile,
ExecutionContext.HomeDirectory,
cancellationToken));
var runningInstanceResult = await project.FindAndStopRunningInstanceAsync(
effectiveAppHostProjectFile,
ExecutionContext.HomeDirectory,
cancellationToken);

if (runningInstanceResult == RunningInstanceResult.InstanceStopped)
{
Expand Down
109 changes: 53 additions & 56 deletions src/Aspire.Cli/Commands/AppHostLauncher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
using Aspire.Cli.Resources;
using Aspire.Cli.Utils;
using Microsoft.Extensions.Logging;
using Spectre.Console;

namespace Aspire.Cli.Commands;

Expand All @@ -27,7 +26,6 @@ internal sealed class AppHostLauncher(
CliExecutionContext executionContext,
IFeatures features,
IInteractionService interactionService,
IAnsiConsole ansiConsole,
IAuxiliaryBackchannelMonitor backchannelMonitor,
ILogger<AppHostLauncher> logger,
TimeProvider timeProvider)
Expand Down Expand Up @@ -122,7 +120,9 @@ public async Task<int> LaunchDetachedAsync(
logger.LogDebug("Waiting for socket with prefix: {SocketPrefix}, Hash: {Hash}", expectedSocketPrefix, expectedHash);

// Start the child process and wait for the backchannel
var launchResult = await LaunchAndWaitForBackchannelAsync(executablePath, childArgs, expectedHash, cancellationToken);
var launchResult = await interactionService.ShowStatusAsync(
RunCommandStrings.StartingAppHostInBackground,
() => LaunchAndWaitForBackchannelAsync(executablePath, childArgs, expectedHash, cancellationToken));

// Handle failure cases
if (launchResult.Backchannel is null || launchResult.ChildProcess is null)
Expand All @@ -131,7 +131,7 @@ public async Task<int> LaunchDetachedAsync(
}

// Display results
await DisplayLaunchResultAsync(launchResult, effectiveAppHostFile, childLogFile, format, isExtensionHost, cancellationToken);
DisplayLaunchResult(launchResult, effectiveAppHostFile, childLogFile, format, isExtensionHost);

return ExitCodeConstants.Success;
}
Expand Down Expand Up @@ -203,76 +203,74 @@ private async Task StopExistingInstancesAsync(FileInfo effectiveAppHostFile, Can
return (dotnetPath, childArgs);
}

private record LaunchResult(Process? ChildProcess, IAppHostAuxiliaryBackchannel? Backchannel, bool ChildExitedEarly, int ChildExitCode);
private record LaunchResult(Process? ChildProcess, IAppHostAuxiliaryBackchannel? Backchannel, DashboardUrlsState? DashboardUrls, bool ChildExitedEarly, int ChildExitCode);

private async Task<LaunchResult> LaunchAndWaitForBackchannelAsync(
string executablePath,
List<string> childArgs,
string expectedHash,
CancellationToken cancellationToken)
{
Process? childProcess = null;
var childExitedEarly = false;
var childExitCode = 0;
Process childProcess;

async Task<IAppHostAuxiliaryBackchannel?> WaitForBackchannelAsync()
try
{
try
{
childProcess = DetachedProcessLauncher.Start(
executablePath,
childArgs,
executionContext.WorkingDirectory.FullName);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to start child CLI process");
return null;
}

logger.LogDebug("Child CLI process started with PID: {PID}", childProcess.Id);
childProcess = DetachedProcessLauncher.Start(
executablePath,
childArgs,
executionContext.WorkingDirectory.FullName);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to start child CLI process");
return new LaunchResult(null, null, null, false, 0);
}

var startTime = timeProvider.GetUtcNow();
var timeout = TimeSpan.FromSeconds(120);
logger.LogDebug("Child CLI process started with PID: {PID}", childProcess.Id);

while (timeProvider.GetUtcNow() - startTime < timeout)
{
cancellationToken.ThrowIfCancellationRequested();
var startTime = timeProvider.GetUtcNow();
var timeout = TimeSpan.FromSeconds(120);

if (childProcess.HasExited)
{
childExitedEarly = true;
childExitCode = childProcess.ExitCode;
logger.LogWarning("Child CLI process exited with code {ExitCode}", childExitCode);
return null;
}
while (timeProvider.GetUtcNow() - startTime < timeout)
{
cancellationToken.ThrowIfCancellationRequested();

await backchannelMonitor.ScanAsync(cancellationToken).ConfigureAwait(false);
if (childProcess.HasExited)
{
var exitCode = childProcess.ExitCode;
logger.LogWarning("Child CLI process exited with code {ExitCode}", exitCode);
return new LaunchResult(childProcess, null, null, true, exitCode);
}

var connection = backchannelMonitor.GetConnectionsByHash(expectedHash).FirstOrDefault();
if (connection is not null)
{
return connection;
}
await backchannelMonitor.ScanAsync(cancellationToken).ConfigureAwait(false);

var connection = backchannelMonitor.GetConnectionsByHash(expectedHash).FirstOrDefault();
if (connection is not null)
{
DashboardUrlsState? dashboardUrls = null;
try
{
await childProcess.WaitForExitAsync(cancellationToken).WaitAsync(TimeSpan.FromMilliseconds(500), cancellationToken).ConfigureAwait(false);
dashboardUrls = await connection.GetDashboardUrlsAsync(cancellationToken).ConfigureAwait(false);
}
catch (TimeoutException)
catch (Exception ex)
{
// Expected - the 500ms delay elapsed without the process exiting
logger.LogDebug(ex, "Failed to retrieve dashboard URLs from backchannel connection. Continuing without dashboard URLs.");
}

return new LaunchResult(childProcess, connection, dashboardUrls, false, 0);
}

return null;
try
{
await childProcess.WaitForExitAsync(cancellationToken).WaitAsync(TimeSpan.FromMilliseconds(500), cancellationToken).ConfigureAwait(false);
}
catch (TimeoutException)
{
// Expected - the 500ms delay elapsed without the process exiting
}
}

var backchannel = await interactionService.ShowStatusAsync(
RunCommandStrings.StartingAppHostInBackground,
WaitForBackchannelAsync);

return new LaunchResult(childProcess, backchannel, childExitedEarly, childExitCode);
return new LaunchResult(childProcess, null, null, false, 0);
}

private int HandleLaunchFailure(LaunchResult result, string childLogFile)
Expand Down Expand Up @@ -312,16 +310,15 @@ private int HandleLaunchFailure(LaunchResult result, string childLogFile)
return ExitCodeConstants.FailedToDotnetRunAppHost;
}

private async Task DisplayLaunchResultAsync(
private void DisplayLaunchResult(
LaunchResult result,
FileInfo effectiveAppHostFile,
string childLogFile,
OutputFormat? format,
bool isExtensionHost,
CancellationToken cancellationToken)
bool isExtensionHost)
{
var appHostInfo = result.Backchannel!.AppHostInfo;
var dashboardUrls = await result.Backchannel.GetDashboardUrlsAsync(cancellationToken).ConfigureAwait(false);
var dashboardUrls = result.DashboardUrls;
var pid = appHostInfo?.ProcessId ?? result.ChildProcess!.Id;

if (format == OutputFormat.Json)
Expand All @@ -339,14 +336,14 @@ private async Task DisplayLaunchResultAsync(
{
var appHostRelativePath = Path.GetRelativePath(executionContext.WorkingDirectory.FullName, effectiveAppHostFile.FullName);
RunCommand.RenderAppHostSummary(
ansiConsole,
interactionService,
appHostRelativePath,
dashboardUrls?.BaseUrlWithLoginToken,
codespacesUrl: null,
childLogFile,
isExtensionHost,
pid);
ansiConsole.WriteLine();
interactionService.DisplayEmptyLine();

interactionService.DisplaySuccess(RunCommandStrings.AppHostStartedSuccessfully);
}
Expand Down
4 changes: 0 additions & 4 deletions src/Aspire.Cli/Commands/ExecCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
using Aspire.Cli.Telemetry;
using Aspire.Cli.Utils;
using Aspire.Hosting;
using Spectre.Console;

namespace Aspire.Cli.Commands;

Expand All @@ -22,7 +21,6 @@ internal class ExecCommand : BaseCommand
private readonly IDotNetCliRunner _runner;
private readonly ICertificateService _certificateService;
private readonly IProjectLocator _projectLocator;
private readonly IAnsiConsole _ansiConsole;
private readonly IDotNetSdkInstaller _sdkInstaller;

private static readonly OptionWithLegacy<FileInfo?> s_appHostOption = new("--apphost", "--project", ExecCommandStrings.ProjectArgumentDescription);
Expand All @@ -48,7 +46,6 @@ public ExecCommand(
IInteractionService interactionService,
ICertificateService certificateService,
IProjectLocator projectLocator,
IAnsiConsole ansiConsole,
AspireCliTelemetry telemetry,
IDotNetSdkInstaller sdkInstaller,
IFeatures features,
Expand All @@ -59,7 +56,6 @@ public ExecCommand(
_runner = runner;
_certificateService = certificateService;
_projectLocator = projectLocator;
_ansiConsole = ansiConsole;
_sdkInstaller = sdkInstaller;

Options.Add(s_appHostOption);
Expand Down
Loading
Loading