From 4182343c7ae7f0013a0d3ce9d8cd2c2d3dc3b96d Mon Sep 17 00:00:00 2001 From: Anthony Simmon Date: Sat, 8 Oct 2022 18:27:30 -0400 Subject: [PATCH] Initialize the replica set in a background task --- src/EphemeralMongo.Core/MongodProcess.cs | 50 ++++++++++++++++++------ 1 file changed, 38 insertions(+), 12 deletions(-) diff --git a/src/EphemeralMongo.Core/MongodProcess.cs b/src/EphemeralMongo.Core/MongodProcess.cs index 9a81908..8cb68f3 100644 --- a/src/EphemeralMongo.Core/MongodProcess.cs +++ b/src/EphemeralMongo.Core/MongodProcess.cs @@ -86,19 +86,8 @@ void OnOutputDataReceivedForReplicaSetReadiness(object sender, DataReceivedEvent var connectionString = string.Format(CultureInfo.InvariantCulture, "mongodb://127.0.0.1:{0}/?connect=direct&replicaSet={1}", this.Options.MongoPort, this.Options.ReplicaSetName); var client = new MongoClient(connectionString); - var admin = client.GetDatabase("admin"); - - var replConfig = new BsonDocument(new List - { - new BsonElement("_id", this.Options.ReplicaSetName), - new BsonElement("members", new BsonArray - { - new BsonDocument { { "_id", 0 }, { "host", string.Format(CultureInfo.InvariantCulture, "127.0.0.1:{0}", this.Options.MongoPort) } }, - }), - }); - var command = new BsonDocument("replSetInitiate", replConfig); - admin.RunCommand(command); + _ = Task.Factory.StartNew(InitializeReplicaSet, new Tuple(this.Options, client), TaskCreationOptions.LongRunning); var isReplicaSetReady = isReplicaSetReadyMre.Wait(this.Options.ReplicaSetSetupTimeout); if (!isReplicaSetReady) @@ -132,4 +121,41 @@ void OnOutputDataReceivedForReplicaSetReadiness(object sender, DataReceivedEvent this.Process.OutputDataReceived -= OnOutputDataReceivedForReplicaSetReadiness; } } + + private static void InitializeReplicaSet(object state) + { + var (options, client) = (Tuple)state; + + try + { + var admin = client.GetDatabase("admin"); + + var replConfig = new BsonDocument(new List + { + new BsonElement("_id", options.ReplicaSetName), + new BsonElement("members", new BsonArray + { + new BsonDocument { { "_id", 0 }, { "host", string.Format(CultureInfo.InvariantCulture, "127.0.0.1:{0}", options.MongoPort) } }, + }), + }); + + using (var cts = new CancellationTokenSource(options.ReplicaSetSetupTimeout)) + { + var command = new BsonDocument("replSetInitiate", replConfig); + admin.RunCommand(command, cancellationToken: cts.Token); + } + } + catch (OperationCanceledException) + { + // ignored + } + catch (TimeoutException) + { + // ignored + } + catch (Exception ex) + { + options.StandardErrorLogger?.Invoke("An error occurred while initializing the replica set: " + ex); + } + } } \ No newline at end of file