summaryrefslogtreecommitdiff
path: root/src/mongo/db/s/collection_sharding_runtime.cpp
blob: 35e65b1dc8b99f83825730619e115df0f96cdeab (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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
/**
 *    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/db/s/collection_sharding_runtime.h"

#include "mongo/db/catalog_raii.h"
#include "mongo/db/global_settings.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/query/query_feature_flags_gen.h"
#include "mongo/db/query/sbe_plan_cache.h"
#include "mongo/db/repl/primary_only_service.h"
#include "mongo/db/s/operation_sharding_state.h"
#include "mongo/db/s/range_deleter_service.h"
#include "mongo/db/s/sharding_runtime_d_params_gen.h"
#include "mongo/db/s/sharding_state.h"
#include "mongo/logv2/log.h"
#include "mongo/s/grid.h"
#include "mongo/s/sharding_feature_flags_gen.h"
#include "mongo/util/duration.h"

#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kSharding

namespace mongo {
namespace {

class UnshardedCollection : public ScopedCollectionDescription::Impl {
public:
    UnshardedCollection() = default;

    const CollectionMetadata& get() override {
        return _metadata;
    }

private:
    CollectionMetadata _metadata;
};

const auto kUnshardedCollection = std::make_shared<UnshardedCollection>();

boost::optional<ShardVersion> getOperationReceivedVersion(OperationContext* opCtx,
                                                          const NamespaceString& nss) {
    // If there is a version attached to the OperationContext, use it as the received version.
    if (OperationShardingState::isComingFromRouter(opCtx)) {
        return OperationShardingState::get(opCtx).getShardVersion(nss);
    }

    // There is no shard version information on the 'opCtx'. This means that the operation
    // represented by 'opCtx' is unversioned, and the shard version is always OK for unversioned
    // operations.
    return boost::none;
}

}  // namespace

CollectionShardingRuntime::ScopedCollectionShardingRuntime::ScopedCollectionShardingRuntime(
    ScopedCollectionShardingState&& scopedCss)
    : _scopedCss(std::move(scopedCss)) {}

CollectionShardingRuntime::CollectionShardingRuntime(
    ServiceContext* service,
    NamespaceString nss,
    std::shared_ptr<executor::TaskExecutor> rangeDeleterExecutor)
    : _serviceContext(service),
      _nss(std::move(nss)),
      _rangeDeleterExecutor(std::move(rangeDeleterExecutor)),
      _metadataType(_nss.isNamespaceAlwaysUnsharded() ? MetadataType::kUnsharded
                                                      : MetadataType::kUnknown) {}

CollectionShardingRuntime::ScopedCollectionShardingRuntime
CollectionShardingRuntime::assertCollectionLockedAndAcquire(OperationContext* opCtx,
                                                            const NamespaceString& nss,
                                                            CSRAcquisitionMode mode) {
    dassert(opCtx->lockState()->isCollectionLockedForMode(nss, MODE_IS));
    return ScopedCollectionShardingRuntime(
        ScopedCollectionShardingState::acquireScopedCollectionShardingState(
            opCtx, nss, mode == CSRAcquisitionMode::kShared ? MODE_IS : MODE_X));
}

ScopedCollectionFilter CollectionShardingRuntime::getOwnershipFilter(
    OperationContext* opCtx,
    OrphanCleanupPolicy orphanCleanupPolicy,
    bool supportNonVersionedOperations) {
    boost::optional<ShardVersion> optReceivedShardVersion = boost::none;
    if (!supportNonVersionedOperations) {
        optReceivedShardVersion = getOperationReceivedVersion(opCtx, _nss);
        // No operations should be calling getOwnershipFilter without a shard version
        tassert(7032300,
                "getOwnershipFilter called by operation that doesn't specify shard version",
                optReceivedShardVersion);
    }

    auto metadata =
        _getMetadataWithVersionCheckAt(opCtx,
                                       repl::ReadConcernArgs::get(opCtx).getArgsAtClusterTime(),
                                       supportNonVersionedOperations);

    if (!supportNonVersionedOperations) {
        tassert(7032301,
                "For sharded collections getOwnershipFilter cannot be relied on without a valid "
                "shard version",
                !ShardVersion::isIgnoredVersion(*optReceivedShardVersion) ||
                    !metadata->get().allowMigrations() || !metadata->get().isSharded());
    }

    return {std::move(metadata)};
}

ScopedCollectionDescription CollectionShardingRuntime::getCollectionDescription(
    OperationContext* opCtx) {
    // If the server has been started with --shardsvr, but hasn't been added to a cluster we should
    // consider all collections as unsharded
    if (!ShardingState::get(opCtx)->enabled())
        return {kUnshardedCollection};

    // Present the collection as unsharded to internal or direct commands against shards
    if (!OperationShardingState::isComingFromRouter(opCtx))
        return {kUnshardedCollection};

    auto& oss = OperationShardingState::get(opCtx);

    auto optMetadata = _getCurrentMetadataIfKnown(boost::none);
    const auto receivedShardVersion{oss.getShardVersion(_nss)};
    uassert(
        StaleConfigInfo(_nss,
                        receivedShardVersion ? *receivedShardVersion : ShardVersion::IGNORED(),
                        boost::none /* wantedVersion */,
                        ShardingState::get(_serviceContext)->shardId()),
        str::stream() << "sharding status of collection " << _nss.ns()
                      << " is not currently available for description and needs to be recovered "
                      << "from the config server",
        optMetadata);

    return {std::move(optMetadata)};
}

