summaryrefslogtreecommitdiff
path: root/src/mongo/db/pipeline/change_stream_expired_pre_image_remover_test.cpp
blob: 6c1c20f156cb61f4cc5bf5ea892ebdf6e7e9d420 (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
/**
 *    Copyright (C) 2022-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/change_stream_options_manager.h"

#include "mongo/db/catalog_raii.h"
#include "mongo/db/change_stream_pre_image_util.h"
#include "mongo/db/change_stream_pre_images_collection_manager.h"
#include "mongo/db/change_stream_pre_images_truncate_markers.h"
#include "mongo/db/change_stream_serverless_helpers.h"
#include "mongo/db/change_streams_cluster_parameter_gen.h"
#include "mongo/db/concurrency/exception_util.h"
#include "mongo/db/op_observer/op_observer_impl.h"
#include "mongo/db/op_observer/op_observer_registry.h"
#include "mongo/db/op_observer/oplog_writer_impl.h"
#include "mongo/db/pipeline/change_stream_expired_pre_image_remover.h"
#include "mongo/db/pipeline/change_stream_preimage_gen.h"
#include "mongo/db/repl/replication_coordinator_mock.h"
#include "mongo/db/repl/storage_interface_impl.h"
#include "mongo/db/service_context_d_test_fixture.h"
#include "mongo/db/service_context_test_fixture.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/assert_util.h"

namespace mongo {

namespace {
std::unique_ptr<ChangeStreamOptions> populateChangeStreamPreImageOptions(
    stdx::variant<std::string, std::int64_t> expireAfterSeconds) {
    PreAndPostImagesOptions preAndPostImagesOptions;
    preAndPostImagesOptions.setExpireAfterSeconds(expireAfterSeconds);

    auto changeStreamOptions = std::make_unique<ChangeStreamOptions>();
    changeStreamOptions->setPreAndPostImages(std::move(preAndPostImagesOptions));

    return changeStreamOptions;
}

void setChangeStreamOptionsToManager(OperationContext* opCtx,
                                     ChangeStreamOptions& changeStreamOptions) {
    auto& changeStreamOptionsManager = ChangeStreamOptionsManager::get(opCtx);
    ASSERT_EQ(changeStreamOptionsManager.setOptions(opCtx, changeStreamOptions).getStatus(),
              ErrorCodes::OK);
}

class ChangeStreamPreImageExpirationPolicyTest : public ServiceContextTest {
public:
    ChangeStreamPreImageExpirationPolicyTest() {
        ChangeStreamOptionsManager::create(getServiceContext());
    }
};

TEST_F(ChangeStreamPreImageExpirationPolicyTest, getPreImageExpirationTimeWithValidIntegralValue) {
    auto opCtx = cc().makeOperationContext();
    const int64_t expireAfterSeconds = 10;

    auto changeStreamOptions = populateChangeStreamPreImageOptions(expireAfterSeconds);
    setChangeStreamOptionsToManager(opCtx.get(), *changeStreamOptions.get());

    auto currentTime = Date_t::now();
    auto receivedExpireAfterSeconds =
        change_stream_pre_image_util::getPreImageExpirationTime(opCtx.get(), currentTime);
    ASSERT(receivedExpireAfterSeconds);
    ASSERT_EQ(*receivedExpireAfterSeconds, currentTime - Seconds(expireAfterSeconds));
}

TEST_F(ChangeStreamPreImageExpirationPolicyTest, getPreImageExpirationTimeWithUnsetValue) {
    auto opCtx = cc().makeOperationContext();

    auto currentTime = Date_t::now();
    auto receivedExpireAfterSeconds =
        change_stream_pre_image_util::getPreImageExpirationTime(opCtx.get(), currentTime);
    ASSERT_FALSE(receivedExpireAfterSeconds);
}

TEST_F(ChangeStreamPreImageExpirationPolicyTest, getPreImageExpirationTimeWithOffValue) {
    auto opCtx = cc().makeOperationContext();

    auto changeStreamOptions = populateChangeStreamPreImageOptions("off");
    setChangeStreamOptionsToManager(opCtx.get(), *changeStreamOptions.get());

    auto currentTime = Date_t::now();
    auto receivedExpireAfterSeconds =
        change_stream_pre_image_util::getPreImageExpirationTime(opCtx.get(), currentTime);
    ASSERT_FALSE(receivedExpireAfterSeconds);
}
}  // namespace

class PreImagesTruncateMarkersPerCollectionTest : public ServiceContextMongoDTest {
protected:
    explicit PreImagesTruncateMarkersPerCollectionTest() : ServiceContextMongoDTest() {
        ChangeStreamOptionsManager::create(getServiceContext());
    }

    virtual void setUp() override {
        ServiceContextMongoDTest::setUp();

        auto service = getServiceContext();
        auto opCtx = cc().makeOperationContext();

        // Use the full StorageInterfaceImpl so the earliest oplog entry Timestamp is not the
        // minimum Timestamp.
        repl::StorageInterface::set(service, std::make_unique<repl::StorageInterfaceImpl>());

        // Set up ReplicationCoordinator and create oplog. The earliest oplog entry Timestamp is
        // required for computing whether a truncate marker is expired.
        repl::ReplicationCoordinator::set(
            service, std::make_unique<repl::ReplicationCoordinatorMock>(service));
        repl::createOplog(opCtx.get());

        // Ensure that we are primary.
        auto replCoord = repl::ReplicationCoordinator::get(opCtx.get());
        ASSERT_OK(replCoord->setFollowerMode(repl::MemberState::RS_PRIMARY));
    }

    void tearDown() override {
        serverGlobalParams.clusterRole = ClusterRole::None;
    }

    void serverlessSetExpireAfterSeconds(const TenantId& tenantId, int64_t expireAfterSeconds) {
        auto* clusterParameters = ServerParameterSet::getClusterParameterSet();
        auto* changeStreamsParam =
            clusterParameters
                ->get<ClusterParameterWithStorage<ChangeStreamsClusterParameterStorage>>(
                    "changeStreams");

        auto oldSettings = changeStreamsParam->getValue(tenantId);
        oldSettings.setExpireAfterSeconds(expireAfterSeconds);
        changeStreamsParam->setValue(oldSettings, tenantId).ignore();
    }

    RecordId generatePreImageRecordId(Timestamp timestamp) {
        const UUID uuid{UUID::gen()};
        ChangeStreamPreImageId preImageId(uuid, timestamp, 0);
        return change_stream_pre_image_util::toRecordId(preImageId);
    }


    RecordId generatePreImageRecordId(Date_t wallTime) {
        const UUID uuid{UUID::gen()};
        Timestamp timestamp{wallTime};
        ChangeStreamPreImageId preImageId(uuid, timestamp, 0);
        return change_stream_pre_image_util::toRecordId(preImageId);
    }

    bool hasExcessMarkers(OperationContext* opCtx, PreImagesTruncateMarkersPerCollection& markers) {
        return markers._hasExcessMarkers(opCtx);
    }

    // The oplog must be populated in order to produce an earliest Timestamp. Creates then
    // performs an insert on an arbitrary collection in order to populate the oplog.
    void initEarliestOplogTSWithInsert(OperationContext* opCtx) {
        NamespaceString arbitraryNss =
            NamespaceString::createNamespaceString_forTest("test", "coll");

        writeConflictRetry(opCtx, "createCollection", arbitraryNss, [&] {
            WriteUnitOfWork wunit(opCtx);
            AutoGetCollection collRaii(opCtx, arbitraryNss, MODE_X);
            invariant(!collRaii);
            auto db = collRaii.ensureDbExists(opCtx);
            invariant(db->createCollection(opCtx, arbitraryNss, {}));
            wunit.commit();
        });

        std::vector<InsertStatement> insert;
        insert.emplace_back(BSON("_id" << 0 << "data"
                                       << "x"));
        WriteUnitOfWork wuow(opCtx);
        AutoGetCollection autoColl(opCtx, arbitraryNss, MODE_IX);
        OpObserverRegistry opObserver;
        opObserver.addObserver(
            std::make_unique<OpObserverImpl>(std::make_unique<OplogWriterImpl>()));
        opObserver.onInserts(opCtx,
                             *autoColl,
                             insert.begin(),
                             insert.end(),
                             /*fromMigrate=*/std::vector<bool>(insert.size(), false),
                             /*defaultFromMigrate=*/false);
        wuow.commit();
    }
};

