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

Fix Azure ServiceBus persistent container support #7136

Merged
merged 23 commits into from
Feb 5, 2025
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
3be1e3d
Fix Azure ServiceBus persistent container support
sebastienros Jan 17, 2025
86513bf
Refactor state persistence
sebastienros Jan 18, 2025
1e9de41
Fix tests
sebastienros Jan 22, 2025
97ce49c
PR feedback
sebastienros Jan 23, 2025
ac1e1f5
Fix build
sebastienros Jan 24, 2025
3ebd0da
Merge remote-tracking branch 'origin/main' into sebros/sbpersist
sebastienros Jan 28, 2025
4ffcda7
Test AspireStore
sebastienros Jan 29, 2025
650e3df
Refactor KeyValueStore
sebastienros Jan 29, 2025
d929346
Add tests
sebastienros Jan 29, 2025
fcb23e7
Update src/Aspire.Hosting.Azure.ServiceBus/AzureServiceBusExtensions.cs
sebastienros Jan 29, 2025
d031cd2
Use /obj folder to store files
sebastienros Jan 30, 2025
376fcca
Create ResourcesPreparingEvent
sebastienros Jan 31, 2025
5620c61
Merge remote-tracking branch 'origin/main' into sebros/sbpersist
sebastienros Feb 3, 2025
b8a1025
Remove unused AddPersistentParameter
sebastienros Feb 3, 2025
727f0f0
Only fallback folder on ENV
sebastienros Feb 3, 2025
417c0ff
Fix method documentation
sebastienros Feb 3, 2025
663ee7a
Remove newly added event
sebastienros Feb 4, 2025
33868bc
Merge remote-tracking branch 'origin/main' into sebros/sbpersist
sebastienros Feb 4, 2025
ec769ed
Fix tests
sebastienros Feb 4, 2025
e691cb9
Use temp path for store in functional tests
sebastienros Feb 4, 2025
21808c5
PR feedback
sebastienros Feb 4, 2025
ad785ef
Moving things
sebastienros Feb 4, 2025
1bd23ae
Merge remote-tracking branch 'origin/main' into sebros/sbpersist
sebastienros Feb 4, 2025
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
2 changes: 1 addition & 1 deletion playground/AzureServiceBus/ServiceBus.AppHost/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
serviceBus.RunAsEmulator(configure => configure.ConfigureEmulator(document =>
{
document["UserConfig"]!["Logging"] = new JsonObject { ["Type"] = "Console" };
}));
}).WithLifetime(ContainerLifetime.Persistent));

builder.AddProject<Projects.ServiceBusWorker>("worker")
.WithReference(serviceBus).WaitFor(serviceBus);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,15 @@ namespace Projects%3B
</ItemGroup>
</Target>

<Target Name="EmbedAppHostIntermediateOutputPath" BeforeTargets="GetAssemblyAttributes" Condition=" '$(IsAspireHost)' == 'true' ">
<ItemGroup>
<AssemblyAttribute Include="System.Reflection.AssemblyMetadataAttribute">
<_Parameter1>apphostprojectbaseintermediateoutputpath</_Parameter1>
<_Parameter2>$(BaseIntermediateOutputPath)</_Parameter2>
</AssemblyAttribute>
</ItemGroup>
</Target>

<PropertyGroup>
<AspirePublisher Condition="'$(AspirePublisher)' == ''">manifest</AspirePublisher>
<AspireManifestPublishOutputPath Condition="'$(AspireManifestPublishOutputPath)' == ''">$(_AspireIntermediatePath)</AspireManifestPublishOutputPath>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

<ItemGroup>
<Compile Include="$(RepoRoot)src\Aspire.Hosting\Utils\PasswordGenerator.cs" Link="Utils\PasswordGenerator.cs" />
<Compile Include="$(SharedDir)AspireStore.cs" Link="Utils\AspireStore.cs" />
</ItemGroup>

<ItemGroup>
Expand Down
259 changes: 139 additions & 120 deletions src/Aspire.Hosting.Azure.ServiceBus/AzureServiceBusExtensions.cs

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// 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.Eventing;

namespace Aspire.Hosting.ApplicationModel;