boost::optional<CollectionMetadata> CollectionShardingRuntime::getCurrentMetadataIfKnown() {
    auto optMetadata = _getCurrentMetadataIfKnown(boost::none);
    if (!optMetadata)
        return boost::none;
    return optMetadata->get();
}

void CollectionShardingRuntime::checkShardVersionOrThrow(OperationContext* opCtx) {
    (void)_getMetadataWithVersionCheckAt(opCtx, boost::none);
}

void CollectionShardingRuntime::enterCriticalSectionCatchUpPhase(const BSONObj& reason) {
    _critSec.enterCriticalSectionCatchUpPhase(reason);

    if (_shardVersionInRecoverOrRefresh) {
        _shardVersionInRecoverOrRefresh->cancellationSource.cancel();
    }
}

void CollectionShardingRuntime::enterCriticalSectionCommitPhase(const BSONObj& reason) {
    _critSec.enterCriticalSectionCommitPhase(reason);
}

void CollectionShardingRuntime::rollbackCriticalSectionCommitPhaseToCatchUpPhase(
    const BSONObj& reason) {
    _critSec.rollbackCriticalSectionCommitPhaseToCatchUpPhase(reason);
}

void CollectionShardingRuntime::exitCriticalSection(const BSONObj& reason) {
    _critSec.exitCriticalSection(reason);
}

void CollectionShardingRuntime::exitCriticalSectionNoChecks() {
    _critSec.exitCriticalSectionNoChecks();
}

boost::optional<SharedSemiFuture<void>> CollectionShardingRuntime::getCriticalSectionSignal(
    OperationContext* opCtx, ShardingMigrationCriticalSection::Operation op) {
    return _critSec.getSignal(op);
}