// When 'expireAfterSeconds' is off, defaults to comparing the 'lastRecord's Timestamp of oldest
// marker with the Timestamp of the ealiest oplog entry.
//
// When 'expireAfterSeconds' is on, defaults to comparing the 'lastRecord's wallTime with
// the current time - 'expireAfterSeconds',  which is already tested as a part of the
// ChangeStreamPreImageExpirationPolicyTest.
TEST_F(PreImagesTruncateMarkersPerCollectionTest, hasExcessMarkersExpiredAfterSecondsOff) {
    auto opCtxPtr = cc().makeOperationContext();
    auto opCtx = opCtxPtr.get();

    // With no explicit 'expireAfterSeconds', excess markers are determined by whether the Timestamp
    // of the 'lastRecord' in the oldest marker is greater than the Timestamp of the earliest oplog
    // entry.
    auto changeStreamOptions = populateChangeStreamPreImageOptions("off");
    setChangeStreamOptionsToManager(opCtx, *changeStreamOptions.get());

    initEarliestOplogTSWithInsert(opCtx);
    const auto currentEarliestOplogEntryTs =
        repl::StorageInterface::get(opCtx->getServiceContext())->getEarliestOplogTimestamp(opCtx);

    // Ensure that the generated Timestamp associated with the lastRecord of the marker is less than
    // the earliest oplog entry Timestamp.
    auto ts = currentEarliestOplogEntryTs - 1;
    ASSERT_GT(currentEarliestOplogEntryTs, ts);
    auto wallTime = Date_t::fromMillisSinceEpoch(ts.asInt64());
    auto lastRecordId = generatePreImageRecordId(wallTime);

    auto numRecords = 1;
    auto numBytes = 100;
    std::deque<CollectionTruncateMarkers::Marker> initialMarkers{
        {numRecords, numBytes, lastRecordId, wallTime}};

    PreImagesTruncateMarkersPerCollection markers(
        boost::none /* tenantId */, std::move(initialMarkers), 0, 0, 100);
    bool excessMarkers = hasExcessMarkers(opCtx, markers);
    ASSERT_TRUE(excessMarkers);
}

