Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add command annotations and wire up #5538

Merged
merged 4 commits into from
Sep 20, 2024
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
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@
<PackageVersion Include="Grpc.Tools" Version="2.66.0" />
<PackageVersion Include="Humanizer.Core" Version="2.14.1" />
<PackageVersion Include="KubernetesClient" Version="14.0.9" />
<PackageVersion Include="JsonPatch.Net" Version="3.1.1" />
JamesNK marked this conversation as resolved.
Show resolved Hide resolved
<PackageVersion Include="Microsoft.Data.SqlClient" Version="5.2.2" />
<PackageVersion Include="Microsoft.FluentUI.AspNetCore.Components" Version="4.9.3" />
<PackageVersion Include="Microsoft.FluentUI.AspNetCore.Components.Icons" Version="4.9.3" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
}
else
{
<FluentMenuItem OnClick="() => HandleItemClicked(item)" title="@item.Tooltip">
<FluentMenuItem OnClick="() => HandleItemClicked(item)" title="@item.Tooltip" Disabled="@item.IsDisabled">
@item.Text
@if (item.Icon != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
@using Aspire.Dashboard.Model
@using Microsoft.FluentUI.AspNetCore.Components

@foreach (var highlightedCommand in Commands.Where(c => c.IsHighlighted))
@foreach (var highlightedCommand in Commands.Where(c => c.IsHighlighted && c.State != CommandViewModelState.Hidden))
Copy link
Member

@mitchdenny mitchdenny Sep 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should there be a maximum number of highlighted commands? Or rather only the first N highlighted commands?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe. It's easy to change if necessary.

{
<FluentButton Appearance="Appearance.Lightweight" Title="@(highlightedCommand.DisplayDescription ?? highlightedCommand.DisplayName)" OnClick="@(() => CommandSelected.InvokeAsync(highlightedCommand))">
<FluentButton Appearance="Appearance.Lightweight" Title="@(highlightedCommand.DisplayDescription ?? highlightedCommand.DisplayName)" OnClick="@(() => CommandSelected.InvokeAsync(highlightedCommand))" Disabled="@(highlightedCommand.State == CommandViewModelState.Disabled)">
@if (!string.IsNullOrEmpty(highlightedCommand.IconName) && CommandViewModel.ResolveIconName(highlightedCommand.IconName) is { } icon)
{
<FluentIcon Value="icon" />
<FluentIcon Value="@icon" />
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ protected override void OnParametersSet()
OnClick = OnConsoleLogs.InvokeAsync
});

var menuCommands = Commands.Where(c => !c.IsHighlighted).ToList();
var menuCommands = Commands.Where(c => !c.IsHighlighted && c.State != CommandViewModelState.Hidden).ToList();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should the context menu show all commands regardless of whether they are highlighted or not?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dunno. It's easy to change.

if (menuCommands.Count > 0)
{
_menuItems.Add(new MenuButtonItem { IsDivider = true });
Expand All @@ -63,7 +63,8 @@ protected override void OnParametersSet()
Text = command.DisplayName,
Tooltip = command.DisplayDescription,
Icon = icon,
OnClick = () => CommandSelected.InvokeAsync(command)
OnClick = () => CommandSelected.InvokeAsync(command),
IsDisabled = command.State == CommandViewModelState.Disabled
});
}
}
Expand Down
6 changes: 4 additions & 2 deletions src/Aspire.Dashboard/Components/Pages/Resources.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -312,16 +312,18 @@ private async Task ExecuteResourceCommandAsync(ResourceViewModel resource, Comma

var response = await DashboardClient.ExecuteResourceCommandAsync(resource.Name, resource.ResourceType, command, CancellationToken.None);

var messageResourceName = GetResourceName(resource);

if (response.Kind == ResourceCommandResponseKind.Succeeded)
{
ToastService.ShowSuccess(string.Format(CultureInfo.InvariantCulture, Loc[nameof(Dashboard.Resources.Resources.ResourceCommandSuccess)], command.DisplayName));
ToastService.ShowSuccess(string.Format(CultureInfo.InvariantCulture, Loc[nameof(Dashboard.Resources.Resources.ResourceCommandSuccess)], command.DisplayName + " " + messageResourceName));
}
else
{
ToastService.ShowCommunicationToast(new ToastParameters<CommunicationToastContent>()
{
Intent = ToastIntent.Error,
Title = string.Format(CultureInfo.InvariantCulture, Loc[nameof(Dashboard.Resources.Resources.ResourceCommandFailed)], command.DisplayName),
Title = string.Format(CultureInfo.InvariantCulture, Loc[nameof(Dashboard.Resources.Resources.ResourceCommandFailed)], command.DisplayName + " " + messageResourceName),
PrimaryAction = Loc[nameof(Dashboard.Resources.Resources.ResourceCommandToastViewLogs)],
OnPrimaryAction = EventCallback.Factory.Create<ToastResult>(this, () => NavigationManager.NavigateTo(DashboardUrls.ConsoleLogsUrl(resource: resource.Name))),
Content = new CommunicationToastContent()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
Class="severity-icon" />
}
}
else if (Resource.IsStartingOrBuildingOrWaiting())
else if (Resource.IsUnusableTransitoryState())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a race with #5770 :)

{
<FluentIcon Icon="Icons.Regular.Size16.CircleHint"
Color="Color.Info"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ public static bool IsStopped(this ResourceViewModel resource)
return resource.KnownState is KnownResourceState.Exited or KnownResourceState.Finished or KnownResourceState.FailedToStart;
}

public static bool IsStartingOrBuildingOrWaiting(this ResourceViewModel resource)
public static bool IsUnusableTransitoryState(this ResourceViewModel resource)
{
return resource.KnownState is KnownResourceState.Starting or KnownResourceState.Building or KnownResourceState.Waiting;
return resource.KnownState is KnownResourceState.Starting or KnownResourceState.Building or KnownResourceState.Waiting or KnownResourceState.Stopping;
}

public static bool HasNoState(this ResourceViewModel resource) => string.IsNullOrEmpty(resource.State);
Expand Down
3 changes: 2 additions & 1 deletion src/Aspire.Dashboard/Model/KnownResourceState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ public enum KnownResourceState
Running,
Building,
Hidden,
Waiting
Waiting,
Stopping
}
1 change: 1 addition & 0 deletions src/Aspire.Dashboard/Model/MenuButtonItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ public class MenuButtonItem
public string? Tooltip { get; set; }
public Icon? Icon { get; set; }
public Func<Task>? OnClick { get; set; }
public bool IsDisabled { get; set; }
}
11 changes: 10 additions & 1 deletion src/Aspire.Dashboard/Model/ResourceViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,19 +74,21 @@ public sealed class CommandViewModel
private static readonly ConcurrentDictionary<string, CustomIcon?> s_iconCache = new();