void CollectionShardingRuntime::setFilteringMetadata(OperationContext* opCtx,
                                                     CollectionMetadata newMetadata) {
    tassert(7032302,
            str::stream() << "Namespace " << _nss.ns() << " must never be sharded.",
            !newMetadata.isSharded() || !_nss.isNamespaceAlwaysUnsharded());

    stdx::lock_guard lk(_metadataManagerLock);

    // If the collection was sharded and the new metadata represents a new collection we might need
    // to clean up some sharding-related state
    if (_metadataManager) {
        const auto oldShardVersion = _metadataManager->getActiveShardVersion();
        const auto newShardVersion = newMetadata.getShardVersion();
        if (!oldShardVersion.isSameCollection(newShardVersion))
            _cleanupBeforeInstallingNewCollectionMetadata(lk, opCtx);
    }

    if (!newMetadata.isSharded()) {
        LOGV2(21917,
              "Marking collection {namespace} as unsharded",
              "Marking collection as unsharded",
              "namespace"_attr = _nss.ns());
        _metadataType = MetadataType::kUnsharded;
        _metadataManager.reset();
        ++_numMetadataManagerChanges;
        return;
    }

    // At this point we know that the new metadata is associated to a sharded collection.
    _metadataType = MetadataType::kSharded;

    if (!_metadataManager || !newMetadata.uuidMatches(_metadataManager->getCollectionUuid())) {
        _metadataManager = std::make_shared<MetadataManager>(
            opCtx->getServiceContext(), _nss, _rangeDeleterExecutor, newMetadata);
        ++_numMetadataManagerChanges;
    } else {
        _metadataManager->setFilteringMetadata(std::move(newMetadata));
    }
}

void CollectionShardingRuntime::_clearFilteringMetadata(OperationContext* opCtx,
                                                        bool collIsDropped) {
    if (_shardVersionInRecoverOrRefresh) {
        _shardVersionInRecoverOrRefresh->cancellationSource.cancel();
    }

    stdx::lock_guard lk(_metadataManagerLock);
    if (!_nss.isNamespaceAlwaysUnsharded()) {
        LOGV2_DEBUG(4798530,
                    1,
                    "Clearing metadata for collection {namespace}",
                    "Clearing collection metadata",
                    "namespace"_attr = _nss,
                    "collIsDropped"_attr = collIsDropped);

        // If the collection is sharded and it's being dropped we might need to clean up some state.
        if (collIsDropped)
            _cleanupBeforeInstallingNewCollectionMetadata(lk, opCtx);

        _metadataType = MetadataType::kUnknown;
        if (collIsDropped)
            _metadataManager.reset();
    }
}

void CollectionShardingRuntime::clearFilteringMetadata(OperationContext* opCtx) {
    _clearFilteringMetadata(opCtx, /* collIsDropped */ false);
}

void CollectionShardingRuntime::clearFilteringMetadataForDroppedCollection(
    OperationContext* opCtx) {
    _clearFilteringMetadata(opCtx, /* collIsDropped */ true);
}

SharedSemiFuture<void> CollectionShardingRuntime::cleanUpRange(ChunkRange const& range,
                                                               CleanWhen when) {
    if (!feature_flags::gRangeDeleterService.isEnabledAndIgnoreFCV()) {
        stdx::lock_guard lk(_metadataManagerLock);
        invariant(_metadataType == MetadataType::kSharded);
        return _metadataManager->cleanUpRange(range, when == kDelayed);
    }

    // This method must never be called if the range deleter service feature flag is enabled
    MONGO_UNREACHABLE;
}

Status CollectionShardingRuntime::waitForClean(OperationContext* opCtx,
                                               const NamespaceString& nss,
                                               const UUID& collectionUuid,
                                               ChunkRange orphanRange,
                                               Date_t deadline) {
    while (true) {
        const StatusWith<SharedSemiFuture<void>> swOrphanCleanupFuture =
            [&]() -> StatusWith<SharedSemiFuture<void>> {
            AutoGetCollection autoColl(opCtx, nss, MODE_IX);
            auto self = CollectionShardingRuntime::assertCollectionLockedAndAcquire(
                opCtx, nss, CSRAcquisitionMode::kShared);
            stdx::lock_guard lk(self->_metadataManagerLock);

            // If the metadata was reset, or the collection was dropped and recreated since the
            // metadata manager was created, return an error.
            if (self->_metadataType != MetadataType::kSharded ||
                (collectionUuid != self->_metadataManager->getCollectionUuid())) {
                return {ErrorCodes::ConflictingOperationInProgress,
                        "Collection being migrated was dropped and created or otherwise had its "
                        "metadata reset"};
            }

            if (feature_flags::gRangeDeleterService.isEnabledAndIgnoreFCV()) {
                return RangeDeleterService::get(opCtx)->getOverlappingRangeDeletionsFuture(
                    self->_metadataManager->getCollectionUuid(), orphanRange);
            } else {
                return self->_metadataManager->trackOrphanedDataCleanup(orphanRange);
            }
        }();

        if (!swOrphanCleanupFuture.isOK()) {
            return swOrphanCleanupFuture.getStatus();
        }

        auto orphanCleanupFuture = std::move(swOrphanCleanupFuture.getValue());
        if (orphanCleanupFuture.isReady()) {
            LOGV2_OPTIONS(21918,
                          {logv2::LogComponent::kShardingMigration},
                          "Finished waiting for deletion of {namespace} range {orphanRange}",
                          "Finished waiting for deletion of orphans",
                          "namespace"_attr = nss.ns(),
                          "orphanRange"_attr = redact(orphanRange.toString()));
            return Status::OK();
        }

        LOGV2_OPTIONS(21919,
                      {logv2::LogComponent::kShardingMigration},
                      "Waiting for deletion of {namespace} range {orphanRange}",
                      "Waiting for deletion of orphans",
                      "namespace"_attr = nss.ns(),
                      "orphanRange"_attr = orphanRange);
        try {
            opCtx->runWithDeadline(
                deadline, ErrorCodes::ExceededTimeLimit, [&] { orphanCleanupFuture.get(opCtx); });
        } catch (const DBException& ex) {
            auto result = ex.toStatus();
            // Swallow RangeDeletionAbandonedBecauseCollectionWithUUIDDoesNotExist error since the
            // collection could either never exist or get dropped directly from the shard after the
            // range deletion task got scheduled.
            if (result != ErrorCodes::RangeDeletionAbandonedBecauseCollectionWithUUIDDoesNotExist) {
                return result.withContext(str::stream() << "Failed to delete orphaned " << nss.ns()
                                                        << " range " << orphanRange.toString());
            }
        }
    }

    MONGO_UNREACHABLE;
}

SharedSemiFuture<void> CollectionShardingRuntime::getOngoingQueriesCompletionFuture(
    const UUID& collectionUuid, ChunkRange const& range) {
    stdx::lock_guard lk(_metadataManagerLock);

    if (!_metadataManager || _metadataManager->getCollectionUuid() != collectionUuid) {
        return SemiFuture<void>::makeReady().share();
    }
    return _metadataManager->getOngoingQueriesCompletionFuture(range);
}


std::shared_ptr<ScopedCollectionDescription::Impl>
CollectionShardingRuntime::_getCurrentMetadataIfKnown(
    const boost::optional<LogicalTime>& atClusterTime) {
    stdx::lock_guard lk(_metadataManagerLock);
    switch (_metadataType) {
        case MetadataType::kUnknown:
            // Until user collections can be sharded in serverless, the sessions collection will be
            // the only sharded collection.
            if (getGlobalReplSettings().isServerless() &&
                _nss != NamespaceString::kLogicalSessionsNamespace) {
                return kUnshardedCollection;
            }
            return nullptr;
        case MetadataType::kUnsharded:
            return kUnshardedCollection;
        case MetadataType::kSharded:
            return _metadataManager->getActiveMetadata(atClusterTime);
    };
    MONGO_UNREACHABLE;
}

