summaryrefslogtreecommitdiff
path: root/src/mongo/db/repl/sync_source_resolver.cpp
blob: 8460ce006d45aa986ac55f48669d75ad144018e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */


#include "mongo/platform/basic.h"

#include "mongo/db/repl/sync_source_resolver.h"

#include <memory>

#include "mongo/db/jsobj.h"
#include "mongo/db/repl/oplog_entry.h"
#include "mongo/db/repl/sync_source_selector.h"
#include "mongo/logv2/log.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/destructor_guard.h"
#include "mongo/util/str.h"

#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kReplication


namespace mongo {
namespace repl {

const Seconds SyncSourceResolver::kFetcherTimeout(30);
const Seconds SyncSourceResolver::kFetcherErrorDenylistDuration(10);
const Seconds SyncSourceResolver::kOplogEmptyDenylistDuration(10);
const Seconds SyncSourceResolver::kFirstOplogEntryEmptyDenylistDuration(10);
const Seconds SyncSourceResolver::kFirstOplogEntryNullTimestampDenylistDuration(10);
const Minutes SyncSourceResolver::kTooStaleDenylistDuration(1);
const Seconds SyncSourceResolver::kNoRequiredOpTimeDenylistDuration(60);

SyncSourceResolver::SyncSourceResolver(executor::TaskExecutor* taskExecutor,
                                       SyncSourceSelector* syncSourceSelector,
                                       const OpTime& lastOpTimeFetched,
                                       const OpTime& requiredOpTime,
                                       const OnCompletionFn& onCompletion)
    : _taskExecutor(taskExecutor),
      _syncSourceSelector(syncSourceSelector),
      _lastOpTimeFetched(lastOpTimeFetched),
      _requiredOpTime(requiredOpTime),
      _onCompletion(onCompletion) {
    uassert(ErrorCodes::BadValue, "task executor cannot be null", taskExecutor);
    uassert(ErrorCodes::BadValue, "sync source selector cannot be null", syncSourceSelector);
    uassert(
        ErrorCodes::BadValue, "last fetched optime cannot be null", !lastOpTimeFetched.isNull());
    uassert(ErrorCodes::BadValue,
            str::stream() << "required optime (if provided) must be more recent than last "
                             "fetched optime. requiredOpTime: "
                          << requiredOpTime.toString()
                          << ", lastOpTimeFetched: " << lastOpTimeFetched.toString(),
            requiredOpTime.isNull() || requiredOpTime > lastOpTimeFetched);
    uassert(ErrorCodes::BadValue, "callback function cannot be null", onCompletion);
}

SyncSourceResolver::~SyncSourceResolver() {
    DESTRUCTOR_GUARD(shutdown(); join(););
}

bool SyncSourceResolver::isActive() const {
    stdx::lock_guard<Latch> lock(_mutex);
    return _isActive_inlock();
}

bool SyncSourceResolver::_isActive_inlock() const {
    return State::kRunning == _state || State::kShuttingDown == _state;
}

Status SyncSourceResolver::startup() {
    {
        stdx::lock_guard<Latch> lock(_mutex);
        switch (_state) {
            case State::kPreStart:
                _state = State::kRunning;
                break;
            case State::kRunning:
                return Status(ErrorCodes::IllegalOperation, "sync source resolver already started");
            case State::kShuttingDown:
                return Status(ErrorCodes::ShutdownInProgress, "sync source resolver shutting down");
            case State::kComplete:
                return Status(ErrorCodes::ShutdownInProgress, "sync source resolver completed");
        }
    }

    return _chooseAndProbeNextSyncSource(OpTime());
}

void SyncSourceResolver::shutdown() {
    stdx::lock_guard<Latch> lock(_mutex);
    // Transition directly from PreStart to Complete if not started yet.
    if (State::kPreStart == _state) {
        _state = State::kComplete;
        return;
    }

    // Nothing to do if we are already in ShuttingDown or Complete state.
    if (State::kShuttingDown == _state || State::kComplete == _state) {
        return;
    }

    invariant(_state == State::kRunning);
    _state = State::kShuttingDown;

    if (_fetcher) {
        _fetcher->shutdown();
    }
    if (_rbidCommandHandle) {
        _taskExecutor->cancel(_rbidCommandHandle);
    }
}

void SyncSourceResolver::join() {
    stdx::unique_lock<Latch> lk(_mutex);
    _condition.wait(lk, [this]() { return !_isActive_inlock(); });
}

bool SyncSourceResolver::_isShuttingDown() const {
    stdx::lock_guard<Latch> lock(_mutex);
    return State::kShuttingDown == _state;
}

StatusWith<HostAndPort> SyncSourceResolver::_chooseNewSyncSource() {
    HostAndPort candidate;
    try {
        candidate = _syncSourceSelector->chooseNewSyncSource(_lastOpTimeFetched);
    } catch (...) {
        return exceptionToStatus();
    }

    if (_isShuttingDown()) {
        return Status(ErrorCodes::CallbackCanceled,
                      str::stream() << "sync source resolver shut down before probing candidate: "
                                    << candidate);
    }

    return candidate;
}

std::unique_ptr<Fetcher> SyncSourceResolver::_makeFirstOplogEntryFetcher(
    HostAndPort candidate, OpTime earliestOpTimeSeen) {
    return std::make_unique<Fetcher>(
        _taskExecutor,
        candidate,
        NamespaceString::kRsOplogNamespace.dbName().db(),
        BSON("find" << NamespaceString::kRsOplogNamespace.coll() << "limit" << 1 << "sort"
                    << BSON("$natural" << 1) << "projection"
                    << BSON(OplogEntryBase::kTimestampFieldName
                            << 1 << OplogEntryBase::kTermFieldName << 1)
                    << ReadConcernArgs::kReadConcernFieldName << ReadConcernArgs::kLocal),
        [=](const StatusWith<Fetcher::QueryResponse>& response,
            Fetcher::NextAction*,
            BSONObjBuilder*) {
            return _firstOplogEntryFetcherCallback(response, candidate, earliestOpTimeSeen);
        },
        ReadPreferenceSetting::secondaryPreferredMetadata(),
        kFetcherTimeout /* find network timeout */,
        kFetcherTimeout /* getMore network timeout */);
}

std::unique_ptr<Fetcher> SyncSourceResolver::_makeRequiredOpTimeFetcher(HostAndPort candidate,
                                                                        OpTime earliestOpTimeSeen,
                                                                        int rbid) {
    // This query is structured so that it is executed on the sync source using the "oplog start
    // hack". The sync source should recognize that it can optimize an oplog query with a $gt/$gte
    // predicate over "ts".
    return std::make_unique<Fetcher>(
        _taskExecutor,
        candidate,
        NamespaceString::kRsOplogNamespace.dbName().db(),
        BSON("find" << NamespaceString::kRsOplogNamespace.coll() << "filter"
                    << BSON("ts" << BSON("$gte" << _requiredOpTime.getTimestamp() << "$lte"
                                                << _requiredOpTime.getTimestamp()))
                    << ReadConcernArgs::kReadConcernFieldName << ReadConcernArgs::kLocal),
        [=](const StatusWith<Fetcher::QueryResponse>& response,
            Fetcher::NextAction*,
            BSONObjBuilder*) {
            return _requiredOpTimeFetcherCallback(response, candidate, earliestOpTimeSeen, rbid);
        },
        ReadPreferenceSetting::secondaryPreferredMetadata(),
        kFetcherTimeout /* find network timeout */,
        kFetcherTimeout /* getMore network timeout */);
}

Status SyncSourceResolver::_scheduleFetcher(std::unique_ptr<Fetcher> fetcher) {
    stdx::lock_guard<Latch> lk(_mutex);
    // TODO SERVER-27499 need to check if _state is kShuttingDown inside the mutex.
    // Must schedule fetcher inside lock in case fetcher's callback gets invoked immediately by task
    // executor.
    auto status = fetcher->schedule();
    if (status.isOK()) {
        // Fetcher destruction blocks on all outstanding callbacks. If we are currently in a
        // Fetcher-related callback, we can't destroy the Fetcher just yet, so we assign it to a
        // temporary unique pointer to allow the destruction to run to completion.
        _shuttingDownFetcher = std::move(_fetcher);
        _fetcher = std::move(fetcher);
    } else {
        LOGV2_ERROR(21776,
                    "Error scheduling fetcher to evaluate host as sync source, "
                    "host:{host}, error: {error}",
                    "Error scheduling fetcher to evaluate host as sync source",
                    "host"_attr = fetcher->getSource(),
                    "error"_attr = status);
    }
    return status;
}

OpTime SyncSourceResolver::_parseRemoteEarliestOpTime(const HostAndPort& candidate,
                                                      const Fetcher::QueryResponse& queryResponse) {
    if (queryResponse.documents.empty()) {
        // Remote oplog is empty.
        const auto until = _taskExecutor->now() + kOplogEmptyDenylistDuration;
        LOGV2(5579703,
              "Denylisting {candidate} due to empty oplog for {denylistDuration} "
              "until: {denylistUntil}",
              "Denylisting candidate due to empty oplog",
              "candidate"_attr = candidate,
              "denylistDuration"_attr = kOplogEmptyDenylistDuration,
              "denylistUntil"_attr = until);
        _syncSourceSelector->denylistSyncSource(candidate, until);
        return OpTime();
    }

    const auto& firstObjFound = queryResponse.documents.front();
    if (firstObjFound.isEmpty()) {
        // First document in remote oplog is empty.
        const auto until = _taskExecutor->now() + kFirstOplogEntryEmptyDenylistDuration;
        LOGV2(5579704,
              "Denylisting {candidate} due to empty first document for "
              "{denylistDuration} until: {denylistUntil}",
              "Denylisting candidate due to empty first document",
              "candidate"_attr = candidate,
              "denylistDuration"_attr = kFirstOplogEntryEmptyDenylistDuration,
              "denylistUntil"_attr = until);
        _syncSourceSelector->denylistSyncSource(candidate, until);
        return OpTime();
    }

    const auto remoteEarliestOpTime = OpTime::parseFromOplogEntry(firstObjFound);
    if (!remoteEarliestOpTime.isOK()) {
        const auto until = _taskExecutor->now() + kFirstOplogEntryNullTimestampDenylistDuration;
        LOGV2(5579705,
              "Denylisting {candidate} due to error parsing OpTime from the oldest oplog entry "
              "for {denylistDuration} until: {denylistUntil}. Error: "
              "{error}, Entry: {oldestOplogEntry}",
              "Denylisting candidate due to error parsing OpTime from the oldest oplog entry",
              "candidate"_attr = candidate,
              "denylistDuration"_attr = kFirstOplogEntryNullTimestampDenylistDuration,
              "denylistUntil"_attr = until,
              "error"_attr = remoteEarliestOpTime.getStatus(),
              "oldestOplogEntry"_attr = redact(firstObjFound));
        _syncSourceSelector->denylistSyncSource(candidate, until);
        return OpTime();
    }

    if (remoteEarliestOpTime.getValue().isNull()) {
        // First document in remote oplog is empty.
        const auto until = _taskExecutor->now() + kFirstOplogEntryNullTimestampDenylistDuration;
        LOGV2(5579706,
              "Denylisting {candidate} due to null timestamp in first document for "
              "{denylistDuration} until: {denylistUntil}",
              "Denylisting candidate due to null timestamp in first document",
              "candidate"_attr = candidate,
              "denylistDuration"_attr = kFirstOplogEntryNullTimestampDenylistDuration,
              "denylistUntil"_attr = until);
        _syncSourceSelector->denylistSyncSource(candidate, until);
        return OpTime();
    }

    return remoteEarliestOpTime.getValue();
}

void SyncSourceResolver::_firstOplogEntryFetcherCallback(
    const StatusWith<Fetcher::QueryResponse>& queryResult,
    HostAndPort candidate,
    OpTime earliestOpTimeSeen) {
    if (_isShuttingDown()) {
        _finishCallback(Status(ErrorCodes::CallbackCanceled,
                               str::stream()
                                   << "sync source resolver shut down while probing candidate: "
                                   << candidate))
            .transitional_ignore();
        return;
    }

    if (ErrorCodes::CallbackCanceled == queryResult.getStatus()) {
        _finishCallback(queryResult.getStatus()).transitional_ignore();
        return;
    }

    if (!queryResult.isOK()) {
        // We got an error.
        const auto until = _taskExecutor->now() + kFetcherErrorDenylistDuration;
        LOGV2(5579707,
              "Denylisting {candidate} due to error: '{error}' for "
              "{denylistDuration} until: {denylistUntil}",
              "Denylisting candidate due to error",
              "candidate"_attr = candidate,
              "error"_attr = queryResult.getStatus(),
              "denylistDuration"_attr = kFetcherErrorDenylistDuration,
              "denylistUntil"_attr = until);
        _syncSourceSelector->denylistSyncSource(candidate, until);

        _chooseAndProbeNextSyncSource(earliestOpTimeSeen).transitional_ignore();
        return;
    }

    const auto& queryResponse = queryResult.getValue();
    const auto remoteEarliestOpTime = _parseRemoteEarliestOpTime(candidate, queryResponse);
    if (remoteEarliestOpTime.isNull()) {
        _chooseAndProbeNextSyncSource(earliestOpTimeSeen).transitional_ignore();
        return;
    }

    // remoteEarliestOpTime may come from a very old config, so we cannot compare their terms.
    if (_lastOpTimeFetched.getTimestamp() < remoteEarliestOpTime.getTimestamp()) {
        // We're too stale to use this sync source.
        const auto denylistDuration = kTooStaleDenylistDuration;
        const auto until = _taskExecutor->now() + denylistDuration;

        LOGV2(5579708,
              "We are too stale to use {candidate} as a sync source. Denylisting this sync source "
              "because our last fetched timestamp: {lastOpTimeFetchedTimestamp} is before "
              "their earliest timestamp: {remoteEarliestOpTimeTimestamp} for "
              "{denylistDuration} until: {denylistUntil}",
              "We are too stale to use candidate as a sync source. Denylisting this sync source "
              "because our last fetched timestamp is before their earliest timestamp",
              "candidate"_attr = candidate,
              "lastOpTimeFetchedTimestamp"_attr = _lastOpTimeFetched.getTimestamp(),
              "remoteEarliestOpTimeTimestamp"_attr = remoteEarliestOpTime.getTimestamp(),
              "denylistDuration"_attr = denylistDuration,
              "denylistUntil"_attr = until);

        _syncSourceSelector->denylistSyncSource(candidate, until);

        // If all the viable sync sources are too far ahead of us (i.e. we are "too stale" relative
        // each sync source), we will want to return the starting timestamp of the sync source
        // candidate that is closest to us. See SyncSourceResolverResponse::earliestOpTimeSeen.
        // We use "earliestOpTimeSeen" to keep track of the current minimum starting timestamp.
        if (earliestOpTimeSeen.isNull() ||
            earliestOpTimeSeen.getTimestamp() > remoteEarliestOpTime.getTimestamp()) {
            earliestOpTimeSeen = remoteEarliestOpTime;
        }

        _chooseAndProbeNextSyncSource(earliestOpTimeSeen).transitional_ignore();
        return;
    }

    // If we should not proceed with the rollback-via-refetch checks, we can safely return the
    // candidate with an uninitialized rbid.
    if (_requiredOpTime.isNull()) {
        _finishCallback(candidate, ReplicationProcess::kUninitializedRollbackId).ignore();
        return;
    }

    auto status = _scheduleRBIDRequest(candidate, earliestOpTimeSeen);
    if (!status.isOK()) {
        _finishCallback(status).ignore();
    }
}

Status SyncSourceResolver::_scheduleRBIDRequest(HostAndPort candidate, OpTime earliestOpTimeSeen) {
    // Once a work is scheduled, nothing prevents it finishing. We need the mutex to protect the
    // access of member variables after scheduling, because otherwise the scheduled callback could
    // finish and allow the destructor to fire before we access the member variables.
    stdx::lock_guard<Latch> lk(_mutex);
    if (_state == State::kShuttingDown) {
        return Status(
            ErrorCodes::CallbackCanceled,
            str::stream()
                << "sync source resolver shut down while checking rollbackId on candidate: "
                << candidate);
    }

    invariant(_state == State::kRunning);
    auto handle = _taskExecutor->scheduleRemoteCommand(
        {candidate, "admin", BSON("replSetGetRBID" << 1), nullptr, kFetcherTimeout},
        [=](const executor::TaskExecutor::RemoteCommandCallbackArgs& rbidReply) {
            _rbidRequestCallback(candidate, earliestOpTimeSeen, rbidReply);
        });
    if (!handle.isOK()) {
        return handle.getStatus();
    }

    _rbidCommandHandle = std::move(handle.getValue());
    return Status::OK();
}

void SyncSourceResolver::_rbidRequestCallback(
    HostAndPort candidate,
    OpTime earliestOpTimeSeen,
    const executor::TaskExecutor::RemoteCommandCallbackArgs& rbidReply) {
    if (rbidReply.response.status == ErrorCodes::CallbackCanceled) {
        _finishCallback(rbidReply.response.status).transitional_ignore();
        return;
    }

    int rbid = ReplicationProcess::kUninitializedRollbackId;
    try {
        uassertStatusOK(rbidReply.response.status);
        uassertStatusOK(getStatusFromCommandResult(rbidReply.response.data));
        rbid = rbidReply.response.data["rbid"].Int();
    } catch (const DBException& ex) {
        const auto until = _taskExecutor->now() + kFetcherErrorDenylistDuration;
        LOGV2(5579709,
              "Denylisting {candidate} due to error: '{error}' for {denylistDuration} "
              "until: {denylistUntil}",
              "Denylisting candidate due to error",
              "candidate"_attr = candidate,
              "error"_attr = ex,
              "denylistDuration"_attr = kFetcherErrorDenylistDuration,
              "denylistUntil"_attr = until);
        _syncSourceSelector->denylistSyncSource(candidate, until);
        _chooseAndProbeNextSyncSource(earliestOpTimeSeen).transitional_ignore();
        return;
    }

    // Schedule fetcher to look for '_requiredOpTime' in the remote oplog.
    // Unittest requires that this kind of failure be handled specially.
    auto status = _scheduleFetcher(_makeRequiredOpTimeFetcher(candidate, earliestOpTimeSeen, rbid));
    if (!status.isOK()) {
        _finishCallback(status).ignore();
    }
}

Status SyncSourceResolver::_compareRequiredOpTimeWithQueryResponse(
    const Fetcher::QueryResponse& queryResponse) {
    if (queryResponse.documents.empty()) {
        return Status(
            ErrorCodes::NoMatchingDocument,
            "remote oplog does not contain entry with optime matching our required optime");
    }
    const OplogEntry oplogEntry(queryResponse.documents.front());
    const auto opTime = oplogEntry.getOpTime();
    if (_requiredOpTime != opTime) {
        return Status(ErrorCodes::BadValue,
                      str::stream()
                          << "remote oplog contain entry with matching timestamp "
                          << opTime.getTimestamp().toString() << " but optime " << opTime.toString()
                          << " does not "
                             "match our required optime");
    }
    if (_requiredOpTime.getTerm() != opTime.getTerm()) {
        return Status(ErrorCodes::BadValue,
                      str::stream() << "remote oplog contain entry with term " << opTime.getTerm()
                                    << " that does not "
                                       "match the term in our required optime");
    }
    return Status::OK();
}

void SyncSourceResolver::_requiredOpTimeFetcherCallback(
    const StatusWith<Fetcher::QueryResponse>& queryResult,
    HostAndPort candidate,
    OpTime earliestOpTimeSeen,
    int rbid) {
    if (_isShuttingDown()) {
        _finishCallback(Status(ErrorCodes::CallbackCanceled,
                               str::stream() << "sync source resolver shut down while looking for "
                                                "required optime "
                                             << _requiredOpTime.toString()
                                             << " in candidate's oplog: " << candidate))
            .transitional_ignore();
        return;
    }

    if (ErrorCodes::CallbackCanceled == queryResult.getStatus()) {
        _finishCallback(queryResult.getStatus()).transitional_ignore();
        return;
    }

    if (!queryResult.isOK()) {
        // We got an error.
        const auto until = _taskExecutor->now() + kFetcherErrorDenylistDuration;
        LOGV2(5579710,
              "Denylisting {candidate} due to required optime fetcher error: "
              "'{error}' for {denylistDuration} until: {denylistUntil}. "
              "required optime: {requiredOpTime}",
              "Denylisting candidate due to required optime fetcher error",
              "candidate"_attr = candidate,
              "error"_attr = queryResult.getStatus(),
              "denylistDuration"_attr = kFetcherErrorDenylistDuration,
              "denylistUntil"_attr = until,
              "requiredOpTime"_attr = _requiredOpTime);
        _syncSourceSelector->denylistSyncSource(candidate, until);

        _chooseAndProbeNextSyncSource(earliestOpTimeSeen).transitional_ignore();
        return;
    }

    const auto& queryResponse = queryResult.getValue();
    auto status = _compareRequiredOpTimeWithQueryResponse(queryResponse);
    if (!status.isOK()) {
        const auto until = _taskExecutor->now() + kNoRequiredOpTimeDenylistDuration;
        LOGV2_WARNING(
            5579711,
            "We cannot use {candidate} as a sync source because it does not contain the necessary "
            "operations for us to reach a consistent state: {error} last fetched optime: "
            "{lastOpTimeFetched}. required optime: {requiredOpTime}. Denylisting this sync source "
            "for {denylistDuration} until: {denylistUntil}",
            "We cannot use candidate as a sync source because it does not contain the necessary "
            "operations for us to reach a consistent state. Denylisting this sync source",
            "candidate"_attr = candidate.toString(),
            "error"_attr = status,
            "lastOpTimeFetched"_attr = _lastOpTimeFetched,
            "requiredOpTime"_attr = _requiredOpTime,
            "denylistDuration"_attr = kNoRequiredOpTimeDenylistDuration,
            "denylistUntil"_attr = until);
        _syncSourceSelector->denylistSyncSource(candidate, until);

        _chooseAndProbeNextSyncSource(earliestOpTimeSeen).transitional_ignore();
        return;
    }

    _finishCallback(candidate, rbid).ignore();
}

Status SyncSourceResolver::_chooseAndProbeNextSyncSource(OpTime earliestOpTimeSeen) {
    auto candidateResult = _chooseNewSyncSource();
    if (!candidateResult.isOK()) {
        return _finishCallback(candidateResult.getStatus());
    }

    if (candidateResult.getValue().empty()) {
        if (earliestOpTimeSeen.isNull()) {
            return _finishCallback(candidateResult.getValue(),
                                   ReplicationProcess::kUninitializedRollbackId);
        }

        SyncSourceResolverResponse response;
        response.syncSourceStatus = {ErrorCodes::TooStaleToSyncFromSource, "too stale to catch up"};
        response.earliestOpTimeSeen = earliestOpTimeSeen;
        return _finishCallback(response);
    }

    auto status = _scheduleFetcher(
        _makeFirstOplogEntryFetcher(candidateResult.getValue(), earliestOpTimeSeen));
    if (!status.isOK()) {
        return _finishCallback(status);
    }

    return Status::OK();
}

Status SyncSourceResolver::_finishCallback(HostAndPort hostAndPort, int rbid) {
    SyncSourceResolverResponse response;
    response.syncSourceStatus = std::move(hostAndPort);
    response.rbid = rbid;
    return _finishCallback(response);
}

Status SyncSourceResolver::_finishCallback(Status status) {
    invariant(!status.isOK());
    SyncSourceResolverResponse response;
    response.syncSourceStatus = std::move(status);
    return _finishCallback(response);
}

Status SyncSourceResolver::_finishCallback(const SyncSourceResolverResponse& response) {
    try {
        _onCompletion(response);
    } catch (...) {
        LOGV2_WARNING(21775,
                      "sync source resolver finish callback threw exception: {error}",
                      "Sync source resolver finish callback threw exception",
                      "error"_attr = exceptionToStatus());
    }

    stdx::lock_guard<Latch> lock(_mutex);
    invariant(_state != State::kComplete);
    _state = State::kComplete;
    _condition.notify_all();
    return response.syncSourceStatus.getStatus();
}

}  // namespace repl
}  // namespace mongo