TEST_F(PreImagesTruncateMarkersPerCollectionTest, hasNoExcessMarkersExpiredAfterSecondsOff) {
    auto opCtxPtr = cc().makeOperationContext();
    auto opCtx = opCtxPtr.get();

    // With no explicit 'expireAfterSeconds', excess markers are determined by whether the Timestamp
    // of the 'lastRecord' in the oldest marker is greater than the Timestamp of the earliest oplog
    // entry.
    auto changeStreamOptions = populateChangeStreamPreImageOptions("off");
    setChangeStreamOptionsToManager(opCtx, *changeStreamOptions.get());

    initEarliestOplogTSWithInsert(opCtx);
    const auto currentEarliestOplogEntryTs =
        repl::StorageInterface::get(opCtx->getServiceContext())->getEarliestOplogTimestamp(opCtx);

    // Ensure that the generated Timestamp associated with the lastRecord of the marker is less than
    // the earliest oplog entry Timestamp.
    auto ts = currentEarliestOplogEntryTs + 1;
    ASSERT_LT(currentEarliestOplogEntryTs, ts);
    auto wallTime = Date_t::fromMillisSinceEpoch(ts.asInt64());
    auto lastRecordId = generatePreImageRecordId(wallTime);

    auto numRecords = 1;
    auto numBytes = 100;
    std::deque<CollectionTruncateMarkers::Marker> initialMarkers{
        {numRecords, numBytes, lastRecordId, wallTime}};

    PreImagesTruncateMarkersPerCollection markers(
        boost::none /* tenantId */, std::move(initialMarkers), 0, 0, 100);
    bool excessMarkers = hasExcessMarkers(opCtx, markers);
    ASSERT_FALSE(excessMarkers);
}

TEST_F(PreImagesTruncateMarkersPerCollectionTest, serverlessHasNoExcessMarkers) {
    int64_t expireAfterSeconds = 1000;
    auto tenantId = change_stream_serverless_helpers::getTenantIdForTesting();
    serverlessSetExpireAfterSeconds(tenantId, expireAfterSeconds);

    auto opCtxPtr = cc().makeOperationContext();
    auto opCtx = opCtxPtr.get();
    auto wallTime = opCtx->getServiceContext()->getFastClockSource()->now() + Minutes(120);
    auto lastRecordId = generatePreImageRecordId(wallTime);
    auto numRecords = 1;
    auto numBytes = 100;
    std::deque<CollectionTruncateMarkers::Marker> initialMarkers{
        {numRecords, numBytes, lastRecordId, wallTime}};

    PreImagesTruncateMarkersPerCollection markers(tenantId, std::move(initialMarkers), 0, 0, 100);
    bool excessMarkers = hasExcessMarkers(opCtx, markers);
    ASSERT_FALSE(excessMarkers);
}

