Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initialize the replica set in a background task and wait on the main thread #10

Merged
merged 2 commits into from
Oct 8, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}
}