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
16 changes: 15 additions & 1 deletion src/Aspire.Hosting/ApplicationModel/ParameterResource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,5 +74,19 @@ internal string ConfigurationKey
set => _configurationKey = value;
}

ValueTask<string?> IValueProvider.GetValueAsync(CancellationToken cancellationToken) => new(Value);
/// <summary>
/// A task completion source that can be used to wait for the value of the parameter to be set.
/// </summary>
internal TaskCompletionSource<string>? WaitForValueTcs { get; set; }

async ValueTask<string?> IValueProvider.GetValueAsync(CancellationToken cancellationToken)
{
if (WaitForValueTcs is not null)
{
// Wait for the value to be set if the task completion source is available.
return await WaitForValueTcs.Task.WaitAsync(cancellationToken).ConfigureAwait(false);
}

return Value;
}
}
1 change: 1 addition & 0 deletions src/Aspire.Hosting/DistributedApplicationBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,7 @@ public DistributedApplicationBuilder(DistributedApplicationOptions options)

// Orchestrator
_innerBuilder.Services.AddSingleton<ApplicationOrchestrator>();
_innerBuilder.Services.AddSingleton<ParameterProcessor>();
_innerBuilder.Services.AddHostedService<OrchestratorHostService>();

// DCP stuff
Expand Down
36 changes: 36 additions & 0 deletions src/Aspire.Hosting/MissingParameterValueException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Aspire.Hosting;

/// <summary>
/// The exception that is thrown when a parameter resource cannot be initialized because its value is missing or cannot be resolved.
/// </summary>
/// <remarks>
/// This exception is typically thrown when:
/// <list type="bullet">
/// <item><description>A parameter value is not provided in configuration and has no default value</description></item>
/// <item><description>A parameter's value callback throws an exception during execution</description></item>
/// <item><description>A parameter's value cannot be retrieved from the configured source (e.g., user secrets, environment variables)</description></item>
/// </list>
/// </remarks>
public class MissingParameterValueException : DistributedApplicationException
{
/// <summary>
/// Initializes a new instance of the <see cref="MissingParameterValueException"/> class with a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public MissingParameterValueException(string message) : base(message)
{
}

/// <summary>
/// Initializes a new instance of the <see cref="MissingParameterValueException"/> class with a specified error message
/// and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param>
public MissingParameterValueException(string message, Exception innerException) : base(message, innerException)
{
}
}
52 changes: 12 additions & 40 deletions src/Aspire.Hosting/Orchestrator/ApplicationOrchestrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ internal sealed class ApplicationOrchestrator
private readonly IDistributedApplicationEventing _eventing;
private readonly IServiceProvider _serviceProvider;
private readonly DistributedApplicationExecutionContext _executionContext;
private readonly ParameterProcessor _parameterProcessor;
private readonly CancellationTokenSource _shutdownCancellation = new();

public ApplicationOrchestrator(DistributedApplicationModel model,
Expand All @@ -34,7 +35,8 @@ public ApplicationOrchestrator(DistributedApplicationModel model,
ResourceLoggerService loggerService,
IDistributedApplicationEventing eventing,
IServiceProvider serviceProvider,
DistributedApplicationExecutionContext executionContext)
DistributedApplicationExecutionContext executionContext,
ParameterProcessor parameterProcessor)
{
_dcpExecutor = dcpExecutor;
_model = model;
Expand All @@ -45,6 +47,7 @@ public ApplicationOrchestrator(DistributedApplicationModel model,
_eventing = eventing;
_serviceProvider = serviceProvider;
_executionContext = executionContext;
_parameterProcessor = parameterProcessor;

dcpExecutorEvents.Subscribe<OnResourcesPreparedContext>(OnResourcesPrepared);
dcpExecutorEvents.Subscribe<OnResourceChangedContext>(OnResourceChanged);
Expand Down Expand Up @@ -269,51 +272,15 @@ private async Task OnResourceEndpointsAllocated(ResourceEndpointsAllocatedEvent
await PublishResourceEndpointUrls(@event.Resource, cancellationToken).ConfigureAwait(false);
}

private async Task OnResourceInitialized(InitializeResourceEvent @event, CancellationToken cancellationToken)
private Task OnResourceInitialized(InitializeResourceEvent @event, CancellationToken cancellationToken)
{
var resource = @event.Resource;

if (resource is ParameterResource parameterResource)
{
await InitializeParameter(parameterResource).ConfigureAwait(false);
}
else if (resource is ConnectionStringResource connectionStringResource)
if (resource is ConnectionStringResource connectionStringResource)
{
InitializeConnectionString(connectionStringResource);
}

async Task InitializeParameter(ParameterResource parameterResource)
{
try
{
await _notificationService.PublishUpdateAsync(parameterResource, s =>
{
return s with
{
Properties = s.Properties.SetResourceProperty(KnownProperties.Parameter.Value, parameterResource.Value ?? "", parameterResource.Secret),
State = new(KnownResourceStates.Active, KnownResourceStateStyles.Info)
};
})
.ConfigureAwait(false);
}
catch (Exception ex)
{
await _notificationService.PublishUpdateAsync(parameterResource, s =>
{
return s with
{
State = new("Value missing", KnownResourceStateStyles.Error),
Properties = s.Properties.SetResourceProperty(KnownProperties.Parameter.Value, ex.Message),
IsHidden = false
};
})
.ConfigureAwait(false);

_loggerService.GetLogger(parameterResource)
.LogError(ex, "Failed to initialize parameter resource {ResourceName}", parameterResource.Name);
}
}

void InitializeConnectionString(ConnectionStringResource connectionStringResource)
{
var logger = _loggerService.GetLogger(resource);
Expand Down Expand Up @@ -349,7 +316,7 @@ void InitializeConnectionString(ConnectionStringResource connectionStringResourc
tcs.SetResult();
return Task.CompletedTask;
});

waitFor.Add(tcs.Task.WaitAsync(cancellationToken));
}
}
Expand All @@ -364,6 +331,8 @@ await _notificationService.PublishUpdateAsync(connectionStringResource, s => s w
}).ConfigureAwait(false);
}, cancellationToken);
}