std::shared_ptr<ScopedCollectionDescription::Impl>
CollectionShardingRuntime::_getMetadataWithVersionCheckAt(
    OperationContext* opCtx,
    const boost::optional<mongo::LogicalTime>& atClusterTime,
    bool supportNonVersionedOperations) {
    // If the server has been started with --shardsvr, but hasn't been added to a cluster we should
    // consider all collections as unsharded
    if (!ShardingState::get(opCtx)->enabled())
        return kUnshardedCollection;

    if (repl::ReadConcernArgs::get(opCtx).getLevel() ==
        repl::ReadConcernLevel::kAvailableReadConcern)
        return kUnshardedCollection;

    const auto optReceivedShardVersion = getOperationReceivedVersion(opCtx, _nss);
    if (!optReceivedShardVersion && !supportNonVersionedOperations)
        return kUnshardedCollection;

    // Assume that the received shard version was IGNORED if the current operation wasn't versioned
    const auto& receivedShardVersion =
        optReceivedShardVersion ? *optReceivedShardVersion : ShardVersion::IGNORED();

    {
        auto criticalSectionSignal = _critSec.getSignal(
            opCtx->lockState()->isWriteLocked() ? ShardingMigrationCriticalSection::kWrite
                                                : ShardingMigrationCriticalSection::kRead);
        std::string reason = _critSec.getReason() ? _critSec.getReason()->toString() : "unknown";
        uassert(StaleConfigInfo(_nss,
                                receivedShardVersion,
                                boost::none /* wantedVersion */,
                                ShardingState::get(opCtx)->shardId(),
                                std::move(criticalSectionSignal),
                                opCtx->lockState()->isWriteLocked()
                                    ? StaleConfigInfo::OperationType::kWrite
                                    : StaleConfigInfo::OperationType::kRead),
                str::stream() << "The critical section for " << _nss.ns()
                              << " is acquired with reason: " << reason,
                !criticalSectionSignal);
    }

    auto optCurrentMetadata = _getCurrentMetadataIfKnown(atClusterTime);
    uassert(StaleConfigInfo(_nss,
                            receivedShardVersion,
                            boost::none /* wantedVersion */,
                            ShardingState::get(opCtx)->shardId()),
            str::stream() << "sharding status of collection " << _nss.ns()
                          << " is not currently known and needs to be recovered",
            optCurrentMetadata);

    const auto& currentMetadata = optCurrentMetadata->get();

    const auto wantedPlacementVersion = currentMetadata.getShardVersion();
    const auto wantedShardVersion =
        ShardVersion(wantedPlacementVersion, boost::optional<CollectionIndexes>(boost::none));
    const ChunkVersion receivedPlacementVersion = receivedShardVersion.placementVersion();

    if (wantedPlacementVersion.isWriteCompatibleWith(receivedPlacementVersion) ||
        receivedShardVersion == ShardVersion::IGNORED())
        return optCurrentMetadata;

    StaleConfigInfo sci(
        _nss, receivedShardVersion, wantedShardVersion, ShardingState::get(opCtx)->shardId());

    uassert(std::move(sci),
            str::stream() << "timestamp mismatch detected for " << _nss.ns(),
            wantedPlacementVersion.isSameCollection(receivedPlacementVersion));

    if (!wantedPlacementVersion.isSet() && receivedPlacementVersion.isSet()) {
        uasserted(std::move(sci),
                  str::stream() << "this shard no longer contains chunks for " << _nss.ns() << ", "
                                << "the collection may have been dropped");
    }

    if (wantedPlacementVersion.isSet() && !receivedPlacementVersion.isSet()) {
        uasserted(std::move(sci),
                  str::stream() << "this shard contains chunks for " << _nss.ns() << ", "
                                << "but the client expects unsharded collection");
    }

    if (wantedPlacementVersion.majorVersion() != receivedPlacementVersion.majorVersion()) {
        // Could be > or < - wanted is > if this is the source of a migration, wanted < if this is
        // the target of a migration
        uasserted(std::move(sci), str::stream() << "version mismatch detected for " << _nss.ns());
    }

    // Those are all the reasons the versions can mismatch
    MONGO_UNREACHABLE;
}

void CollectionShardingRuntime::appendShardVersion(BSONObjBuilder* builder) {
    auto optCollDescr = getCurrentMetadataIfKnown();
    if (optCollDescr) {
        BSONObjBuilder versionBuilder(builder->subobjStart(_nss.ns()));
        versionBuilder.appendTimestamp("placementVersion",
                                       optCollDescr->getShardVersion().toLong());
        versionBuilder.append("timestamp", optCollDescr->getShardVersion().getTimestamp());
    }
}

