Repository navigation
MongoDB Replicaset support - #16698
Artiom Chilaru (artiomchi) wants to merge 9 commits into
Conversation
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 16698Or
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 16698" |
Minor cleanup
66c95f0 to
67db131
Compare
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Adds single-node replica set support for hosted MongoDB resources so transaction-dependent scenarios can run against the Aspire MongoDB container, and introduces tests for the new API and connection string behavior.
Changes:
- Add
WithReplicaSet(...)to configure MongoDB as a single-node replica set and exposeReplicaSetName. - Replace the default MongoDB health check with a custom health check that initializes the replica set and waits for primary election.
- Add functional and unit tests covering the new API, container args, and connection string updates.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/Aspire.Hosting.MongoDB.Tests/MongoDbFunctionalTests.cs | Adds a functional test that verifies transactions succeed against a replica-set-enabled MongoDB resource. |
| tests/Aspire.Hosting.MongoDB.Tests/MongoDBPublicApiTests.cs | Adds public API validation tests for WithReplicaSet and ReplicaSetName. |
| tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs | Adds unit tests for replica set defaults, args, annotations, and connection string behavior. |
| src/Aspire.Hosting.MongoDB/api/Aspire.Hosting.MongoDB.cs | Updates the shipped public API surface with WithReplicaSet and ReplicaSetName. |
| src/Aspire.Hosting.MongoDB/MongoDBServerResource.cs | Extends the resource model and connection string generation for replica set mode. |
| src/Aspire.Hosting.MongoDB/MongoDBServerHealthCheck.cs | Introduces a custom health check that initializes the replica set and checks primary readiness. |
| src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs | Registers the new health check and implements WithReplicaSet. |
…ead safe way Disposing of the mongo cursor in the health check
…tensions.CreateGeneratedParameter
| /// <param name="replicaSetName">The name of the replica set. Defaults to <c>rs0</c>.</param> | ||
| /// <returns>The <see cref="IResourceBuilder{T}"/>.</returns> | ||
| [AspireExport(Description = "Configures the MongoDB container to start as a single-node replica set")] | ||
| public static IResourceBuilder<MongoDBServerResource> WithReplicaSet(this IResourceBuilder<MongoDBServerResource> builder, string replicaSetName = "rs0") |
There was a problem hiding this comment.
My concern is that this design does not allow to extend this feature beyond single-node replica sets.
In my opinion, having a replica set as a separate resource is a better option.
There was a problem hiding this comment.
Is this needed though, for a local development database? This shouldn't be used to deploy a resilient production level database, that would require an entirely different ballgame
There was a problem hiding this comment.
Artiom Chilaru (@artiomchi) Why would that require an entirely different ballgame though? I would agree with fedarovich that we should support this scenario.
There was a problem hiding this comment.
What's the use-case for spinning a multi-node replica set in a local aspire host though?
For local development, the reason to have a replica set is to be able to use transactions in your application. Whether this is running in a single node or multiple - the end result will be the same.
And this would never be used in a production deployment.
Right now Aspire doesn't support this at all. And had 2 PRs rejected with previous implementations. This approach adds the replica set support with minimal changes, no side-effects, simple configuration and transparent usage for the users. And doing it without adding unnecessary complexity.
Changing this to deploy a replica set in a separate resource would mean a more complex configuration for the users. It would also mean they need a different way to get the connection string, as well as depending on the replica set resource instead of the database resource, when building their app host. So now you need to configure your app host dependencies differently depending on whether your mongo instance is a replica set or not.
This can be done, but I just don't see the purpose. Or any reason to overcomplicate the API and diminish the user experience without getting anything tangible in return
There was a problem hiding this comment.
P.S. If you think I'm wrong on this, I would genuinely want to know that and I'm happy to reconsider.
There was a problem hiding this comment.
I am actually currently working on a PR that achieves what yours achieves while treating the replica set as its own "logical" resource, thereby enabling multi-node replica sets. I'll ping you once it's ready and you tell me what you think of the approach.
There was a problem hiding this comment.
True, but in a cloud environment it would deploy a managed cloud database resource. i.e. in the link you provided, it would deploy a Relational Database Service in AWS or Database for Postgres in Azure. Both are managed resources that are already pre-configured for reliability, uptime, monitoring, resilience and security by DB specialists.
Deploying a stateless application is one thing, but you wouldn't just deploy a database in production in a docker/k8s container from Aspire like that. You need storage configuration, node affinity, networking configuration, backups, credential/key rotation, updates, monitoring and SO much more. So yes, for Aspire I don't see the Mongo component as a production ready deployable resource - in prod it would use a managed MongoDB cloud resource, not a Docker container
There was a problem hiding this comment.
I am actually currently working on a PR that achieves what yours achieves while treating the replica set as its own "logical" resource, thereby enabling multi-node replica sets. I'll ping you once it's ready and you tell me what you think of the approach.
I've had something like that implemented in the first iterations of this implementation. It worked (with a couple small caveats), but in the end it just added unnecessary complexity, and didn't really bring any benefits.
But I'm happy to check it out and share my thoughts on it once it's done!
There was a problem hiding this comment.
Soo.. What happened as part of your PR? I saw you going through it for a while.. but in the end - you closed it? Why was it closed, and what happens next?
There was a problem hiding this comment.
Artiom Chilaru (@artiomchi) I closed it accidentally; I just reopened it.
It's near complete; only some final touches left: #18196
|
David Fowler (@davidfowl) I noticed the previous PRs that tried to implement this feature were eventually closed, as they needed some internal Aspire refactoring/features.. This one uses a different (and much simpler) approach, and shouldn't be blocked by anything though. Happy to help in any way to get this reviewed and moved across |
|
Mitch Denny (@mitchdenny) David Negstad (@danegsta) Is there any chance this PR could get some eyes on it? It's a simple enough change, can be improved with publish/deployment support in the future (if that's even needed), but would do a LOT to help with local dev experience, and wouldn't detract from any of the existing functionality. I'm very eager to get any form of replicaset support added to Aspire, and would like to help make it happen. Please just let us know how we can help. |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.
Suppressed comments (6)
tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:308
ContainerFileSystemCallbackContext.Servicesis required. Assigning the obsoleteServiceProvideralias does not satisfy required-member initialization, so this test does not compile (CS9035) and also uses an obsolete API.
new() { Model = mongo.Resource, ServiceProvider = app.Services },
tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:353
- This test is marked
asyncbut contains noawait, producing CS1998. Make it synchronous so the test project remains warning-free.
public async Task WithReplicaSetDatabaseConnectionStringIncludesDirectConnection()
src/Aspire.Hosting.MongoDB/api/Aspire.Hosting.MongoDB.cs:43
- This file is explicitly auto-generated (lines 2–6), and repository convention keeps these API baseline files unchanged in feature PRs because edits can alter the compatibility baseline and are overwritten by regeneration. Revert all additions in this generated file; the release process regenerates API baselines.
[AspireExport("withReplicaSet", Description = "Configures the MongoDB container to start as a single-node replica set")]
public static ApplicationModel.IResourceBuilder<ApplicationModel.MongoDBServerResource> WithReplicaSet(this ApplicationModel.IResourceBuilder<ApplicationModel.MongoDBServerResource> builder, string replicaSetName = "rs0") { throw null; }
src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs:288
- This public method explicitly throws three exception types, but its XML documentation omits them. Documenting these exceptions is required for public Aspire APIs so IntelliSense accurately describes the contract.
/// <param name="builder">The resource builder.</param>
/// <param name="replicaSetName">The name of the replica set. Defaults to <c>rs0</c>.</param>
/// <returns>The <see cref="IResourceBuilder{T}"/>.</returns>
src/Aspire.Hosting.MongoDB/MongoDBServerResource.cs:142
- Appending
directConnection=truemakes the publicUriExpressionremarks inaccurate: they still document only the optional authentication query segment. Update that format documentation to include the replica-set direct-connection query parameter.
if (ReplicaSetName is not null)
{
builder.AppendLiteral(PasswordParameter is not null ? "&" : "?");
builder.AppendLiteral("directConnection=true");
}
tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:321
- This test is marked
asyncbut contains noawait, producing CS1998. Make it synchronous so the test project remains warning-free.
This issue also appears on line 353 of the same file.
public async Task WithReplicaSetServerConnectionStringIncludesDirectConnectionWithAuth()
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.
Suppressed comments (13)
src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs:295
- The new public method also throws for a null builder/name, an empty name, and duplicate replica-set configuration, but only publish mode is documented. Add the missing exception contracts so IntelliSense matches the validated behavior.
/// <exception cref="NotSupportedException">Thrown if called while publishing.</exception>
tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:362
- This test is marked
asyncbut contains noawait, producing CS1998 and unnecessary state-machine semantics. Make it synchronous.
public async Task WithReplicaSetDatabaseConnectionStringIncludesDirectConnection()
src/Aspire.Hosting.MongoDB/api/Aspire.Hosting.MongoDB.cs:43
- This generated API baseline should not be updated in an individual feature PR. Keeping these edits bypasses the repository's release-time API generation workflow; revert all additions in this
api/*.csfile and let the release process regenerate it.
public static ApplicationModel.IResourceBuilder<ApplicationModel.MongoDBServerResource> WithReplicaSet(this ApplicationModel.IResourceBuilder<ApplicationModel.MongoDBServerResource> builder, string replicaSetName = "rs0") { throw null; }
src/Aspire.Hosting.MongoDB/MongoDBServerResource.cs:71
KeyFileContentParameterexposes an implementation-only replica-set authentication credential as permanent public API. The only production consumer is the container-file callback in this assembly, so this unnecessarily expands the public and secret-bearing surface; keep it internal unless there is a concrete external customization scenario.
public ParameterResource? KeyFileContentParameter { get; internal set; }
src/Aspire.Hosting.MongoDB/MongoDBServerResource.cs:69
- The remarks claim this parameter is emitted during publish, but
WithReplicaSetalways throws in publish mode, so this documented behavior is unreachable. Remove the publish-mode statement so IntelliSense describes the actual API contract.
/// The value is generated as a high-entropy secret on first use and persisted to the AppHost's user secrets store
/// in run mode, so it remains stable across runs of the same AppHost. In publish mode the parameter is emitted to
/// the manifest with a <c>generate</c> directive.
src/Aspire.Hosting.MongoDB/MongoDBServerResource.cs:141
- Appending
directConnection=truechanges the documented URI format, but the publicUriExpressionremarks above still describe only the authentication query parameters. Update that format documentation to include the optional direct-connection query parameter for replica-set resources.
if (ReplicaSetName is not null)
{
builder.AppendLiteral(PasswordParameter is not null ? "&" : "?");
builder.AppendLiteral("directConnection=true");
src/Aspire.Hosting.MongoDB/MongoDBServerResource.cs:176
- The new
DirectConnectionstructured connection property is not exercised by the added tests; they only inspectConnectionStringExpression. Add a replica-set case toConnectionPropertiesTeststhat verifies the key/value and its propagation to database connection properties, otherwise this consumer-facing contract can regress independently of the URI tests.
if (ReplicaSetName is not null)
{
yield return new("DirectConnection", ReferenceExpression.Create($"true"));
tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:330
- This test is marked
asyncbut contains noawait, producing CS1998 and unnecessary state-machine semantics. Make it synchronous.
This issue also appears on line 362 of the same file.
public async Task WithReplicaSetServerConnectionStringIncludesDirectConnectionWithAuth()
tests/Aspire.Hosting.MongoDB.Tests/MongoDbFunctionalTests.cs:451
CancellationTokenSourceowns a timer and is not disposed, so the timer can remain rooted after the test finishes. Dispose it with the test scope.
var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5));
tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:358
- These partial positive/negative checks can pass for other malformed connection strings and use the repository-discouraged
Assert.DoesNotContainpattern. Assert the complete expression so the separator and full URI shape are covered.
Assert.Contains("?directConnection=true", mongo.Resource.ConnectionStringExpression.ValueExpression);
Assert.DoesNotContain("&directConnection=true", mongo.Resource.ConnectionStringExpression.ValueExpression);
tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:375
- Checking only for the new token does not verify that it is placed in the database URI's query string correctly. Follow the exact connection-string assertions used elsewhere in this file so malformed ordering or separators fail this regression test.
Assert.Contains("directConnection=true", dbResource.ConnectionStringExpression.ValueExpression);
tests/Aspire.Hosting.MongoDB.Tests/AddMongoDBTests.cs:384
- This absence-only assertion is explicitly discouraged in this test suite because it does not verify the connection string that is produced. Assert the complete standalone URI instead.
Assert.DoesNotContain("directConnection", mongo.Resource.ConnectionStringExpression.ValueExpression);
src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs:290
- This new public fluent extension lacks the usage example required for Aspire extension APIs. Add an
<example>with a<code>block showingAddMongoDB(...).WithReplicaSet()so the generated API documentation demonstrates the supported run-mode usage.
This issue also appears on line 295 of the same file.
/// This method is only supported when running the AppHost (F5/<c>aspire run</c>). The manifest publisher
/// serializes the <c>--keyFile</c> argument without invoking the container file callback that writes the
/// keyfile, so publishing would produce a container that references a keyfile that never gets created.
/// </para>
/// </remarks>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.
Suppressed comments (4)
src/Aspire.Hosting.MongoDB/MongoDBServerResource.cs:127
- Appending
directConnection=truemakes the public URI documentation inaccurate:MongoDBServerResource.UriExpressionandMongoDBDatabaseResource.UriExpressionstill say query segments are present only when a password is configured and omit the replica-set option. Update both XML comments so generated documentation describes replica-set connection strings.
if (ReplicaSetName is not null)
src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs:294
- This new public fluent extension has no
<example>/<code>usage block, leaving the published API documentation incomplete. Add a minimalAddMongoDB(...).WithReplicaSet(...)example.
public static IResourceBuilder<MongoDBServerResource> WithReplicaSet(this IResourceBuilder<MongoDBServerResource> builder, string replicaSetName = "rs0")
src/Aspire.Hosting.MongoDB/MongoDBServerHealthCheck.cs:36
- This server-state check specifically fixes reinitialization after a container is recreated, but the new functional test only initializes a fresh container once. Add a restart/recreation regression test that first reaches healthy, recreates the MongoDB container without its prior replica-set configuration, and verifies the health check initializes it again; otherwise the previously identified stale-state failure can regress unnoticed.
// The server is the source of truth for replica set state. A node started with
// --replSet that has not had replSetInitiate run reports no `setName` in `hello`;
// the same is true after a container is recreated and its prior config is gone.
if (!hello.Contains("setName"))
src/Aspire.Hosting.MongoDB/MongoDBBuilderExtensions.cs:296
- The XML documentation omits the exceptions thrown when
builderis null orreplicaSetNameis null/empty. Document both validation failures so IntelliSense accurately describes this public API.
/// <exception cref="NotSupportedException">Thrown if called while publishing.</exception>
/// <exception cref="InvalidOperationException">Thrown if a replica set has already been configured for the resource.</exception>
|
Artiom Chilaru (@artiomchi) Not sure what is the exact intent of CommunityToolkit/Aspire, but do you think there is perhaps a better chance to land your simplified version there first? |
|
ggirard07 (@ggirard07) thing is, there are already a couple third party external packages that add replicaset support. The idea is to add this as a first party solution directly into Aspire, avoiding having to import a third party package that you have to trust in your environment. |
|
Duplicate of #19961 The new PR superseeds this one |
Description
This PR modifies the MongoDB Builder to add support for building a single node replica set. This will allow applications using transactions or change streams to use MongoDB in Aspire.
I'm using the same approach as I used when building the Testcontainers.MongoDb library. Instead of building a separate container in a dockerfile, the standard mongo container is used. To start as a replicaset, a keyfile is generated and added to to the container. The healthcheck is used to ensure the replicaset is initialised on server startup. This keeps the implementation clean and doesn't require an additional dockerfile.
WithReplicaSet()Extension Method on the builderreplSetInitiatecommand runsdirectConnection=trueparameter when replica set is enabledFixes #5238
Decision points
New health check
The new health check replaces the simple original health check and will only return healthy once the replica set is initialised. It is also used to call the
rs.initiate()call in Mongo to initialise the replicaset.Alternatives considered:
OnResourceReadycallback fires after the health check passes - this would mark the resource as healthy before the replica set is readydocker-entrypoint-initdb.d- tried in the past, this won't work as that script runs against a standalonemongodinstance, and won't affect the main instanceDirect connection in connection string
Specifying the replicaset name in the connection string is explicitly discouraged by the MongoDB driver configuration, and can cause behavioural conflicts. Specifying
directConnection=truein the connection string tells the MongoDB driver to connect directly to the specified host bypassing topology discovery. Since we only have a single node, this is more than enough. Additionally, the topology discovery would return the internal host address within the container, which wouldn't be accessible by the application.Note
There may be an issue in Mongo 8.0 - 8.2 that causes Mongo to crash every ~30 seconds if replica set is initiated. Seems to be a compatibility issue with certain linux kernels. Switching to older Mongo versions (7.0) seems to completely bypass the issue. Not related to this PR or Aspire, purely a MongoDB regression.
ref:
bluewave-labs/Checkmate#3444
https://www.mongodb.com/community/forums/t/mongodb-8-x-and-linux-kernel-6-19/337547
stoatchat/self-hosted#268
Checklist
<remarks />and<code />elements on your triple slash comments?aspire.devissue: