Skip to content

Commit

Permalink
Merge pull request #10 from asimmon/feature/background-replicaset-init
Browse files Browse the repository at this point in the history
Initialize the replica set in a background task and wait on the main thread
  • Loading branch information
asimmon authored Oct 8, 2022
2 parents 1217009 + 071eb6e commit 4ab99de
Showing 1 changed file with 38 additions and 12 deletions.
50 changes: 38 additions & 12 deletions src/EphemeralMongo.Core/MongodProcess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<BsonElement>
{
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<BsonDocument>(command);
_ = Task.Factory.StartNew(InitializeReplicaSet, new Tuple<MongoRunnerOptions, MongoClient>(this.Options, client), TaskCreationOptions.LongRunning);

var isReplicaSetReady = isReplicaSetReadyMre.Wait(this.Options.ReplicaSetSetupTimeout);
if (!isReplicaSetReady)
Expand Down Expand Up @@ -132,4 +121,41 @@ void OnOutputDataReceivedForReplicaSetReadiness(object sender, DataReceivedEvent
this.Process.OutputDataReceived -= OnOutputDataReceivedForReplicaSetReadiness;
}
}

private static void InitializeReplicaSet(object state)
{
var (options, client) = (Tuple<MongoRunnerOptions, MongoClient>)state;

try
{
var admin = client.GetDatabase("admin");

var replConfig = new BsonDocument(new List<BsonElement>
{
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<BsonDocument>(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);
}
}
}

0 comments on commit 4ab99de

Please sign in to comment.