size_t CollectionShardingRuntime::numberOfRangesScheduledForDeletion() const {
    stdx::lock_guard lk(_metadataManagerLock);
    if (_metadataType == MetadataType::kSharded) {
        return _metadataManager->numberOfRangesScheduledForDeletion();
    }
    return 0;
}


void CollectionShardingRuntime::setShardVersionRecoverRefreshFuture(
    SharedSemiFuture<void> future, CancellationSource cancellationSource) {
    invariant(!_shardVersionInRecoverOrRefresh);
    _shardVersionInRecoverOrRefresh.emplace(std::move(future), std::move(cancellationSource));
}

boost::optional<SharedSemiFuture<void>>
CollectionShardingRuntime::getShardVersionRecoverRefreshFuture(OperationContext* opCtx) {
    return _shardVersionInRecoverOrRefresh
        ? boost::optional<SharedSemiFuture<void>>(_shardVersionInRecoverOrRefresh->future)
        : boost::none;
}

void CollectionShardingRuntime::resetShardVersionRecoverRefreshFuture() {
    invariant(_shardVersionInRecoverOrRefresh);
    _shardVersionInRecoverOrRefresh = boost::none;
}

boost::optional<CollectionIndexes> CollectionShardingRuntime::getCollectionIndexes(
    OperationContext* opCtx) {
    return _globalIndexesInfo ? boost::make_optional(_globalIndexesInfo->getCollectionIndexes())
                              : boost::none;
}

boost::optional<GlobalIndexesCache>& CollectionShardingRuntime::getIndexes(
    OperationContext* opCtx) {
    return _globalIndexesInfo;
}

void CollectionShardingRuntime::addIndex(OperationContext* opCtx,
                                         const IndexCatalogType& index,
                                         const CollectionIndexes& collectionIndexes) {
    if (_globalIndexesInfo) {
        _globalIndexesInfo->add(index, collectionIndexes);
    } else {
        IndexCatalogTypeMap indexMap;
        indexMap.emplace(index.getName(), index);
        _globalIndexesInfo.emplace(collectionIndexes, std::move(indexMap));
    }
}

void CollectionShardingRuntime::removeIndex(OperationContext* opCtx,
                                            const std::string& name,
                                            const CollectionIndexes& collectionIndexes) {
    tassert(
        7019500, "Index information does not exist on CSR", _globalIndexesInfo.is_initialized());
    _globalIndexesInfo->remove(name, collectionIndexes);
}

void CollectionShardingRuntime::clearIndexes(OperationContext* opCtx) {
    _globalIndexesInfo = boost::none;
}

void CollectionShardingRuntime::replaceIndexes(OperationContext* opCtx,
                                               const std::vector<IndexCatalogType>& indexes,
                                               const CollectionIndexes& collectionIndexes) {
    if (_globalIndexesInfo) {
        _globalIndexesInfo = boost::none;
    }
    IndexCatalogTypeMap indexMap;
    for (const auto& index : indexes) {
        indexMap.emplace(index.getName(), index);
    }
    _globalIndexesInfo.emplace(collectionIndexes, std::move(indexMap));
}

CollectionCriticalSection::CollectionCriticalSection(OperationContext* opCtx,
                                                     NamespaceString nss,
                                                     BSONObj reason)
    : _opCtx(opCtx), _nss(std::move(nss)), _reason(std::move(reason)) {
    // This acquisition is performed with collection lock MODE_S in order to ensure that any ongoing
    // writes have completed and become visible
    AutoGetCollection autoColl(_opCtx,
                               _nss,
                               MODE_S,
                               AutoGetCollection::Options{}.deadline(
                                   _opCtx->getServiceContext()->getPreciseClockSource()->now() +
                                   Milliseconds(migrationLockAcquisitionMaxWaitMS.load())));
    auto scopedCsr = CollectionShardingRuntime::assertCollectionLockedAndAcquire(
        _opCtx, _nss, CSRAcquisitionMode::kExclusive);
    tassert(7032305,
            "Collection metadata unknown when entering critical section",
            scopedCsr->getCurrentMetadataIfKnown());
    scopedCsr->enterCriticalSectionCatchUpPhase(_reason);
}

