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 Aspire.MySqlConnector #825

Merged
merged 14 commits into from Nov 18, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions Aspire.sln
Expand Up @@ -152,6 +152,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Aspire.RabbitMQ.Client", "s
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Aspire.RabbitMQ.Client.Tests", "tests\Aspire.RabbitMQ.Client.Tests\Aspire.RabbitMQ.Client.Tests.csproj", "{165411FE-755E-4869-A756-F87F455860AC}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Aspire.MySqlConnector", "src\Components\Aspire.MySqlConnector\Aspire.MySqlConnector.csproj", "{CA283D7F-EB95-4353-B196-C409965D2B42}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Aspire.MySqlConnector.Tests", "tests\Aspire.MySqlConnector.Tests\Aspire.MySqlConnector.Tests.csproj", "{C8079F06-304F-49B1-A0C1-45AA3782A923}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -406,6 +410,14 @@ Global
{165411FE-755E-4869-A756-F87F455860AC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{165411FE-755E-4869-A756-F87F455860AC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{165411FE-755E-4869-A756-F87F455860AC}.Release|Any CPU.Build.0 = Release|Any CPU
{CA283D7F-EB95-4353-B196-C409965D2B42}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CA283D7F-EB95-4353-B196-C409965D2B42}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CA283D7F-EB95-4353-B196-C409965D2B42}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CA283D7F-EB95-4353-B196-C409965D2B42}.Release|Any CPU.Build.0 = Release|Any CPU
{C8079F06-304F-49B1-A0C1-45AA3782A923}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C8079F06-304F-49B1-A0C1-45AA3782A923}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C8079F06-304F-49B1-A0C1-45AA3782A923}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C8079F06-304F-49B1-A0C1-45AA3782A923}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -477,6 +489,8 @@ Global
{A84C4EE3-2601-4804-BCDC-E9948E164A22} = {A68BA1A5-1604-433D-9778-DC0199831C2A}
{4D8A92AB-4E77-4965-AD8E-8E206DCE66A4} = {27381127-6C45-4B4C-8F18-41FF48DFE4B2}
{165411FE-755E-4869-A756-F87F455860AC} = {4981B3A5-4AFD-4191-BF7D-8692D9783D60}
{CA283D7F-EB95-4353-B196-C409965D2B42} = {27381127-6C45-4B4C-8F18-41FF48DFE4B2}
{C8079F06-304F-49B1-A0C1-45AA3782A923} = {4981B3A5-4AFD-4191-BF7D-8692D9783D60}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6DCEDFEC-988E-4CB3-B45B-191EB5086E0C}
Expand Down
2 changes: 2 additions & 0 deletions Directory.Packages.props
Expand Up @@ -35,6 +35,7 @@
<PackageVersion Include="AspNetCore.HealthChecks.Azure.Storage.Blobs" Version="7.0.0" />
<PackageVersion Include="AspNetCore.HealthChecks.Azure.Storage.Queues" Version="7.0.0" />
<PackageVersion Include="AspNetCore.HealthChecks.AzureServiceBus" Version="7.0.0" />
<PackageVersion Include="AspNetCore.HealthChecks.MySql" Version="7.0.0" />
<PackageVersion Include="AspNetCore.HealthChecks.NpgSql" Version="7.1.0" />
<PackageVersion Include="AspNetCore.HealthChecks.Rabbitmq" Version="7.0.0" />
<PackageVersion Include="AspNetCore.HealthChecks.Redis" Version="7.0.1" />
Expand Down Expand Up @@ -70,6 +71,7 @@
<PackageVersion Include="JsonSchema.Net" Version="5.3.1" />
<PackageVersion Include="Microsoft.FluentUI.AspNetCore.Components" Version="4.0.0" />
<PackageVersion Include="Microsoft.FluentUI.AspNetCore.Components.Icons" Version="4.0.0" />
<PackageVersion Include="MySqlConnector.DependencyInjection" Version="2.3.1" />
<PackageVersion Include="Npgsql.DependencyInjection" Version="8.0.0-rc.2" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0-rc.2" />
<PackageVersion Include="Polly" Version="8.2.0" />
Expand Down
11 changes: 11 additions & 0 deletions src/Aspire.Hosting/MySql/IMySqlResource.cs
@@ -0,0 +1,11 @@
// 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.ApplicationModel;

