Skip to content

Commit 01e4ca9

Browse files
committed
Refactor AddDbGate method to use default name
Removed the `name` parameter from the `AddDbGate` method across various builder extension classes, simplifying the method signature to only require the `port` parameter. The default name "dbgate" is now used internally. Updated tests to reflect the new method signature and default naming convention, ensuring assertions check for the new default name. Adjusted environment variable handling in `ConfigureDbGateContainer` methods to accommodate these changes. These updates streamline the API for adding a DbGate container resource while maintaining functionality for different database types.
1 parent 30a4b63 commit 01e4ca9

File tree

14 files changed

+144
-187
lines changed

14 files changed

+144
-187
lines changed

src/CommunityToolkit.Aspire.Hosting.DbGate/DbGateBuilderExtensions.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,13 @@ public static IResourceBuilder<DbGateContainerResource> WithDataBindMount(this I
5757
/// Adds a DbGate container resource to the application.
5858
/// </summary>
5959
/// <param name="builder">The resource builder.</param>
60-
/// <param name="name">The name of the resource. This name will be used as the connection string name when referenced in a dependency.</param>
60+
/// <param name="name">The name of the resource. This name will be used as the connection string name when referenced in a dependency. Optional; defaults to <c>dbgate</c>.</param>
6161
/// <param name="port">The host port to bind the underlying container to.</param>
6262
/// <remarks>
6363
/// Multiple <see cref="AddDbGate(IDistributedApplicationBuilder, string, int?)"/> calls will return the same resource builder instance.
6464
/// </remarks>
6565
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
66-
public static IResourceBuilder<DbGateContainerResource> AddDbGate(this IDistributedApplicationBuilder builder, [ResourceName] string name, int? port = null)
66+
public static IResourceBuilder<DbGateContainerResource> AddDbGate(this IDistributedApplicationBuilder builder, [ResourceName] string name = "dbgate", int? port = null)
6767
{
6868
ArgumentNullException.ThrowIfNull(builder);
6969
ArgumentNullException.ThrowIfNull(name);

src/CommunityToolkit.Aspire.Hosting.MongoDB.Extensions/MongoDBBuilderExtensions.cs

Lines changed: 15 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -37,57 +37,35 @@ public static IResourceBuilder<MongoDBServerResource> WithDbGate(this IResourceB
3737
{
3838
ArgumentNullException.ThrowIfNull(builder);
3939

40-
containerName ??= $"{builder.Resource.Name}-dbgate";
41-
42-
var dbGateBuilder = DbGateBuilderExtensions.AddDbGate(builder.ApplicationBuilder, containerName);
40+
var dbGateBuilder = builder.ApplicationBuilder.AddDbGate();
4341

4442
dbGateBuilder
45-
.WithEnvironment(context => ConfigureDbGateContainer(context, builder.ApplicationBuilder));
43+
.WithEnvironment(context => ConfigureDbGateContainer(context, builder))
44+
.WaitFor(builder);
4645

4746
configureContainer?.Invoke(dbGateBuilder);
4847

4948
return builder;
5049
}
5150

52-
private static void ConfigureDbGateContainer(EnvironmentCallbackContext context, IDistributedApplicationBuilder applicationBuilder)
51+
private static void ConfigureDbGateContainer(EnvironmentCallbackContext context, IResourceBuilder<MongoDBServerResource> builder)
5352
{
54-
var mongoDBInstances = applicationBuilder.Resources.OfType<MongoDBServerResource>();
53+
var mongoDBServer = builder.Resource;
5554

56-
var counter = 1;
55+
// DbGate assumes MongoDB is being accessed over a default Aspire container network and hardcodes the resource address
56+
// This will need to be refactored once updated service discovery APIs are available
57+
context.EnvironmentVariables.Add($"LABEL_{mongoDBServer.Name}", mongoDBServer.Name);
58+
context.EnvironmentVariables.Add($"URL_{mongoDBServer.Name}", mongoDBServer.ConnectionStringExpression);
59+
context.EnvironmentVariables.Add($"ENGINE_{mongoDBServer.Name}", "mongo@dbgate-plugin-mongo");
5760

58-
// Multiple WithDbGate calls will be ignored
59-
if (context.EnvironmentVariables.ContainsKey($"LABEL_mongodb{counter}"))
61+
string CONNECTIONS = context.EnvironmentVariables.GetValueOrDefault("CONNECTIONS")?.ToString() ?? string.Empty;
62+
if (string.IsNullOrEmpty(CONNECTIONS))
6063
{
61-
return;
64+
context.EnvironmentVariables["CONNECTIONS"] = mongoDBServer.Name;
6265
}
63-
64-
foreach (var mongoDBServer in mongoDBInstances)
66+
else
6567
{
66-
// DbGate assumes MongoDB is being accessed over a default Aspire container network and hardcodes the resource address
67-
// This will need to be refactored once updated service discovery APIs are available
68-
context.EnvironmentVariables.Add($"LABEL_mongodb{counter}", mongoDBServer.Name);
69-
context.EnvironmentVariables.Add($"URL_mongodb{counter}", mongoDBServer.ConnectionStringExpression);
70-
context.EnvironmentVariables.Add($"ENGINE_mongodb{counter}", "mongo@dbgate-plugin-mongo");
71-
72-
counter++;
73-
}
74-
75-
var instancesCount = mongoDBInstances.Count();
76-
if (instancesCount > 0)
77-
{
78-
var strBuilder = new StringBuilder();
79-
strBuilder.AppendJoin(',', Enumerable.Range(1, instancesCount).Select(i => $"mongodb{i}"));
80-
var connections = strBuilder.ToString();
81-
82-
string CONNECTIONS = context.EnvironmentVariables.GetValueOrDefault("CONNECTIONS")?.ToString() ?? string.Empty;
83-
if (string.IsNullOrEmpty(CONNECTIONS))
84-
{
85-
context.EnvironmentVariables["CONNECTIONS"] = connections;
86-
}
87-
else
88-
{
89-
context.EnvironmentVariables["CONNECTIONS"] += $",{connections}";
90-
}
68+
context.EnvironmentVariables["CONNECTIONS"] += $",{mongoDBServer.Name}";
9169
}
9270
}
9371
}

src/CommunityToolkit.Aspire.Hosting.Redis.Extensions/RedisBuilderExtensions.cs

Lines changed: 17 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -36,61 +36,38 @@ public static IResourceBuilder<RedisResource> WithDbGate(this IResourceBuilder<R
3636
{
3737
ArgumentNullException.ThrowIfNull(builder);
3838

39-
containerName ??= $"{builder.Resource.Name}-dbgate";
40-
41-
var dbGateBuilder = DbGateBuilderExtensions.AddDbGate(builder.ApplicationBuilder, containerName);
39+
var dbGateBuilder = builder.ApplicationBuilder.AddDbGate();
4240

4341
dbGateBuilder
44-
.WithEnvironment(context => ConfigureDbGateContainer(context, builder.ApplicationBuilder));
42+
.WithEnvironment(context => ConfigureDbGateContainer(context, builder))
43+
.WaitFor(builder);
4544

4645
configureContainer?.Invoke(dbGateBuilder);
4746

4847
return builder;
4948
}
5049

51-
private static void ConfigureDbGateContainer(EnvironmentCallbackContext context, IDistributedApplicationBuilder applicationBuilder)
50+
private static void ConfigureDbGateContainer(EnvironmentCallbackContext context, IResourceBuilder<RedisResource> builder)
5251
{
53-
var reidsInstances = applicationBuilder.Resources.OfType<RedisResource>();
52+
var redisResource = builder.Resource;
5453

55-
var counter = 1;
54+
// DbGate assumes Redis is being accessed over a default Aspire container network and hardcodes the resource address
55+
var redisUrl = redisResource.PasswordParameter is not null ?
56+
ReferenceExpression.Create($"redis://:{redisResource.PasswordParameter}@{redisResource.Name}:{redisResource.PrimaryEndpoint.TargetPort?.ToString()}") :
57+
ReferenceExpression.Create($"redis://{redisResource.Name}:{redisResource.PrimaryEndpoint.TargetPort?.ToString()}");
5658

57-
// Multiple WithDbGate calls will be ignored
58-
if (context.EnvironmentVariables.ContainsKey($"LABEL_redis{counter}"))
59-
{
60-
return;
61-
}
59+
context.EnvironmentVariables.Add($"LABEL_redis{redisResource.Name}", redisResource.Name);
60+
context.EnvironmentVariables.Add($"URL_redis{redisResource.Name}", redisUrl);
61+
context.EnvironmentVariables.Add($"ENGINE_redis{redisResource.Name}", "redis@dbgate-plugin-redis");
6262

63-
foreach (var redisResource in reidsInstances)
63+
string CONNECTIONS = context.EnvironmentVariables.GetValueOrDefault("CONNECTIONS")?.ToString() ?? string.Empty;
64+
if (string.IsNullOrEmpty(CONNECTIONS))
6465
{
65-
66-
// DbGate assumes Redis is being accessed over a default Aspire container network and hardcodes the resource address
67-
var redisUrl = redisResource.PasswordParameter is not null ?
68-
ReferenceExpression.Create($"redis://:{redisResource.PasswordParameter}@{redisResource.Name}:{redisResource.PrimaryEndpoint.TargetPort?.ToString()}") :
69-
ReferenceExpression.Create($"redis://{redisResource.Name}:{redisResource.PrimaryEndpoint.TargetPort?.ToString()}");
70-
71-
context.EnvironmentVariables.Add($"LABEL_redis{counter}", redisResource.Name);
72-
context.EnvironmentVariables.Add($"URL_redis{counter}", redisUrl);
73-
context.EnvironmentVariables.Add($"ENGINE_redis{counter}", "redis@dbgate-plugin-redis");
74-
75-
counter++;
66+
context.EnvironmentVariables["CONNECTIONS"] = redisResource.Name;
7667
}
77-
78-
var instancesCount = reidsInstances.Count();
79-
if (instancesCount > 0)
68+
else
8069
{
81-
var strBuilder = new StringBuilder();
82-
strBuilder.AppendJoin(',', Enumerable.Range(1, instancesCount).Select(i => $"redis{i}"));
83-
var connections = strBuilder.ToString();
84-
85-
string CONNECTIONS = context.EnvironmentVariables.GetValueOrDefault("CONNECTIONS")?.ToString() ?? string.Empty;
86-
if (string.IsNullOrEmpty(CONNECTIONS))
87-
{
88-
context.EnvironmentVariables["CONNECTIONS"] = connections;
89-
}
90-
else
91-
{
92-
context.EnvironmentVariables["CONNECTIONS"] += $",{connections}";
93-
}
70+
context.EnvironmentVariables["CONNECTIONS"] += $",{redisResource.Name}";
9471
}
9572
}
9673
}

tests/CommunityToolkit.Aspire.Hosting.DbGate.Tests/AddDbGateTests.cs

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ public void AddDbGateContainerWithDefaultsAddsAnnotationMetadata()
1313
{
1414
var appBuilder = DistributedApplication.CreateBuilder();
1515

16-
var dbgate = appBuilder.AddDbGate("dbgate");
16+
var dbgate = appBuilder.AddDbGate();
1717

1818
using var app = appBuilder.Build();
1919

@@ -49,7 +49,7 @@ public void AddDbGateContainerWithPort()
4949
{
5050
var appBuilder = DistributedApplication.CreateBuilder();
5151

52-
var dbgate = appBuilder.AddDbGate("dbgate", 9090);
52+
var dbgate = appBuilder.AddDbGate(port: 9090);
5353

5454
using var app = appBuilder.Build();
5555

@@ -85,23 +85,23 @@ public void MultipleAddDbGateCallsShouldAddOneDbGateResource()
8585
{
8686
var appBuilder = DistributedApplication.CreateBuilder();
8787

88-
appBuilder.AddDbGate("dbgate1");
89-
appBuilder.AddDbGate("dbgate2");
88+
appBuilder.AddDbGate();
89+
appBuilder.AddDbGate();
9090

9191
using var app = appBuilder.Build();
9292

9393
var appModel = app.Services.GetRequiredService<DistributedApplicationModel>();
9494

9595
var containerResource = Assert.Single(appModel.Resources.OfType<DbGateContainerResource>());
96-
Assert.Equal("dbgate1", containerResource.Name);
96+
Assert.Equal("dbgate", containerResource.Name);
9797
}
9898

9999
[Fact]
100100
public void VerifyWithHostPort()
101101
{
102102
var appBuilder = DistributedApplication.CreateBuilder();
103103

104-
var dbgate = appBuilder.AddDbGate("dbgate").WithHostPort(9090);
104+
var dbgate = appBuilder.AddDbGate().WithHostPort(9090);
105105

106106
using var app = appBuilder.Build();
107107

@@ -139,7 +139,7 @@ public void VerifyWithData(bool useVolume)
139139
{
140140
var appBuilder = DistributedApplication.CreateBuilder();
141141

142-
var dbgate = appBuilder.AddDbGate("dbgate");
142+
var dbgate = appBuilder.AddDbGate();
143143

144144
if (useVolume)
145145
{
@@ -241,11 +241,17 @@ public async Task WithDbGateShouldAddAnnotationsForMultipleDatabaseTypes()
241241

242242
Assert.NotNull(dbGateResource);
243243

244-
Assert.Equal("mongodb1-dbgate", dbGateResource.Name);
244+
Assert.Equal("dbgate", dbGateResource.Name);
245245

246246
var envs = await dbGateResource.GetEnvironmentVariableValuesAsync();
247247

248248
Assert.NotEmpty(envs);
249+
250+
var CONNECTIONS = envs["CONNECTIONS"];
251+
envs.Remove("CONNECTIONS");
252+
253+
Assert.Equal("mongodb1,mongodb2,postgres1,postgres2,redis1,redis2,sqlserver1,sqlserver2", CONNECTIONS);
254+
249255
Assert.Collection(envs,
250256
item =>
251257
{
@@ -552,7 +558,7 @@ public void WithDbGateShouldShouldAddOneDbGateResourceForMultipleDatabaseTypes()
552558
var dbGateResource = appModel.Resources.OfType<DbGateContainerResource>().SingleOrDefault();
553559

554560
var containerResource = Assert.Single(appModel.Resources.OfType<DbGateContainerResource>());
555-
Assert.Equal("mongodb1-dbgate", containerResource.Name);
561+
Assert.Equal("dbgate", containerResource.Name);
556562
}
557563

558564
[Fact]

tests/CommunityToolkit.Aspire.Hosting.DbGate.Tests/AppHostTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ public class AppHostTests(AspireIntegrationTestFixture<Projects.CommunityToolkit
99
[Fact]
1010
public async Task ResourceStartsAndRespondsOk()
1111
{
12-
var resourceName = "postgres1-dbgate";
12+
var resourceName = "dbgate";
1313
await fixture.ResourceNotificationService.WaitForResourceHealthyAsync(resourceName).WaitAsync(TimeSpan.FromMinutes(5));
1414
var httpClient = fixture.CreateHttpClient(resourceName);
1515

tests/CommunityToolkit.Aspire.Hosting.DbGate.Tests/DbGatePublicApiTests.cs

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,26 +8,13 @@ public class DbGatePublicApiTests
88
public void AddDbGateContainerShouldThrowWhenBuilderIsNull()
99
{
1010
IDistributedApplicationBuilder builder = null!;
11-
const string name = "dbgate";
1211

13-
var action = () => builder.AddDbGate(name);
12+
var action = () => builder.AddDbGate();
1413

1514
var exception = Assert.Throws<ArgumentNullException>(action);
1615
Assert.Equal(nameof(builder), exception.ParamName);
1716
}
1817

19-
[Fact]
20-
public void AddDbGateContainerShouldThrowWhenNameIsNull()
21-
{
22-
IDistributedApplicationBuilder builder = new DistributedApplicationBuilder([]);
23-
string name = null!;
24-
25-
var action = () => builder.AddDbGate(name);
26-
27-
var exception = Assert.Throws<ArgumentNullException>(action);
28-
Assert.Equal(nameof(name), exception.ParamName);
29-
}
30-
3118
[Theory]
3219
[InlineData(false)]
3320
[InlineData(true)]
@@ -56,7 +43,7 @@ public void WithDataShouldThrowWhenBuilderIsNull(bool useVolume)
5643
public void WithDataBindMountShouldThrowWhenSourceIsNull()
5744
{
5845
var builder = new DistributedApplicationBuilder([]);
59-
var resourceBuilder = builder.AddDbGate("dbgate");
46+
var resourceBuilder = builder.AddDbGate();
6047

6148
string source = null!;
6249

tests/CommunityToolkit.Aspire.Hosting.MongoDB.Extensions.Tests/AppHostTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ public class AppHostTests(AspireIntegrationTestFixture<Projects.CommunityToolkit
99
[Fact]
1010
public async Task ResourceStartsAndRespondsOk()
1111
{
12-
var resourceName = "mongodb1-dbgate";
12+
var resourceName = "dbgate";
1313
await fixture.ResourceNotificationService.WaitForResourceHealthyAsync(resourceName).WaitAsync(TimeSpan.FromMinutes(5));
1414
var httpClient = fixture.CreateHttpClient(resourceName);
1515

tests/CommunityToolkit.Aspire.Hosting.MongoDB.Extensions.Tests/ResourceCreationTests.cs

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -23,31 +23,32 @@ public async Task WithDbGateAddsAnnotations()
2323

2424
Assert.NotNull(dbGateResource);
2525

26-
Assert.Equal("mongodb-dbgate", dbGateResource.Name);
26+
Assert.Equal("dbgate", dbGateResource.Name);
2727

2828
var envs = await dbGateResource.GetEnvironmentVariableValuesAsync();
2929

3030
Assert.NotEmpty(envs);
31+
32+
var CONNECTIONS = envs["CONNECTIONS"];
33+
envs.Remove("CONNECTIONS");
34+
35+
Assert.Equal("mongodb", CONNECTIONS);
36+
3137
Assert.Collection(envs,
3238
item =>
3339
{
34-
Assert.Equal("LABEL_mongodb1", item.Key);
40+
Assert.Equal("LABEL_mongodb", item.Key);
3541
Assert.Equal(mongodbResource.Name, item.Value);
3642
},
3743
async item =>
3844
{
39-
Assert.Equal("URL_mongodb1", item.Key);
45+
Assert.Equal("URL_mongodb", item.Key);
4046
Assert.Equal(await mongodbResource.ConnectionStringExpression.GetValueAsync(default), item.Value);
4147
},
4248
item =>
4349
{
44-
Assert.Equal("ENGINE_mongodb1", item.Key);
50+
Assert.Equal("ENGINE_mongodb", item.Key);
4551
Assert.Equal("mongo@dbgate-plugin-mongo", item.Value);
46-
},
47-
item =>
48-
{
49-
Assert.Equal("CONNECTIONS", item.Key);
50-
Assert.Equal("mongodb1", item.Value);
5152
});
5253
}
5354

@@ -65,7 +66,7 @@ public void MultipleWithDbGateCallsAddsOneDbGateResource()
6566
var dbGateResource = appModel.Resources.OfType<DbGateContainerResource>().SingleOrDefault();
6667
Assert.NotNull(dbGateResource);
6768

68-
Assert.Equal("mongodb1-dbgate", dbGateResource.Name);
69+
Assert.Equal("dbgate", dbGateResource.Name);
6970
}
7071

7172
[Fact]
@@ -128,11 +129,17 @@ public async Task WithDbGateAddsAnnotationsForMultipleMongoDBResource()
128129

129130
Assert.NotNull(dbGateResource);
130131

131-
Assert.Equal("mongodb1-dbgate", dbGateResource.Name);
132+
Assert.Equal("dbgate", dbGateResource.Name);
132133

133134
var envs = await dbGateResource.GetEnvironmentVariableValuesAsync();
134135

135136
Assert.NotEmpty(envs);
137+
138+
var CONNECTIONS = envs["CONNECTIONS"];
139+
envs.Remove("CONNECTIONS");
140+
141+
Assert.Equal("mongodb1,mongodb2", CONNECTIONS);
142+
136143
Assert.Collection(envs,
137144
item =>
138145
{
@@ -163,11 +170,6 @@ public async Task WithDbGateAddsAnnotationsForMultipleMongoDBResource()
163170
{
164171
Assert.Equal("ENGINE_mongodb2", item.Key);
165172
Assert.Equal("mongo@dbgate-plugin-mongo", item.Value);
166-
},
167-
item =>
168-
{
169-
Assert.Equal("CONNECTIONS", item.Key);
170-
Assert.Equal("mongodb1,mongodb2", item.Value);
171173
});
172174
}
173175
}

tests/CommunityToolkit.Aspire.Hosting.PostgreSQL.Extensions.Tests/AppHostTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ public class AppHostTests(AspireIntegrationTestFixture<Projects.CommunityToolkit
99
[Fact]
1010
public async Task ResourceStartsAndRespondsOk()
1111
{
12-
var resourceName = "postgres1-dbgate";
12+
var resourceName = "dbgate";
1313
await fixture.ResourceNotificationService.WaitForResourceHealthyAsync(resourceName).WaitAsync(TimeSpan.FromMinutes(5));
1414
var httpClient = fixture.CreateHttpClient(resourceName);
1515

0 commit comments

Comments
 (0)