summaryrefslogtreecommitdiff
path: root/src/mongo/db/sessions_collection.cpp
blob: 9864cc11aa9973ec4f90411d29151e2c0a95b0c0 (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
/**
 *    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/sessions_collection.h"

#include <functional>
#include <memory>
#include <vector>

#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/client/dbclient_base.h"
#include "mongo/db/create_indexes_gen.h"
#include "mongo/db/logical_session_id.h"
#include "mongo/db/ops/write_ops.h"
#include "mongo/db/repl/read_concern_args.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/s/write_ops/batched_command_response.h"

namespace mongo {
namespace {

// This batch size is chosen to ensure that we don't form requests larger than the 16mb limit.
// Especially for refreshes, the updates we send include the full user name (user@db), and user
// names can be quite large (we enforce a max 10k limit for usernames used with sessions).
//
// At 1000 elements, a 16mb payload gives us a budget of 16000 bytes per user, which we should
// comfortably be able to stay under, even with 10k user names.
constexpr size_t kMaxBatchSize = 1000;

// Used to refresh or remove items from the session collection with write
// concern majority
const WriteConcernOptions kMajorityWriteConcern{WriteConcernOptions::kMajority,
                                                WriteConcernOptions::SyncMode::UNSET,
                                                WriteConcernOptions::kWriteConcernTimeoutSystem};


BSONObj lsidQuery(const LogicalSessionId& lsid) {
    return BSON(LogicalSessionRecord::kIdFieldName << lsid.toBSON());
}

BSONObj lsidQuery(const LogicalSessionRecord& record) {
    return lsidQuery(record.getId());
}

BSONArray updateQuery(const LogicalSessionRecord& record) {
    // [ { $set : { lastUse : $$NOW } } , { $set : { user: <user> } } ]

    // Build our update doc.
    BSONArrayBuilder updateBuilder;
    updateBuilder << BSON("$set" << BSON(LogicalSessionRecord::kLastUseFieldName << "$$NOW"));

    if (record.getUser()) {
        updateBuilder << BSON("$set" << BSON(LogicalSessionRecord::kUserFieldName
                                             << BSON("name" << *record.getUser())));
    }

    return updateBuilder.arr();
}

template <typename TFactory, typename AddLineFn, typename SendFn, typename Container>
void runBulkGeneric(TFactory makeT, AddLineFn addLine, SendFn sendBatch, const Container& items) {
    using T = decltype(makeT());

    size_t i = 0;
    boost::optional<T> thing;

    auto setupBatch = [&] {
        i = 0;
        thing.emplace(makeT());
    };

    auto sendLocalBatch = [&] { sendBatch(thing.value()); };

    setupBatch();

    for (const auto& item : items) {
        addLine(*thing, item);

        if (++i >= kMaxBatchSize) {
            sendLocalBatch();

            setupBatch();
        }
    }

    if (i > 0) {
        sendLocalBatch();
    }
}

template <typename InitBatchFn, typename AddLineFn, typename SendBatchFn, typename Container>
void runBulkCmd(StringData label,
                InitBatchFn&& initBatch,
                AddLineFn&& addLine,
                SendBatchFn&& sendBatch,
                const Container& items) {
    BufBuilder buf;

    boost::optional<BSONObjBuilder> batchBuilder;
    boost::optional<BSONArrayBuilder> entries;

    auto makeBatch = [&] {
        buf.reset();
        batchBuilder.emplace(buf);
        initBatch(&(batchBuilder.get()));
        entries.emplace(batchBuilder->subarrayStart(label));

        return &(entries.get());
    };

    auto sendLocalBatch = [&](BSONArrayBuilder*) {
        entries->done();
        sendBatch(batchBuilder->done());
    };

    runBulkGeneric(makeBatch, addLine, sendLocalBatch, items);
}

}  // namespace

constexpr StringData SessionsCollection::kSessionsTTLIndex;

SessionsCollection::SessionsCollection() = default;

SessionsCollection::~SessionsCollection() = default;

SessionsCollection::SendBatchFn SessionsCollection::makeSendFnForBatchWrite(
    const NamespaceString& ns, DBClientBase* client) {
    auto send = [client, ns](BSONObj batch) {
        BSONObj res;
        if (!client->runCommand(ns.db().toString(), batch, res)) {
            uassertStatusOK(getStatusFromCommandResult(res));
        }
    };

    return send;
}

SessionsCollection::SendBatchFn SessionsCollection::makeSendFnForCommand(const NamespaceString& ns,
                                                                         DBClientBase* client) {
    auto send = [client, ns](BSONObj cmd) {
        BSONObj res;
        if (!client->runCommand(ns.db().toString(), cmd, res)) {
            uassertStatusOK(getStatusFromCommandResult(res));
        }
    };

    return send;
}

SessionsCollection::FindBatchFn SessionsCollection::makeFindFnForCommand(const NamespaceString& ns,
                                                                         DBClientBase* client) {
    auto send = [client, ns](BSONObj cmd) -> BSONObj {
        BSONObj res;
        if (!client->runCommand(ns.db().toString(), cmd, res)) {
            uassertStatusOK(getStatusFromCommandResult(res));
        }

        return res;
    };

    return send;
}

void SessionsCollection::_doRefresh(const NamespaceString& ns,
                                    const std::vector<LogicalSessionRecord>& sessions,
                                    SendBatchFn send) {
    auto init = [ns](BSONObjBuilder* batch) {
        batch->append("update", ns.coll());
        batch->append("ordered", false);
        batch->append(WriteConcernOptions::kWriteConcernField, kMajorityWriteConcern.toBSON());
    };

    auto add = [](BSONArrayBuilder* entries, const LogicalSessionRecord& record) {
        entries->append(
            BSON("q" << lsidQuery(record) << "u" << updateQuery(record) << "upsert" << true));
    };

    runBulkCmd("updates", init, add, send, sessions);
}

void SessionsCollection::_doRemove(const NamespaceString& ns,
                                   const std::vector<LogicalSessionId>& sessions,
                                   SendBatchFn send) {
    auto init = [ns](BSONObjBuilder* batch) {
        batch->append("delete", ns.coll());
        batch->append("ordered", false);
        batch->append(WriteConcernOptions::kWriteConcernField, kMajorityWriteConcern.toBSON());
    };

    auto add = [](BSONArrayBuilder* builder, const LogicalSessionId& lsid) {
        builder->append(BSON("q" << lsidQuery(lsid) << "limit" << 0));
    };

    runBulkCmd("deletes", init, add, send, sessions);
}

LogicalSessionIdSet SessionsCollection::_doFindRemoved(
    const NamespaceString& ns, const std::vector<LogicalSessionId>& sessions, FindBatchFn send) {
    auto makeT = [] { return std::vector<LogicalSessionId>{}; };

    auto add = [](std::vector<LogicalSessionId>& batch, const LogicalSessionId& record) {
        batch.push_back(record);
    };

    LogicalSessionIdSet removed{sessions.begin(), sessions.end()};

    auto wrappedSend = [&](BSONObj batch) {
        BSONObjBuilder batchWithReadConcernLocal(batch);
        batchWithReadConcernLocal.append(repl::ReadConcernArgs::kReadConcernFieldName,
                                         repl::ReadConcernArgs::kImplicitDefault);
        auto swBatchResult = send(batchWithReadConcernLocal.obj());

        auto result =
            SessionsCollectionFetchResult::parse("SessionsCollectionFetchResult"_sd, swBatchResult);

        for (const auto& lsid : result.getCursor().getFirstBatch()) {
            removed.erase(lsid.get_id());
        }
    };

    auto sendLocal = [&](std::vector<LogicalSessionId>& batch) {
        SessionsCollectionFetchRequest request;

        request.setFind(ns.coll());
        request.setFilter({});
        request.getFilter().set_id({});
        request.getFilter().get_id().setIn(batch);

        request.setProjection({});
        request.getProjection().set_id(1);
        request.setBatchSize(batch.size());
        request.setLimit(batch.size());
        request.setSingleBatch(true);

        wrappedSend(request.toBSON());
    };

    runBulkGeneric(makeT, add, sendLocal, sessions);

    return removed;
}

BSONObj SessionsCollection::generateCreateIndexesCmd() {
    NewIndexSpec index;
    index.setKey(BSON("lastUse" << 1));
    index.setName(kSessionsTTLIndex);
    index.setExpireAfterSeconds(localLogicalSessionTimeoutMinutes * 60);

    CreateIndexesCommand createIndexes(NamespaceString::kLogicalSessionsNamespace);
    createIndexes.setIndexes({index.toBSON()});

    return createIndexes.toBSON(
        BSON(WriteConcernOptions::kWriteConcernField << WriteConcernOptions::kImplicitDefault));
}

BSONObj SessionsCollection::generateCollModCmd() {
    BSONObjBuilder collModCmdBuilder;

    collModCmdBuilder << "collMod" << NamespaceString::kLogicalSessionsNamespace.coll();

    BSONObjBuilder indexBuilder(collModCmdBuilder.subobjStart("index"));
    indexBuilder << "name" << kSessionsTTLIndex;
    indexBuilder << "expireAfterSeconds" << localLogicalSessionTimeoutMinutes * 60;

    indexBuilder.done();
    collModCmdBuilder.append(WriteConcernOptions::kWriteConcernField,
                             WriteConcernOptions::kImplicitDefault);
    collModCmdBuilder.done();

    return collModCmdBuilder.obj();
}

}  // namespace mongo