/// <summary>
/// Represents a MySQL resource that requires a connection string.
/// </summary>
public interface IMySqlResource : IResourceWithConnectionString
{
}
81 changes: 81 additions & 0 deletions src/Aspire.Hosting/MySql/MySqlBuilderExtensions.cs
@@ -0,0 +1,81 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Net.Sockets;
using System.Text.Json;
using Aspire.Hosting.ApplicationModel;

namespace Aspire.Hosting;

/// <summary>
/// Provides extension methods for adding MySQL resources to an <see cref="IDistributedApplicationBuilder"/>.
/// </summary>
public static class MySqlBuilderExtensions
{
private const string PasswordEnvVarName = "MYSQL_ROOT_PASSWORD";

/// <summary>
/// Adds a MySQL container to the application model. The default image is "mysql" and the tag is "latest".
/// </summary>
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/>.</param>
/// <param name="name">The name of the resource. This name will be used as the connection string name when referenced in a dependency.</param>
/// <param name="port">The host port for MySQL.</param>
/// <param name="password">The password for the MySQL root user. Defaults to a random password.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{MySqlContainerResource}"/>.</returns>
public static IResourceBuilder<MySqlContainerResource> AddMySqlContainer(this IDistributedApplicationBuilder builder, string name, int? port = null, string? password = null)
{
password ??= Guid.NewGuid().ToString("N");
var mySqlContainer = new MySqlContainerResource(name, password);
return builder.AddResource(mySqlContainer)
.WithAnnotation(new ManifestPublishingCallbackAnnotation(WriteMySqlContainerToManifest))
.WithAnnotation(new ServiceBindingAnnotation(ProtocolType.Tcp, port: port, containerPort: 3306)) // Internal port is always 3306.
.WithAnnotation(new ContainerImageAnnotation { Image = "mysql", Tag = "latest" })
.WithEnvironment(PasswordEnvVarName, () => mySqlContainer.Password);
}

/// <summary>
/// Adds a MySQL connection to the application model. Connection strings can also be read from the connection string section of the configuration using the name of the resource.
/// </summary>
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/>.</param>
/// <param name="name">The name of the resource. This name will be used as the connection string name when referenced in a dependency.</param>
/// <param name="connectionString">The MySQL connection string (optional).</param>
/// <returns>A reference to the <see cref="IResourceBuilder{MySqlConnectionResource}"/>.</returns>
public static IResourceBuilder<MySqlConnectionResource> AddMySqlConnection(this IDistributedApplicationBuilder builder, string name, string? connectionString = null)
{
var mySqlConnection = new MySqlConnectionResource(name, connectionString);

return builder.AddResource(mySqlConnection)
.WithAnnotation(new ManifestPublishingCallbackAnnotation((json) => WriteMySqlConnectionToManifest(json, mySqlConnection)));
}

/// <summary>
/// Adds a MySQL database to the application model.
/// </summary>
/// <param name="builder">The MySQL server resource builder.</param>
/// <param name="name">The name of the resource. This name will be used as the connection string name when referenced in a dependency.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{MySqlDatabaseResource}"/>.</returns>
public static IResourceBuilder<MySqlDatabaseResource> AddDatabase(this IResourceBuilder<MySqlContainerResource> builder, string name)
{
var mySqlDatabase = new MySqlDatabaseResource(name, builder.Resource);
return builder.ApplicationBuilder.AddResource(mySqlDatabase)
.WithAnnotation(new ManifestPublishingCallbackAnnotation(
(json) => WriteMySqlDatabaseToManifest(json, mySqlDatabase)));
}

private static void WriteMySqlConnectionToManifest(Utf8JsonWriter jsonWriter, MySqlConnectionResource mySqlConnection)
{
jsonWriter.WriteString("type", "mysql.connection.v0");
jsonWriter.WriteString("connectionString", mySqlConnection.GetConnectionString());
}

private static void WriteMySqlContainerToManifest(Utf8JsonWriter jsonWriter)
{
jsonWriter.WriteString("type", "mysql.server.v0");
}

private static void WriteMySqlDatabaseToManifest(Utf8JsonWriter json, MySqlDatabaseResource mySqlDatabase)
{
json.WriteString("type", "mysql.database.v0");
json.WriteString("parent", mySqlDatabase.Parent.Name);
}
}
20 changes: 20 additions & 0 deletions src/Aspire.Hosting/MySql/MySqlConnectionResource.cs
@@ -0,0 +1,20 @@
// 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.ApplicationModel;

/// <summary>
/// A resource that represents a MySQL connection.
/// </summary>
/// <param name="name">The name of the resource.</param>
/// <param name="connectionString">The MySQL connection string.</param>
public class MySqlConnectionResource(string name, string? connectionString) : Resource(name), IMySqlResource
{
private readonly string? _connectionString = connectionString;

/// <summary>
/// Gets the connection string for the MySQL server.
/// </summary>
/// <returns>The specified connection string.</returns>
public string? GetConnectionString() => _connectionString;
}
31 changes: 31 additions & 0 deletions src/Aspire.Hosting/MySql/MySqlContainerResource.cs
@@ -0,0 +1,31 @@
// 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.ApplicationModel;

/// <summary>
/// A resource that represents a MySQL container.
/// </summary>
/// <param name="name">The name of the resource.</param>
/// <param name="password">The MySQL server root password.</param>
public class MySqlContainerResource(string name, string password) : ContainerResource(name), IMySqlResource
{
public string Password { get; } = password;

/// <summary>
/// Gets the connection string for the MySQL server.
/// </summary>
/// <returns>A connection string for the MySQL server in the form "Server=host;Port=port;User ID=root;Password=password".</returns>
public string? GetConnectionString()
{
if (!this.TryGetAllocatedEndPoints(out var allocatedEndpoints))
{
throw new DistributedApplicationException("Expected allocated endpoints!");
}

var allocatedEndpoint = allocatedEndpoints.Single(); // We should only have one endpoint for MySQL.

var connectionString = $"Server={allocatedEndpoint.Address};Port={allocatedEndpoint.Port};User ID=root;Password={Password};";
return connectionString;
}
}
30 changes: 30 additions & 0 deletions src/Aspire.Hosting/MySql/MySqlDatabaseResource.cs
@@ -0,0 +1,30 @@
// 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.ApplicationModel;

/// <summary>
/// A resource that represents a MySQL database. This is a child resource of a <see cref="MySqlContainerResource"/>.
/// </summary>
/// <param name="name">The name of the resource.</param>
/// <param name="mySqlContainer">The MySQL server resource associated with this database.</param>
public class MySqlDatabaseResource(string name, MySqlContainerResource mySqlContainer) : Resource(name), IMySqlResource, IResourceWithParent<MySqlContainerResource>
{
public MySqlContainerResource Parent { get; } = mySqlContainer;

/// <summary>
/// Gets the connection string for the MySQL database.
/// </summary>
/// <returns>A connection string for the MySQL database.</returns>
public string? GetConnectionString()
{
if (Parent.GetConnectionString() is { } connectionString)
{
return $"{connectionString}Database={Name}";
}
else
{
throw new DistributedApplicationException("Parent resource connection string was null.");
Copy link
Member

Choose a reason for hiding this comment

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

@eerhardt should we start moving these things to a resx? I assume we won't localize unless the base libraries start to localize. So perhaps there isn't much value.

Copy link
Member

Choose a reason for hiding this comment

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

ASP.NET Core doesn't have a lot of its exception messages in resx's either. For example

https://github.com/dotnet/aspnetcore/blob/f8f03ea3764826d009f7ceb9bb91e482ce4a3fa9/src/Shared/Json/JsonSerializerExtensions.cs#L26

If we ever needed to localize our exceptions, it wouldn't be that hard to find these. But odds are, after 8 years of .NET Core System.* libraries not being localized, I'd be surprised if it ever happens.

Copy link
Member

Choose a reason for hiding this comment

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

Agreed.

}
}
}
24 changes: 24 additions & 0 deletions src/Components/Aspire.MySqlConnector/Aspire.MySqlConnector.csproj
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>$(NetCurrent)</TargetFramework>
<IsPackable>true</IsPackable>
<PackageTags>$(ComponentDatabasePackageTags) mysqlconnector mysql sql</PackageTags>
<Description>A MySQL client that integrates with Aspire, including health checks, metrics, logging, and telemetry.</Description>
Copy link
Member

