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 GetEnvironmentVariableValuesAsync method to ResourceExtensions #4530

Merged
merged 22 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
dabab87
Add to ResourceExtensions ```GetEnvironmentVariableValuesAsync``` #4464
Alirexaa Jun 15, 2024
0837fd0
Merge branch 'main' into ResourceExtensions
Alirexaa Jun 15, 2024
07b576a
Merge branch 'main' into ResourceExtensions
mitchdenny Jun 24, 2024
1d0a3cc
add example and remarks
Alirexaa Jun 27, 2024
6d4c568
add test
Alirexaa Jun 27, 2024
95fbc40
Update src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs
Alirexaa Jun 27, 2024
8624afa
Update src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs
Alirexaa Jun 27, 2024
de3cb95
Update src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs
Alirexaa Jun 27, 2024
8214b94
add more tests,add suggested code
Alirexaa Jul 3, 2024
ad6b08a
Merge branch 'dotnet:main' into ResourceExtensions
Alirexaa Jul 11, 2024
9cfba74
Merge branch 'main' into ResourceExtensions
mitchdenny Jul 18, 2024
4f91395
Merge branch 'ResourceExtensions' of https://github.com/alirexaa/aspi…
mitchdenny Jul 18, 2024
f1be433
Tweak API based on Eric's feedback.
mitchdenny Jul 18, 2024
c13cb4f
Use a different example.
mitchdenny Jul 18, 2024
28a36e5
Merge remote-tracking branch 'upstream/main' into ResourceExtensions
eerhardt Jul 18, 2024
fedacd2
Update src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs
mitchdenny Jul 18, 2024
c4237c3
Remove password from example.
mitchdenny Jul 18, 2024
80950f7
Indentation fixes.
mitchdenny Jul 18, 2024
6ca31f9
Update tests/Aspire.Hosting.Tests/ResourceExtensionsTests.cs
mitchdenny Jul 21, 2024
94f524c
Update tests/Aspire.Hosting.Tests/ResourceExtensionsTests.cs
mitchdenny Jul 21, 2024
3a0ac4e
PR feedback.
mitchdenny Jul 21, 2024
15b4ba8
Namespace fix.
mitchdenny Jul 21, 2024
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
72 changes: 72 additions & 0 deletions src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,78 @@ public static bool TryGetEnvironmentVariables(this IResource resource, [NotNullW
return TryGetAnnotationsOfType(resource, out environmentVariables);
}

/// <summary>
/// Get the environment variables from the given resource.
/// </summary>
/// <remarks>
/// This method is useful when you want to make sure the environment variables are added properly to resources, mostly in test situations.
/// This method has asynchronous behavior if <paramref name = "applicationOperation" /> be <see cref="DistributedApplicationOperation.Run"/>
/// and environment variables were provided from <see cref="IValueProvider"/> otherwise it will be synchronous.
/// </remarks>
/// <param name="resource">The resource to get the environment variables from.</param>
/// <param name="applicationOperation">The context in which the AppHost is being executed</param>
/// <returns>The environment variables retrieved from the resource.</returns>
Copy link
Member

Choose a reason for hiding this comment

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

Can we get some <remarks> added which cover off where this method is useful and considerations around the sync nature. As well as one or two <example> sections which cover off its usage.

I'm not sure this needs its own conceptual document, but the following could be expanded:

https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/testing

Could you create a docs issue to capture that?

/// <example>
/// <code>
/// using var builder = TestDistributedApplicationBuilder.Create();
///
/// builder.AddMongoDB("mongo")
/// .WithEndpoint("tcp", e => e.AllocatedEndpoint = new AllocatedEndpoint(e, "localhost", 3000, containerHost))
/// .WithMongoExpress();
///
/// var env = await mongoExpress.GetEnvironmentVariableValuesAsync();
///
/// Assert.Collection(env,
/// e =>
/// {
/// Assert.Equal("ME_CONFIG_MONGODB_URL", e.Key);
/// Assert.Equal($"mongodb://{containerHost}:3000/?directConnection=true", e.Value);
/// },
/// e =>
/// {
/// Assert.Equal("ME_CONFIG_BASICAUTH", e.Key);
/// Assert.Equal("false", e.Value);
/// });
/// </code>
/// </example>

public static async ValueTask<IReadOnlyDictionary<string, string>> GetEnvironmentVariableValuesAsync(this IResourceWithEnvironment resource,
DistributedApplicationOperation applicationOperation = DistributedApplicationOperation.Run)
{
var environmentVariables = new Dictionary<string, string>();

if (resource.TryGetEnvironmentVariables(out var callbacks))
{
var config = new Dictionary<string, object>();
var executionContext = new DistributedApplicationExecutionContext(applicationOperation);
var context = new EnvironmentCallbackContext(executionContext, config);

foreach (var callback in callbacks)
{
await callback.Callback(context).ConfigureAwait(false);
}

foreach (var (key, expr) in config)
{
var value = (applicationOperation, expr) switch
{
(_, string s) => s,
(DistributedApplicationOperation.Run, IValueProvider provider) => await provider.GetValueAsync().ConfigureAwait(false),
(DistributedApplicationOperation.Publish, IManifestExpressionProvider provider) => provider.ValueExpression,
(_, null) => null,
_ => throw new InvalidOperationException($"Unsupported expression type: {expr.GetType()}")
};

if (value is not null)
{
environmentVariables[key] = value;
}
}
}

return environmentVariables;
}

/// <summary>
/// Attempts to get the container mounts for the specified resource.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions src/Aspire.Hosting/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#nullable enable
static Aspire.Hosting.ApplicationModel.ResourceExtensions.GetEnvironmentVariableValuesAsync(this Aspire.Hosting.ApplicationModel.IResourceWithEnvironment! resource, Aspire.Hosting.DistributedApplicationOperation applicationOperation = Aspire.Hosting.DistributedApplicationOperation.Run) -> System.Threading.Tasks.ValueTask<System.Collections.Generic.IReadOnlyDictionary<string!, string!>!>
Aspire.Hosting.ApplicationModel.ResourceNotificationService.ResourceNotificationService(Microsoft.Extensions.Logging.ILogger<Aspire.Hosting.ApplicationModel.ResourceNotificationService!>! logger, Microsoft.Extensions.Hosting.IHostApplicationLifetime! hostApplicationLifetime) -> void
Aspire.Hosting.ApplicationModel.ResourceNotificationService.WaitForResourceAsync(string! resourceName, string? targetState = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
Aspire.Hosting.ApplicationModel.ResourceNotificationService.WaitForResourceAsync(string! resourceName, System.Collections.Generic.IEnumerable<string!>! targetStates, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<string!>!
Expand Down
Loading