/// <summary>
/// This event is raised by orchestrators before the resources are prepared.
/// </summary>
public class BeforeResourcesPreparedEvent() : IDistributedApplicationEvent
{
}
1 change: 1 addition & 0 deletions src/Aspire.Hosting/Aspire.Hosting.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
<Compile Include="$(SharedDir)LoggingHelpers.cs" Link="Utils\LoggingHelpers.cs" />
<Compile Include="$(SharedDir)StringUtils.cs" Link="Utils\StringUtils.cs" />
<Compile Include="$(SharedDir)SchemaUtils.cs" Link="Utils\SchemaUtils.cs" />
<Compile Include="$(SharedDir)AspireStore.cs" Link="Utils\AspireStore.cs" />
<Compile Include="$(SharedDir)SecretsStore.cs" Link="Utils\SecretsStore.cs" />
<Compile Include="$(SharedDir)ConsoleLogs\LogEntries.cs" Link="Utils\ConsoleLogs\LogEntries.cs" />
<Compile Include="$(SharedDir)ConsoleLogs\LogEntry.cs" Link="Utils\ConsoleLogs\LogEntry.cs" />
Expand Down
2 changes: 2 additions & 0 deletions src/Aspire.Hosting/Dcp/DcpExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,8 @@ public async Task RunApplicationAsync(CancellationToken cancellationToken = defa

try
{
await _executorEvents.PublishAsync(new OnResourcesPreparingContext(cancellationToken)).ConfigureAwait(false);

PrepareServices();
PrepareContainers();
PrepareExecutables();
Expand Down
1 change: 1 addition & 0 deletions src/Aspire.Hosting/Dcp/DcpExecutorEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ namespace Aspire.Hosting.Dcp;
internal record ResourceStatus(string? State, DateTime? StartupTimestamp, DateTime? FinishedTimestamp);
internal record OnEndpointsAllocatedContext(CancellationToken CancellationToken);
internal record OnResourceStartingContext(CancellationToken CancellationToken, string ResourceType, IResource Resource, string? DcpResourceName);
internal record OnResourcesPreparingContext(CancellationToken CancellationToken);
internal record OnResourcesPreparedContext(CancellationToken CancellationToken);
internal record OnResourceChangedContext(CancellationToken CancellationToken, string ResourceType, IResource Resource, string DcpResourceName, ResourceStatus Status, Func<CustomResourceSnapshot, CustomResourceSnapshot> UpdateSnapshot);
internal record OnResourceFailedToStartContext(CancellationToken CancellationToken, string ResourceType, IResource Resource, string? DcpResourceName);
Expand Down
7 changes: 7 additions & 0 deletions src/Aspire.Hosting/Orchestrator/ApplicationOrchestrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public ApplicationOrchestrator(DistributedApplicationModel model,

dcpExecutorEvents.Subscribe<OnEndpointsAllocatedContext>(OnEndpointsAllocated);
dcpExecutorEvents.Subscribe<OnResourceStartingContext>(OnResourceStarting);
dcpExecutorEvents.Subscribe<OnResourcesPreparingContext>(OnResourcesPreparing);
dcpExecutorEvents.Subscribe<OnResourcesPreparedContext>(OnResourcesPrepared);
dcpExecutorEvents.Subscribe<OnResourceChangedContext>(OnResourceChanged);
dcpExecutorEvents.Subscribe<OnResourceFailedToStartContext>(OnResourceFailedToStart);
Expand Down Expand Up @@ -94,6 +95,12 @@ await _notificationService.PublishUpdateAsync(context.Resource, s => s with
await _eventing.PublishAsync(beforeResourceStartedEvent, context.CancellationToken).ConfigureAwait(false);
}

private async Task OnResourcesPreparing(OnResourcesPreparingContext context)
{
var beforeResourcePreparedEvent = new BeforeResourcesPreparedEvent();
await _eventing.PublishAsync(beforeResourcePreparedEvent, context.CancellationToken).ConfigureAwait(false);
}

private async Task OnResourcesPrepared(OnResourcesPreparedContext _)
{
await PublishResourcesWithInitialStateAsync().ConfigureAwait(false);
Expand Down
30 changes: 30 additions & 0 deletions src/Aspire.Hosting/ParameterResourceBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,36 @@ public static IResourceBuilder<ParameterResource> AddParameter(this IDistributed
return builder.AddParameter(name, () => value, publishValueAsDefault, secret);
}

/// <summary>
/// Creates a new <see cref="ParameterResource"/> that has a generated value using the <paramref name="valueGetter"/>.
/// </summary>
/// <remarks>
/// The value will be saved to the app host project's user secrets store when <see cref="DistributedApplicationExecutionContext.IsRunMode"/> is <c>true</c>
/// and the lifetime of the resource is <see cref="ContainerLifetime.Persistent"/>.
/// </remarks>
/// <param name="builder">Distributed application builder</param>
/// <param name="name">Name of the parameter</param>
/// <param name="valueGetter">A callback returning the default value</param>
/// <returns>The created <see cref="ParameterResource"/>.</returns>
public static ParameterResource AddPersistentParameter(this IDistributedApplicationBuilder builder, string name, Func<string> valueGetter)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentNullException.ThrowIfNull(name);
ArgumentNullException.ThrowIfNull(valueGetter);

var parameterResource = new ParameterResource(name, defaultValue => GetParameterValue(builder.Configuration, name, defaultValue), true)
{
Default = new ConstantParameterDefault(valueGetter)
};

if (builder.ExecutionContext.IsRunMode && builder.AppHostAssembly is not null)
{
parameterResource.Default = new UserSecretsParameterDefault(builder.AppHostAssembly, builder.Environment.ApplicationName, name, parameterResource.Default);
}

return parameterResource;
}

/// <summary>
/// Adds a parameter resource to the application with a value coming from a callback function.
/// </summary>
Expand Down
3 changes: 3 additions & 0 deletions src/Aspire.Hosting/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
#nullable enable
Aspire.Hosting.ApplicationModel.BeforeResourcesPreparedEvent
Aspire.Hosting.ApplicationModel.BeforeResourcesPreparedEvent.BeforeResourcesPreparedEvent() -> void
Aspire.Hosting.ApplicationModel.ContainerLifetime.Session = 0 -> Aspire.Hosting.ApplicationModel.ContainerLifetime
Aspire.Hosting.ApplicationModel.CustomResourceSnapshot.HealthStatus.get -> Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus?
Aspire.Hosting.ApplicationModel.CustomResourceSnapshot.Relationships.get -> System.Collections.Immutable.ImmutableArray<Aspire.Hosting.ApplicationModel.RelationshipSnapshot!>
Expand Down Expand Up @@ -256,6 +258,7 @@ static Aspire.Hosting.ParameterResourceBuilderExtensions.AddParameter(this Aspir
static Aspire.Hosting.ParameterResourceBuilderExtensions.AddParameter(this Aspire.Hosting.IDistributedApplicationBuilder! builder, string! name, string! value, bool publishValueAsDefault = false, bool secret = false) -> Aspire.Hosting.ApplicationModel.IResourceBuilder<Aspire.Hosting.ApplicationModel.ParameterResource!>!
static Aspire.Hosting.ParameterResourceBuilderExtensions.AddParameter(this Aspire.Hosting.IDistributedApplicationBuilder! builder, string! name, System.Func<string!>! valueGetter, bool publishValueAsDefault = false, bool secret = false) -> Aspire.Hosting.ApplicationModel.IResourceBuilder<Aspire.Hosting.ApplicationModel.ParameterResource!>!
static Aspire.Hosting.ParameterResourceBuilderExtensions.AddParameterFromConfiguration(this Aspire.Hosting.IDistributedApplicationBuilder! builder, string! name, string! configurationKey, bool secret = false) -> Aspire.Hosting.ApplicationModel.IResourceBuilder<Aspire.Hosting.ApplicationModel.ParameterResource!>!
static Aspire.Hosting.ParameterResourceBuilderExtensions.AddPersistentParameter(this Aspire.Hosting.IDistributedApplicationBuilder! builder, string! name, System.Func<string!>! valueGetter) -> Aspire.Hosting.ApplicationModel.ParameterResource!
static Aspire.Hosting.ProjectResourceBuilderExtensions.PublishAsDockerFile<T>(this Aspire.Hosting.ApplicationModel.IResourceBuilder<T!>! builder, System.Action<Aspire.Hosting.ApplicationModel.IResourceBuilder<Aspire.Hosting.ApplicationModel.ContainerResource!>!>? configure = null) -> Aspire.Hosting.ApplicationModel.IResourceBuilder<T!>!
static Aspire.Hosting.ProjectResourceBuilderExtensions.WithEndpointsInEnvironment(this Aspire.Hosting.ApplicationModel.IResourceBuilder<Aspire.Hosting.ApplicationModel.ProjectResource!>! builder, System.Func<Aspire.Hosting.ApplicationModel.EndpointAnnotation!, bool>! filter) -> Aspire.Hosting.ApplicationModel.IResourceBuilder<Aspire.Hosting.ApplicationModel.ProjectResource!>!
Aspire.Hosting.DistributedApplicationExecutionContext.DistributedApplicationExecutionContext(Aspire.Hosting.DistributedApplicationExecutionContextOptions! options) -> void
Expand Down
225 changes: 225 additions & 0 deletions src/Shared/AspireStore.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;
using System.Reflection;
using System.Security.Cryptography;

namespace Aspire.Hosting.Utils;

internal sealed class AspireStore
{
internal const string AspireStoreDir = "ASPIRE_STORE_DIR";

private readonly string _basePath;
private static readonly SearchValues<char> s_invalidFileNameChars = SearchValues.Create(Path.GetInvalidFileNameChars());

private AspireStore(string basePath)
{
ArgumentNullException.ThrowIfNull(basePath);

_basePath = basePath;
EnsureDirectory();
}

internal string BasePath => _basePath;

/// <summary>
/// Creates a new instance of <see cref="AspireStore"/> using the provided <paramref name="builder"/>.
/// </summary>
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/>.</param>
/// <returns>A new instance of <see cref="AspireStore"/>.</returns>
/// <remarks>
/// The store is created in the following locations:
/// - On Windows: %APPDATA%\Aspire\{applicationHash}\aspire.json
/// - On Mac/Linux: ~/.aspire/{applicationHash}\aspire.json
/// - If none of the above locations are available, the store is created in the directory specified by the ASPIRE_STORE_FALLBACK_DIR environment variable.
/// - If the ASPIRE_STORE_FALLBACK_DIR environment variable is not set, an <see cref="InvalidOperationException"/> is thrown.
///
/// The directory has the permissions set to 700 on Unix systems.
/// </remarks>
public static AspireStore Create(IDistributedApplicationBuilder builder)
{
ArgumentNullException.ThrowIfNull(builder);

var assemblyMetadata = builder.AppHostAssembly?.GetCustomAttributes<AssemblyMetadataAttribute>();
var objDir = GetMetadataValue(assemblyMetadata, "AppHostProjectBaseIntermediateOutputPath");

var fallbackDir = Environment.GetEnvironmentVariable(AspireStoreDir);
var root = fallbackDir
?? objDir
?? Environment.GetEnvironmentVariable("APPDATA") // On Windows it goes to %APPDATA%\Microsoft\UserSecrets\
?? Environment.GetEnvironmentVariable("HOME") // On Mac/Linux it goes to ~/.microsoft/usersecrets/
?? Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

if (string.IsNullOrEmpty(root))
{
throw new InvalidOperationException($"Could not determine an appropriate location for storing user secrets. Set the {AspireStoreDir} environment variable to a folder where the App Host content should be stored.");
}

var directoryPath = Path.Combine(root, ".aspire");

// The /obj directory doesn't need to be prefixed with the app host name.
if (root != objDir)
{
directoryPath = Path.Combine(directoryPath, GetAppHostSpecificPrefix(builder));
}

return new AspireStore(directoryPath);
}

private static string? GetMetadataValue(IEnumerable<AssemblyMetadataAttribute>? assemblyMetadata, string key) =>
assemblyMetadata?.FirstOrDefault(a => string.Equals(a.Key, key, StringComparison.OrdinalIgnoreCase))?.Value;

private static string GetAppHostSpecificPrefix(IDistributedApplicationBuilder builder)
{
var appName = Sanitize(builder.Environment.ApplicationName).ToLowerInvariant();
var appNameHash = builder.Configuration["AppHost:Sha256"]![..10].ToLowerInvariant();
return $"{appName}.{appNameHash}";
}

/// <summary>
/// Gets a deterministic file path that is a copy of the <paramref name="sourceFilename"/>.
/// The resulting file name will depend on the content of the file.
/// </summary>
/// <param name="filename">A file name the to base the result on.</param>
/// <param name="sourceFilename">An existing file.</param>
/// <returns>A deterministic file path with the same content as <paramref name="sourceFilename"/>.</returns>
public string GetFileNameWithContent(string filename, string sourceFilename)
{
ArgumentNullException.ThrowIfNullOrWhiteSpace(filename);
ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename);

if (!File.Exists(sourceFilename))
{
throw new FileNotFoundException("The source file '{0}' does not exist.", sourceFilename);
}

EnsureDirectory();

// Strip any folder information from the filename.
filename = Path.GetFileName(filename);

// Delete existing file versions with the same name.
var allFiles = Directory.EnumerateFiles(_basePath, filename + ".*");

foreach (var file in allFiles)
{
try
{
File.Delete(file);
}
catch
{
}
}

var hashStream = File.OpenRead(sourceFilename);

// Compute the hash of the content.
var hash = SHA256.HashData(hashStream);

hashStream.Dispose();

var name = Path.GetFileNameWithoutExtension(filename);
var ext = Path.GetExtension(filename);
var finalFilePath = Path.Combine(_basePath, $"{name}.{Convert.ToHexString(hash)[..12].ToLowerInvariant()}{ext}".ToLowerInvariant());

if (!File.Exists(finalFilePath))
{
File.Copy(sourceFilename, finalFilePath, overwrite: true);
}

return finalFilePath;
}

public string GetFileNameWithContent(string filename, Stream contentStream)
{
ArgumentNullException.ThrowIfNullOrWhiteSpace(filename);
ArgumentNullException.ThrowIfNull(contentStream);

// Create a temporary file to write the content to.
var tempFileName = Path.GetTempFileName();

// Write the content to the temporary file.
using (var fileStream = File.OpenWrite(tempFileName))
{
contentStream.CopyTo(fileStream);
}

var finalFilePath = GetFileNameWithContent(filename, tempFileName);

File.Delete(tempFileName);

return finalFilePath;
}

/// <summary>
/// Creates a file with the provided <paramref name="filename"/> in the store.
/// </summary>
/// <param name="filename">The file name to use in the store.</param>
/// <returns>The absolute file name in the store.</returns>
public string GetFileName(string filename)
{
EnsureDirectory();

// Strip any folder information from the filename.
filename = Path.GetFileName(filename);

return Path.Combine(_basePath, filename);
}

public void DeleteFile(string filename)
{
// Strip any folder information from the filename.
filename = Path.GetFileName(filename);

var finalFilePath = Path.Combine(_basePath, filename);

if (File.Exists(finalFilePath))
{
File.Delete(finalFilePath);
}
}

public void DeleteStore()
{
if (Directory.Exists(_basePath))
{
Directory.Delete(_basePath, recursive: true);
}
}

/// <summary>
/// Removes any unwanted characters from the <paramref name="filename"/>.
/// </summary>
internal static string Sanitize(string filename)
{
return string.Create(filename.Length, filename, static (s, name) =>
{
name.CopyTo(s);

while (s.IndexOfAny(s_invalidFileNameChars) is var i and not -1)
{
s[i] = '_';
}
});
}

private void EnsureDirectory()
{
if (!string.IsNullOrEmpty(_basePath) && !Directory.Exists(_basePath))
{
if (!OperatingSystem.IsWindows())
{
var tempDir = Directory.CreateTempSubdirectory();
tempDir.MoveTo(_basePath);
}
else
{
Directory.CreateDirectory(_basePath);
}
}
}
}
1 change: 0 additions & 1 deletion src/Shared/SecretsStore.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json.Nodes;
using Microsoft.Extensions.Configuration;
Expand Down
Loading
Loading