Choose a reason for hiding this comment

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

Does MySQL need a ® sign after it, like we do for PostgreSQL?

<PackageIconFullPath>$(SharedDir)SQL_256x.png</PackageIconFullPath>
Copy link
Member

Choose a reason for hiding this comment

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

@DamianEdwards - should this have the same icon as the https://www.nuget.org/packages/MySqlConnector/ package?

image

Copy link
Member

Choose a reason for hiding this comment

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

That would be ideal, assuming we have permission to do so 😀

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I created the MySqlConnector package icon (using free sources) and will give any necessary permission to include it here.

</PropertyGroup>

<ItemGroup>
<Compile Include="..\Common\HealthChecksExtensions.cs" Link="HealthChecksExtensions.cs" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="AspNetCore.HealthChecks.MySql" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
<PackageReference Include="MySqlConnector.DependencyInjection" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" />
</ItemGroup>

</Project>
132 changes: 132 additions & 0 deletions src/Components/Aspire.MySqlConnector/AspireMySqlConnectorExtensions.cs
@@ -0,0 +1,132 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Aspire;
using Aspire.MySqlConnector;
using HealthChecks.MySql;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using MySqlConnector;

namespace Microsoft.Extensions.Hosting;

/// <summary>
/// Extension methods for connecting MySQL database with MySqlConnector client
/// </summary>
public static class AspireMySqlConnectorExtensions
{
private const string DefaultConfigSectionName = "Aspire:MySqlConnector";

/// <summary>
/// Registers <see cref="MySqlDataSource"/> service for connecting MySQL database with MySqlConnector client.
/// Configures health check, logging and telemetry for the MySqlConnector client.
/// </summary>
/// <param name="builder">The <see cref="IHostApplicationBuilder" /> to read config from and add services to.</param>
/// <param name="connectionName">A name used to retrieve the connection string from the ConnectionStrings configuration section.</param>
/// <param name="configureSettings">An optional delegate that can be used for customizing options. It's invoked after the settings are read from the configuration.</param>
/// <remarks>Reads the configuration from "Aspire:MySqlConnector" section.</remarks>
/// <exception cref="ArgumentNullException">Thrown if mandatory <paramref name="builder"/> is null.</exception>
/// <exception cref="InvalidOperationException">Thrown when mandatory <see cref="MySqlConnectorSettings.ConnectionString"/> is not provided.</exception>
public static void AddMySqlDataSource(this IHostApplicationBuilder builder, string connectionName, Action<MySqlConnectorSettings>? configureSettings = null)
=> AddMySqlDataSource(builder, DefaultConfigSectionName, configureSettings, connectionName, serviceKey: null);

/// <summary>
/// Registers <see cref="MySqlDataSource"/> as a keyed service for given <paramref name="name"/> for connecting MySQL database with MySqlConnector client.
/// Configures health check, logging and telemetry for the MySqlConnector client.
/// </summary>
/// <param name="builder">The <see cref="IHostApplicationBuilder" /> to read config from and add services to.</param>
/// <param name="name">The name of the component, which is used as the <see cref="ServiceDescriptor.ServiceKey"/> of the service and also to retrieve the connection string from the ConnectionStrings configuration section.</param>
/// <param name="configureSettings">An optional method that can be used for customizing options. It's invoked after the settings are read from the configuration.</param>
/// <remarks>Reads the configuration from "Aspire:MySqlConnector:{name}" section.</remarks>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="name"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown if mandatory <paramref name="name"/> is empty.</exception>
/// <exception cref="InvalidOperationException">Thrown when mandatory <see cref="MySqlConnectorSettings.ConnectionString"/> is not provided.</exception>
public static void AddKeyedMySqlDataSource(this IHostApplicationBuilder builder, string name, Action<MySqlConnectorSettings>? configureSettings = null)
{
ArgumentException.ThrowIfNullOrEmpty(name);

AddMySqlDataSource(builder, $"{DefaultConfigSectionName}:{name}", configureSettings, connectionName: name, serviceKey: name);
}

private static void AddMySqlDataSource(IHostApplicationBuilder builder, string configurationSectionName,
Action<MySqlConnectorSettings>? configureSettings, string connectionName, object? serviceKey)
{
ArgumentNullException.ThrowIfNull(builder);

MySqlConnectorSettings settings = new();
builder.Configuration.GetSection(configurationSectionName).Bind(settings);

if (builder.Configuration.GetConnectionString(connectionName) is string connectionString)
{
settings.ConnectionString = connectionString;
}

configureSettings?.Invoke(settings);

builder.RegisterMySqlServices(settings, configurationSectionName, connectionName, serviceKey);

// Same as SqlClient connection pooling is on by default and can be handled with connection string
// https://mysqlconnector.net/connection-options/#Pooling
if (settings.HealthChecks)
{
builder.TryAddHealthCheck(new HealthCheckRegistration(
serviceKey is null ? "MySql" : $"MySql_{connectionName}",
sp => new MySqlHealthCheck(new MySqlHealthCheckOptions()
{
ConnectionString = serviceKey is null
? sp.GetRequiredService<MySqlDataSource>().ConnectionString
: sp.GetRequiredKeyedService<MySqlDataSource>(serviceKey).ConnectionString
Comment on lines +78 to +80
Copy link
Member

Choose a reason for hiding this comment

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

How do you feel about opening a PR to https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks to make this consistent with Npgsql? We shouldn't be creating another DbDataSource and checking the health of that. Instead, we should be using the same DbDataSource instance as the app is using. That way if that DbDataSource ever gets corrupt, the health check is accurate. From the Components README:

- Consider whether the Health Check should reuse the same client object registered in DI by the component or not. Reusing the same client object has the advantages of getting the same configuration, logging, etc during the health check.

See also Xabaril/AspNetCore.Diagnostics.HealthChecks#1832

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sounds good; I have another reason to open a PR there, too: Xabaril/AspNetCore.Diagnostics.HealthChecks#2031.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

}),
failureStatus: default,
tags: default,
timeout: default));
}

if (settings.Tracing)
{
builder.Services.AddOpenTelemetry()
.WithTracing(tracerProviderBuilder =>
{
tracerProviderBuilder.AddSource("MySqlConnector");
});
}

if (settings.Metrics)
{
builder.Services.AddOpenTelemetry()
.WithMetrics(meterProviderBuilder =>
{
meterProviderBuilder.AddMeter("MySqlConnector");
});
}
}

private static void RegisterMySqlServices(this IHostApplicationBuilder builder, MySqlConnectorSettings settings, string configurationSectionName, string connectionName, object? serviceKey)
{
if (serviceKey is null)
{
builder.Services.AddMySqlDataSource(settings.ConnectionString ?? string.Empty, dataSourceBuilder =>
{
ValidateConnection();
});
}
else
{
builder.Services.AddKeyedMySqlDataSource(serviceKey, settings.ConnectionString ?? string.Empty, dataSourceBuilder =>
{
ValidateConnection();
});
}

// delay validating the ConnectionString until the DataSource is requested. This ensures an exception doesn't happen until a Logger is established.
void ValidateConnection()
{
if (string.IsNullOrEmpty(settings.ConnectionString))
{
throw new InvalidOperationException($"ConnectionString is missing. It should be provided in 'ConnectionStrings:{connectionName}' or under the 'ConnectionString' key in '{configurationSectionName}' configuration section.");
}
}
}
}