From 898c98bb761cc7960ccf0819d154f476942ab85a Mon Sep 17 00:00:00 2001 From: davidfowl <95136+davidfowl@users.noreply.github.com> Date: Sat, 31 Oct 2026 13:38:48 +0000 Subject: [PATCH] Wait for the initiated MongoDB replica set member to become primary before reconfiguring replSetInitiate returns while the initial member is still stepping up. The forced replSetReconfig that adds the remaining members was sent straight away and raced that election, failing with InterruptedDueToReplStateChange (11602), which the initialization loop does not treat as retryable, so the replica set resource went to FailedToStart. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../MongoDBReplicaSetBuilderExtensions.cs | 95 ++++++++++---- .../MongoDBReplicaSetInitiationTests.cs | 120 ++++++++++++++++++ 2 files changed, 193 insertions(+), 22 deletions(-) create mode 100644 tests/Aspire.Hosting.MongoDB.Tests/ReplicaSet/MongoDBReplicaSetInitiationTests.cs diff --git a/src/Aspire.Hosting.MongoDB/ReplicaSet/MongoDBReplicaSetBuilderExtensions.cs b/src/Aspire.Hosting.MongoDB/ReplicaSet/MongoDBReplicaSetBuilderExtensions.cs index 381c1c2e074..e009bee36d8 100644 --- a/src/Aspire.Hosting.MongoDB/ReplicaSet/MongoDBReplicaSetBuilderExtensions.cs +++ b/src/Aspire.Hosting.MongoDB/ReplicaSet/MongoDBReplicaSetBuilderExtensions.cs @@ -28,6 +28,8 @@ public static class MongoDBReplicaSetBuilderExtensions private const string NewReplicaSetConfigurationIncompatibleCodeName = "NewReplicaSetConfigurationIncompatible"; private const string ConfigurationInProgressCodeName = "ConfigurationInProgress"; // NOTE: Represents the error `Cannot run replSetReconfig because the node is currently updating its configuration.` that can be returned by `replSetReconfig` when a preceding `replSetInitiate` (or `replSetReconfig`, for that matter) command is still being processed in the background. private static readonly TimeSpan s_rsInitiationRetryWaitInterval = TimeSpan.FromSeconds(1); + private static readonly TimeSpan s_primaryElectionPollInterval = TimeSpan.FromMilliseconds(100); + private static readonly TimeSpan s_primaryElectionTimeout = TimeSpan.FromSeconds(30); /// /// Adds a MongoDB replica set resource to the application model. @@ -299,28 +301,7 @@ await admin.RunCommandAsync( // NOTE: There is no existing configuration to preserve member ids from, so all of them are freshly allocated. var membersBsonArray = BuildMembersConfiguration(memberHosts, currentMembers: null); - // NOTE: The initialization is performed in two steps, first with a single member and then with the full configuration. `replSetInitiate` runs a quorum check against every host in the configuration it is handed and only returns once an election has succeeded, so initiating with the full member list makes success depend on every other member already being reachable. Initiating with only the initial primary elects it immediately, and the remaining members are then added by a reconfiguration, which does not have to wait on them. - await admin.RunCommandAsync(new BsonDocument - { - ["replSetInitiate"] = new BsonDocument - { - ["_id"] = rsResource.Name, - ["members"] = new BsonArray([membersBsonArray[0]]), - }, - // NOTE: A member has no primary until this very command has run, so selecting one is - // the one thing that cannot be asked for here. - }, readPreference: ReadPreference.Nearest, cancellationToken: ct).ConfigureAwait(false); - - await admin.RunCommandAsync(new BsonDocument - { - ["replSetReconfig"] = new BsonDocument - { - ["_id"] = rsResource.Name, - ["version"] = 2, - ["members"] = membersBsonArray, - }, - ["force"] = true, - }, readPreference: ReadPreference.Nearest, cancellationToken: ct).ConfigureAwait(false); + await InitiateReplicaSetAsync(admin, rsResource.Name, membersBsonArray, ct).ConfigureAwait(false); configured = true; break; } @@ -551,6 +532,76 @@ await evt.Services.GetRequiredService() .WithRelationship(member, "replica set member"); } + /// + /// Initiates a brand new replica set on the initial primary and then extends it to every declared member. + /// + /// + /// The initialization is performed in two steps, first with a single member and then with the full configuration. + /// replSetInitiate runs a quorum check against every host in the configuration it is handed, so initiating + /// with the full member list makes success depend on every other member already being reachable. Initiating with + /// only the initial primary does not, and the remaining members are then added by a reconfiguration. + /// + internal static async Task InitiateReplicaSetAsync(IMongoDatabase admin, string replicaSetName, BsonArray members, CancellationToken cancellationToken) + { + await admin.RunCommandAsync(new BsonDocument + { + ["replSetInitiate"] = new BsonDocument + { + ["_id"] = replicaSetName, + ["members"] = new BsonArray([members[0]]), + }, + // NOTE: A member has no primary until this very command has run, so selecting one is + // the one thing that cannot be asked for here. + }, readPreference: ReadPreference.Nearest, cancellationToken: cancellationToken).ConfigureAwait(false); + + // NOTE: `replSetInitiate` returns as soon as the configuration is installed, while the member is still going + // through its own election. A reconfiguration sent straight away races that election: it is either rejected with + // `ConfigurationInProgress`, or interrupted with `InterruptedDueToReplStateChange` by the state transition that + // makes the member primary. Waiting for the member to report itself as a writable primary closes that window. + await WaitForWritablePrimaryAsync(admin, cancellationToken).ConfigureAwait(false); + + await admin.RunCommandAsync(new BsonDocument + { + ["replSetReconfig"] = new BsonDocument + { + ["_id"] = replicaSetName, + ["version"] = 2, + ["members"] = members, + }, + ["force"] = true, + }, readPreference: ReadPreference.Nearest, cancellationToken: cancellationToken).ConfigureAwait(false); + } + + private static async Task WaitForWritablePrimaryAsync(IMongoDatabase admin, CancellationToken cancellationToken) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(s_primaryElectionTimeout); + + try + { + while (true) + { + // NOTE: `hello` is answered in every replica set state, and `isWritablePrimary` only turns true once the + // member has finished stepping up, which is the transition that would otherwise interrupt the next command. + var hello = await admin.RunCommandAsync( + new BsonDocument("hello", 1), + readPreference: ReadPreference.Nearest, + cancellationToken: timeout.Token).ConfigureAwait(false); + + if (hello.TryGetValue("isWritablePrimary", out var isWritablePrimary) && isWritablePrimary.ToBoolean()) + { + return; + } + + await Task.Delay(s_primaryElectionPollInterval, timeout.Token).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (timeout.IsCancellationRequested && !cancellationToken.IsCancellationRequested) + { + throw new DistributedApplicationException($"The initial MongoDB replica set member did not become a writable primary within {s_primaryElectionTimeout.TotalSeconds} seconds of being initiated."); + } + } + /// /// Whether a replica set's current members array already says what says, so that a /// reconfiguration would change nothing. diff --git a/tests/Aspire.Hosting.MongoDB.Tests/ReplicaSet/MongoDBReplicaSetInitiationTests.cs b/tests/Aspire.Hosting.MongoDB.Tests/ReplicaSet/MongoDBReplicaSetInitiationTests.cs new file mode 100644 index 00000000000..c5eefbf5f95 --- /dev/null +++ b/tests/Aspire.Hosting.MongoDB.Tests/ReplicaSet/MongoDBReplicaSetInitiationTests.cs @@ -0,0 +1,120 @@ +// 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; +using System.Reflection; +using MongoDB.Bson; +using MongoDB.Driver; +using MongoDB.Driver.Core.Clusters; +using MongoDB.Driver.Core.Connections; +using MongoDB.Driver.Core.Servers; + +#pragma warning disable ASPIREMONGODB001 + +namespace Aspire.Hosting.MongoDB.Tests; + +public class MongoDBReplicaSetInitiationTests +{ + private static readonly BsonArray s_members = + [ + new BsonDocument { ["_id"] = 0, ["host"] = "mongo1:27017" }, + new BsonDocument { ["_id"] = 1, ["host"] = "mongo2:27017" }, + new BsonDocument { ["_id"] = 2, ["host"] = "mongo3:27017" }, + ]; + + [Fact] + public async Task InitiationWaitsForTheInitialMemberToBecomeWritablePrimaryBeforeReconfiguring() + { + // The initiated member keeps reporting that it is not yet a writable primary for a few probes, and interrupts a + // reconfiguration sent before then with `InterruptedDueToReplStateChange`, like a real `mongod` stepping up does. + var admin = SteppingUpMember.Create(probesBeforePrimary: 3); + + await MongoDBReplicaSetBuilderExtensions.InitiateReplicaSetAsync(admin, "rs0", s_members, CancellationToken.None); + + var member = (SteppingUpMember)(object)admin; + Assert.Equal(["replSetInitiate", "hello", "hello", "hello", "replSetReconfig"], member.Commands.Select(c => c.GetElement(0).Name)); + + var initiate = member.Commands[0]["replSetInitiate"].AsBsonDocument; + Assert.Equal("rs0", initiate["_id"].AsString); + Assert.Equal(new BsonArray([s_members[0]]), initiate["members"].AsBsonArray); + + var reconfig = member.Commands[^1]; + Assert.True(reconfig["force"].AsBoolean); + Assert.Equal(2, reconfig["replSetReconfig"]["version"].AsInt32); + Assert.Equal(s_members, reconfig["replSetReconfig"]["members"].AsBsonArray); + } + + [Fact] + public async Task InitiationStopsWaitingForPrimaryWhenCancelled() + { + using var cancellation = new CancellationTokenSource(); + var admin = SteppingUpMember.Create(probesBeforePrimary: int.MaxValue, onProbe: probe => + { + if (probe == 2) + { + cancellation.Cancel(); + } + }); + + await Assert.ThrowsAnyAsync(() => + MongoDBReplicaSetBuilderExtensions.InitiateReplicaSetAsync(admin, "rs0", s_members, cancellation.Token)); + + var member = (SteppingUpMember)(object)admin; + Assert.DoesNotContain(member.Commands, c => c.GetElement(0).Name == "replSetReconfig"); + } + + public class SteppingUpMember : DispatchProxy + { + private int _probesBeforePrimary; + private int _probes; + private bool _initiated; + private Action? _onProbe; + + public List Commands { get; } = []; + + public static IMongoDatabase Create(int probesBeforePrimary, Action? onProbe = null) + { + var admin = Create(); + var member = (SteppingUpMember)(object)admin; + member._probesBeforePrimary = probesBeforePrimary; + member._onProbe = onProbe; + return admin; + } + + private bool IsWritablePrimary => _initiated && _probes >= _probesBeforePrimary; + + protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) + { + if (targetMethod is not { Name: nameof(IMongoDatabase.RunCommandAsync) } || args is not [BsonDocumentCommand command, _, CancellationToken cancellationToken]) + { + throw new NotSupportedException($"Unexpected call to '{targetMethod?.Name}'."); + } + + cancellationToken.ThrowIfCancellationRequested(); + Commands.Add(command.Document); + + switch (command.Document.GetElement(0).Name) + { + case "replSetInitiate": + _initiated = true; + return Task.FromResult(new BsonDocument("ok", 1)); + + case "hello": + _probes++; + _onProbe?.Invoke(_probes); + return Task.FromResult(new BsonDocument { ["isWritablePrimary"] = IsWritablePrimary, ["ok"] = 1 }); + + case "replSetReconfig" when !IsWritablePrimary: + var result = new BsonDocument { ["ok"] = 0, ["code"] = 11602, ["codeName"] = "InterruptedDueToReplStateChange" }; + var connectionId = new ConnectionId(new ServerId(new ClusterId(), new DnsEndPoint("mongo1", 27017))); + return Task.FromException(new MongoNodeIsRecoveringException(connectionId, command.Document, result)); + + case "replSetReconfig": + return Task.FromResult(new BsonDocument("ok", 1)); + + default: + throw new NotSupportedException($"Unexpected command '{command.Document}'."); + } + } + } +}