public string CommandType { get; }
public CommandViewModelState State { get; }
public string DisplayName { get; }
public string? DisplayDescription { get; }
public string? ConfirmationMessage { get; }
public Value? Parameter { get; }
public bool IsHighlighted { get; }
public string? IconName { get; }

public CommandViewModel(string commandType, string displayName, string? displayDescription, string? confirmationMessage, Value? parameter, bool isHighlighted, string? iconName)
public CommandViewModel(string commandType, CommandViewModelState state, string displayName, string? displayDescription, string? confirmationMessage, Value? parameter, bool isHighlighted, string? iconName)
{
ArgumentException.ThrowIfNullOrWhiteSpace(commandType);
ArgumentException.ThrowIfNullOrWhiteSpace(displayName);

CommandType = commandType;
State = state;
DisplayName = displayName;
DisplayDescription = displayDescription;
ConfirmationMessage = confirmationMessage;
Expand Down Expand Up @@ -118,6 +120,13 @@ public CommandViewModel(string commandType, string displayName, string? displayD
}
}

public enum CommandViewModelState
{
Enabled,
Disabled,
Hidden
}

[DebuggerDisplay("Name = {Name}, Value = {Value}, FromSpec = {FromSpec}, IsValueMasked = {IsValueMasked}")]
public sealed class EnvironmentVariableViewModel
{
Expand Down
12 changes: 11 additions & 1 deletion src/Aspire.Dashboard/ResourceService/Partials.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,18 @@ ImmutableArray<VolumeViewModel> GetVolumes()
ImmutableArray<CommandViewModel> GetCommands()
{
return Commands
.Select(c => new CommandViewModel(c.CommandType, c.DisplayName, c.HasDisplayDescription ? c.DisplayDescription : null, c.ConfirmationMessage, c.Parameter, c.IsHighlighted, c.HasIconName ? c.IconName : null))
.Select(c => new CommandViewModel(c.CommandType, Map(c.State), c.DisplayName, c.HasDisplayDescription ? c.DisplayDescription : null, c.ConfirmationMessage, c.Parameter, c.IsHighlighted, c.HasIconName ? c.IconName : null))
.ToImmutableArray();
static CommandViewModelState Map(ResourceCommandState state)
{
return state switch
{
ResourceCommandState.Enabled => CommandViewModelState.Enabled,
ResourceCommandState.Disabled => CommandViewModelState.Disabled,
ResourceCommandState.Hidden => CommandViewModelState.Hidden,
_ => throw new InvalidOperationException("Unknown state: " + state),
};
}
}

T ValidateNotNull<T>(T value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : class
Expand Down
105 changes: 105 additions & 0 deletions src/Aspire.Hosting/ApplicationModel/CommandsConfigurationExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Aspire.Hosting.Dcp;
using Microsoft.Extensions.DependencyInjection;

namespace Aspire.Hosting.ApplicationModel;

internal static class CommandsConfigurationExtensions
{
internal const string StartType = "start";
internal const string StopType = "stop";
internal const string RestartType = "restart";

internal static IResourceBuilder<T> WithLifeCycleCommands<T>(this IResourceBuilder<T> builder) where T : IResource
{
builder.WithCommand(
type: StartType,
displayName: "Start",
executeCommand: async context =>
{
var executor = context.ServiceProvider.GetRequiredService<ApplicationExecutor>();

await executor.StartResourceAsync(context.ResourceName, context.CancellationToken).ConfigureAwait(false);
return CommandResults.Success();
},
updateState: context =>
{
if (IsStarting(context.ResourceSnapshot.State?.Text))
{
return ResourceCommandState.Disabled;
}
else if (IsStopped(context.ResourceSnapshot.State?.Text))
{
return ResourceCommandState.Enabled;
}
else
{
return ResourceCommandState.Hidden;
}
},
iconName: "Play",
isHighlighted: true);

builder.WithCommand(
type: StopType,
displayName: "Stop",
executeCommand: async context =>
{
var executor = context.ServiceProvider.GetRequiredService<ApplicationExecutor>();

await executor.StopResourceAsync(context.ResourceName, context.CancellationToken).ConfigureAwait(false);
return CommandResults.Success();
},
updateState: context =>
{
if (IsWaiting(context.ResourceSnapshot.State?.Text) || IsStopping(context.ResourceSnapshot.State?.Text))
{
return ResourceCommandState.Disabled;
}
else if (!IsStopped(context.ResourceSnapshot.State?.Text) && !IsStarting(context.ResourceSnapshot.State?.Text))
{
return ResourceCommandState.Enabled;
}
else
{
return ResourceCommandState.Hidden;
}
},
iconName: "Stop",
isHighlighted: true);

builder.WithCommand(
type: RestartType,
displayName: "Restart",
executeCommand: async context =>
{
var executor = context.ServiceProvider.GetRequiredService<ApplicationExecutor>();

await executor.StopResourceAsync(context.ResourceName, context.CancellationToken).ConfigureAwait(false);
await executor.StartResourceAsync(context.ResourceName, context.CancellationToken).ConfigureAwait(false);
return CommandResults.Success();
},
updateState: context =>
{
if (IsWaiting(context.ResourceSnapshot.State?.Text) || IsStarting(context.ResourceSnapshot.State?.Text) || IsStopping(context.ResourceSnapshot.State?.Text) || IsStopped(context.ResourceSnapshot.State?.Text))
{
return ResourceCommandState.Disabled;
}
else
{
return ResourceCommandState.Enabled;
}
},
iconName: "ArrowCounterclockwise",
isHighlighted: false);

return builder;

static bool IsStopped(string? state) => state is "Exited" or "Finished" or "FailedToStart";
static bool IsStopping(string? state) => state is "Stopping";
static bool IsStarting(string? state) => state is "Starting";
static bool IsWaiting(string? state) => state is "Waiting";
}
}
34 changes: 34 additions & 0 deletions src/Aspire.Hosting/ApplicationModel/CustomResourceSnapshot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ public sealed record CustomResourceSnapshot
/// The volumes that should show up in the dashboard for this resource.
/// </summary>
public ImmutableArray<VolumeSnapshot> Volumes { get; init; } = [];

/// <summary>
/// The commands available in the dashboard for this resource.
/// </summary>
public ImmutableArray<ResourceCommandSnapshot> Commands { get; init; } = [];
}

/// <summary>
Expand Down Expand Up @@ -105,6 +110,35 @@ public sealed record VolumeSnapshot(string? Source, string Target, string MountT
/// <param name="Value">The value of the property.</param>
public sealed record ResourcePropertySnapshot(string Name, object? Value);

/// <summary>
/// A snapshot of a resource command.
/// </summary>
/// <param name="Type">The type of command. The type uniquely identifies the command.</param>
/// <param name="State">The state of the command.</param>
/// <param name="DisplayName">The display name visible in UI for the command.</param>
/// <param name="IconName">The icon name for the command. The name should be a valid FluentUI icon name. https://aka.ms/fluentui-system-icons</param>
/// <param name="IsHighlighted">A flag indicating whether the command is highlighted in the UI.</param>
public sealed record ResourceCommandSnapshot(string Type, ResourceCommandState State, string DisplayName, string? IconName, bool IsHighlighted);

/// <summary>
/// The state of a resource command.
/// </summary>
public enum ResourceCommandState
{
/// <summary>
/// Command is visible and enabled for use.
/// </summary>
Enabled,
/// <summary>
/// Command is visible and disabled for use.
/// </summary>
Disabled,
/// <summary>
/// Command is hidden.
/// </summary>
Hidden
}

/// <summary>
/// The set of well known resource states.
/// </summary>
Expand Down
Loading