CollectionCriticalSection::~CollectionCriticalSection() {
    // TODO (SERVER-71444): Fix to be interruptible or document exception.
    UninterruptibleLockGuard noInterrupt(_opCtx->lockState());  // NOLINT.
    AutoGetCollection autoColl(_opCtx, _nss, MODE_IX);
    auto scopedCsr = CollectionShardingRuntime::assertCollectionLockedAndAcquire(
        _opCtx, _nss, CSRAcquisitionMode::kExclusive);
    scopedCsr->exitCriticalSection(_reason);
}

void CollectionCriticalSection::enterCommitPhase() {
    AutoGetCollection autoColl(_opCtx,
                               _nss,
                               MODE_X,
                               AutoGetCollection::Options{}.deadline(
                                   _opCtx->getServiceContext()->getPreciseClockSource()->now() +
                                   Milliseconds(migrationLockAcquisitionMaxWaitMS.load())));
    auto scopedCsr = CollectionShardingRuntime::assertCollectionLockedAndAcquire(
        _opCtx, _nss, CSRAcquisitionMode::kExclusive);
    tassert(7032304,
            "Collection metadata unknown when entering critical section commit phase",
            scopedCsr->getCurrentMetadataIfKnown());
    scopedCsr->enterCriticalSectionCommitPhase(_reason);
}

void CollectionShardingRuntime::_cleanupBeforeInstallingNewCollectionMetadata(
    WithLock, OperationContext* opCtx) {
    if (!_metadataManager) {
        // The old collection metadata was unsharded, nothing to cleanup so far.
        return;
    }

    if (feature_flags::gFeatureFlagSbeFull.isEnabledAndIgnoreFCV()) {
        const auto oldUUID = _metadataManager->getCollectionUuid();
        const auto oldShardVersion = _metadataManager->getActiveShardVersion();
        ExecutorFuture<void>{Grid::get(opCtx)->getExecutorPool()->getFixedExecutor()}
            .then([svcCtx{opCtx->getServiceContext()}, oldUUID, oldShardVersion] {
                ThreadClient tc{"CleanUpShardedMetadata", svcCtx};
                {
                    stdx::lock_guard<Client> lk{*tc.get()};
                    tc->setSystemOperationKillableByStepdown(lk);
                }
                auto uniqueOpCtx{tc->makeOperationContext()};
                auto opCtx{uniqueOpCtx.get()};

                try {
                    auto& planCache = sbe::getPlanCache(opCtx);
                    planCache.removeIf([&](const sbe::PlanCacheKey& key,
                                           const sbe::PlanCacheEntry& entry) -> bool {
                        const auto matchingCollState =
                            [&](const sbe::PlanCacheKeyCollectionState& entryCollState) {
                                return entryCollState.uuid == oldUUID &&
                                    entryCollState.shardVersion &&
                                    entryCollState.shardVersion->epoch == oldShardVersion.epoch() &&
                                    entryCollState.shardVersion->ts ==
                                    oldShardVersion.getTimestamp();
                            };

                        // Check whether the main collection of this plan is the one being removed
                        if (matchingCollState(key.getMainCollectionState()))
                            return true;

                        // Check whether a secondary collection is the one being removed
                        for (const auto& secCollState : key.getSecondaryCollectionStates()) {
                            if (matchingCollState(secCollState))
                                return true;
                        }

                        return false;
                    });
                } catch (const DBException& ex) {
                    LOGV2(6549200,
                          "Interrupted deferred clean up of sharded metadata",
                          "error"_attr = redact(ex));
                }
            })
            .getAsync([](auto) {});
    }
}

}  // namespace mongo