TEST_F(PreImagesTruncateMarkersPerCollectionTest, serverlessHasExcessMarkers) {
    int64_t expireAfterSeconds = 1;
    auto tenantId = change_stream_serverless_helpers::getTenantIdForTesting();
    serverlessSetExpireAfterSeconds(tenantId, expireAfterSeconds);

    auto opCtxPtr = cc().makeOperationContext();
    auto opCtx = opCtxPtr.get();
    auto wallTime = opCtx->getServiceContext()->getFastClockSource()->now() - Minutes(120);
    auto lastRecordId = generatePreImageRecordId(wallTime);
    auto numRecords = 1;
    auto numBytes = 100;
    std::deque<CollectionTruncateMarkers::Marker> initialMarkers{
        {numRecords, numBytes, lastRecordId, wallTime}};

    PreImagesTruncateMarkersPerCollection markers(tenantId, std::move(initialMarkers), 0, 0, 100);
    bool excessMarkers = hasExcessMarkers(opCtx, markers);
    ASSERT_TRUE(excessMarkers);
}

TEST_F(PreImagesTruncateMarkersPerCollectionTest, RecordIdToPreImageTimstampRetrieval) {
    // Basic case.
    {
        Timestamp ts0(Date_t::now());
        int64_t applyOpsIndex = 0;

        ChangeStreamPreImageId preImageId(UUID::gen(), ts0, applyOpsIndex);
        auto preImageRecordId = change_stream_pre_image_util::toRecordId(preImageId);

        auto ts1 = change_stream_pre_image_util::getPreImageTimestamp(preImageRecordId);
        ASSERT_EQ(ts0, ts1);
    }

    // Min Timestamp.
    {
        Timestamp ts0 = Timestamp::min();
        int64_t applyOpsIndex = 0;

        ChangeStreamPreImageId preImageId(UUID::gen(), ts0, applyOpsIndex);
        auto preImageRecordId = change_stream_pre_image_util::toRecordId(preImageId);

        auto ts1 = change_stream_pre_image_util::getPreImageTimestamp(preImageRecordId);
        ASSERT_EQ(ts0, ts1);
    }

    // Max Timestamp
    {
        Timestamp ts0 = Timestamp::max();
        int64_t applyOpsIndex = 0;

        ChangeStreamPreImageId preImageId(UUID::gen(), ts0, applyOpsIndex);
        auto preImageRecordId = change_stream_pre_image_util::toRecordId(preImageId);

        auto ts1 = change_stream_pre_image_util::getPreImageTimestamp(preImageRecordId);
        ASSERT_EQ(ts0, ts1);
    }

    // Extra large 'applyOpsIndex'.
    //
    // Parsing a RecordId with an underlying KeyString representation into BSON discards type bits.
    // Since the 'applyOpsIndex' is the only field in 'ChangeStreamPreImageId' that requires type
    // bits to generate the original value from KeyString, ensure different numeric values of
    // 'applyOpsIndex' don't impact the Timestamp retrieval.
    {
        Timestamp ts0(Date_t::now());
        int64_t applyOpsIndex = std::numeric_limits<int64_t>::max();

        ChangeStreamPreImageId preImageId(UUID::gen(), ts0, applyOpsIndex);
        auto preImageRecordId = change_stream_pre_image_util::toRecordId(preImageId);

        auto ts1 = change_stream_pre_image_util::getPreImageTimestamp(preImageRecordId);
        ASSERT_EQ(ts0, ts1);
    }

    // Extra large 'applyOpsIndex' with Timestamp::max().
    {
        Timestamp ts0 = Timestamp::max();
        int64_t applyOpsIndex = std::numeric_limits<int64_t>::max();

        ChangeStreamPreImageId preImageId(UUID::gen(), ts0, applyOpsIndex);
        auto preImageRecordId = change_stream_pre_image_util::toRecordId(preImageId);

        auto ts1 = change_stream_pre_image_util::getPreImageTimestamp(preImageRecordId);
        ASSERT_EQ(ts0, ts1);
    }
}

}  // namespace mongo