return Task.CompletedTask;
}

private async Task OnResourceChanged(OnResourceChangedContext context)
Expand Down Expand Up @@ -467,6 +436,9 @@ await SetChildResourceAsync(child, state, startTimeStamp, stopTimeStamp)

private async Task PublishResourcesInitialStateAsync(CancellationToken cancellationToken)
{
// Initialize all parameter resources up front
await _parameterProcessor.InitializeParametersAsync(_model.Resources.OfType<ParameterResource>()).ConfigureAwait(false);

// Publish the initial state of the resources that have a snapshot annotation.
foreach (var resource in _model.Resources)
{
Expand Down
199 changes: 199 additions & 0 deletions src/Aspire.Hosting/Orchestrator/ParameterProcessor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
#pragma warning disable ASPIREINTERACTION001

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Aspire.Dashboard.Model;
using Aspire.Hosting.ApplicationModel;
using Microsoft.Extensions.Logging;

namespace Aspire.Hosting.Orchestrator;

/// <summary>
/// Handles processing of parameter resources during application orchestration.
/// </summary>
internal sealed class ParameterProcessor(
ResourceNotificationService notificationService,
ResourceLoggerService loggerService,
IInteractionService interactionService,
ILogger<ParameterProcessor> logger)
{
private readonly List<ParameterResource> _unresolvedParameters = [];

public async Task InitializeParametersAsync(IEnumerable<ParameterResource> parameterResources)
Copy link
Member

Choose a reason for hiding this comment

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

Should this take a cancellation token?

{
// Initialize all parameter resources by setting their WaitForValueTcs.
// This allows them to be processed asynchronously later.
foreach (var parameterResource in parameterResources)
{
parameterResource.WaitForValueTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);

await ProcessParameterAsync(parameterResource).ConfigureAwait(false);
}

// If interaction service is available, we can handle unresolved parameters.
// This will allow the user to provide values for parameters that could not be initialized.
if (interactionService.IsAvailable)
{
// All parameters have been processed, we can now handle unresolved parameters if any.
if (_unresolvedParameters.Count > 0)
{
// Start the loop that will allow the user to specify values for unresolved parameters.
_ = Task.Run(async () =>
{
try
{
await HandleUnresolvedParametersAsync().ConfigureAwait(false);

logger.LogDebug("All unresolved parameters have been handled successfully.");
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to handle unresolved parameters.");
}
});
}
}
}

private async Task ProcessParameterAsync(ParameterResource parameterResource)
{
try
{
var value = parameterResource.Value ?? "";

await notificationService.PublishUpdateAsync(parameterResource, s =>
{
return s with
{
Properties = s.Properties.SetResourceProperty(KnownProperties.Parameter.Value, value, parameterResource.Secret),
State = new(KnownResourceStates.Active, KnownResourceStateStyles.Success)
};
})
.ConfigureAwait(false);

parameterResource.WaitForValueTcs?.TrySetResult(value);
}
catch (Exception ex)
{
// Missing parameter values throw a MissingParameterValueException.
if (interactionService.IsAvailable && ex is MissingParameterValueException)
{
// If interaction service is available, we can prompt the user to provide a value.
// Add the parameter to unresolved parameters list.
_unresolvedParameters.Add(parameterResource);

loggerService.GetLogger(parameterResource)
.LogWarning(ex, "Parameter resource {ResourceName} could not be initialized. Waiting for user input.", parameterResource.Name);
}
else
{
// If interaction service is not available, we log the error and set the state to error.
parameterResource.WaitForValueTcs?.TrySetException(ex);

loggerService.GetLogger(parameterResource)
.LogError(ex, "Failed to initialize parameter resource {ResourceName}.", parameterResource.Name);
}

var stateText = ex is MissingParameterValueException ?
"Value missing" :
"Error initializing parameter";

await notificationService.PublishUpdateAsync(parameterResource, s =>
{
return s with
{
State = new(stateText, KnownResourceStateStyles.Error),
Properties = s.Properties.SetResourceProperty(KnownProperties.Parameter.Value, ex.Message),
IsHidden = false
};
})
.ConfigureAwait(false);
}
}

// Internal for testing purposes.
private async Task HandleUnresolvedParametersAsync()
{
await HandleUnresolvedParametersAsync(_unresolvedParameters).ConfigureAwait(false);
}

// Internal for testing purposes - allows passing specific parameters to test.
internal async Task HandleUnresolvedParametersAsync(IList<ParameterResource> unresolvedParameters)
{
// This method will continue in a loop until all unresolved parameters are resolved.
while (unresolvedParameters.Count > 0)
{
// First we show a notification that there are unresolved parameters.
var result = await interactionService.PromptMessageBarAsync(
"Unresolved parameters",
"There are unresolved parameters that need to be set. Please provide values for them.",
new MessageBarInteractionOptions
{
Intent = MessageIntent.Warning,
PrimaryButtonText = "Enter values"
})
.ConfigureAwait(false);

if (result.Data)
{
// Now we build up a new form base on the unresolved parameters.
var inputs = new List<InteractionInput>();

foreach (var parameter in unresolvedParameters)
{
// Create an input for each unresolved parameter.
inputs.Add(new InteractionInput
{
InputType = parameter.Secret ? InputType.SecretText : InputType.Text,
Label = parameter.Name,
Placeholder = "Enter value for " + parameter.Name,
});
}

var valuesPrompt = await interactionService.PromptInputsAsync(
"Set unresolved parameters",
"Please provide values for the unresolved parameters.",
inputs,
new InputsDialogInteractionOptions
{
PrimaryButtonText = "Save",
ShowDismiss = true
})
.ConfigureAwait(false);

if (!valuesPrompt.Canceled)
{
// Iterate through the unresolved parameters and set their values based on user input.
for (var i = unresolvedParameters.Count - 1; i >= 0; i--)
{
var parameter = unresolvedParameters[i];
var inputValue = valuesPrompt.Data[i].Value;

if (string.IsNullOrEmpty(inputValue))
{
// If the input value is null, we skip this parameter.
continue;
}

parameter.WaitForValueTcs?.TrySetResult(inputValue);

// Update the parameter resource state to active with the provided value.
await notificationService.PublishUpdateAsync(parameter, s =>
{
return s with
{
Properties = s.Properties.SetResourceProperty(KnownProperties.Parameter.Value, inputValue, parameter.Secret),
State = new(KnownResourceStates.Active, KnownResourceStateStyles.Success)
};
})
.ConfigureAwait(false);

// Remove the parameter from unresolved parameters list.
unresolvedParameters.RemoveAt(i);
}
}
}
}
}
}
4 changes: 2 additions & 2 deletions src/Aspire.Hosting/ParameterResourceBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ private static string GetParameterValue(ConfigurationManager configuration, stri
configurationKey ??= $"Parameters:{name}";
return configuration[configurationKey]
?? parameterDefault?.GetDefaultValue()
?? throw new DistributedApplicationException($"Parameter resource could not be used because configuration key '{configurationKey}' is missing and the Parameter has no default value.");
?? throw new MissingParameterValueException($"Parameter resource could not be used because configuration key '{configurationKey}' is missing and the Parameter has no default value.");
}

internal static IResourceBuilder<T> AddParameter<T>(this IDistributedApplicationBuilder builder, T resource)
Expand Down Expand Up @@ -191,7 +191,7 @@ public static IResourceBuilder<IResourceWithConnectionString> AddConnectionStrin
new ConnectionStringParameterResource(
name,
_ => builder.Configuration.GetConnectionString(name) ??
throw new DistributedApplicationException($"Connection string parameter resource could not be used because connection string '{name}' is missing."),
throw new MissingParameterValueException($"Connection string parameter resource could not be used because connection string '{name}' is missing."),
environmentVariableName)
);
}
Expand Down
Loading
Loading