-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
document_source_facet.cpp
423 lines (369 loc) · 17.8 KB
/
document_source_facet.cpp
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
/**
* 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.
*/
// IWYU pragma: no_include "boost/container/detail/std_fwd.hpp"
#include <algorithm>
#include <list>
#include <memory>
#include <vector>
#include <boost/move/utility_core.hpp>
#include <boost/optional/optional.hpp>
#include <boost/smart_ptr/intrusive_ptr.hpp>
#include "mongo/base/error_codes.h"
#include "mongo/base/string_data.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/bson/bsontypes.h"
#include "mongo/db/exec/document_value/document.h"
#include "mongo/db/exec/document_value/document_metadata_fields.h"
#include "mongo/db/exec/document_value/value.h"
#include "mongo/db/pipeline/document_source_facet.h"
#include "mongo/db/pipeline/document_source_tee_consumer.h"
#include "mongo/db/pipeline/expression_context.h"
#include "mongo/db/pipeline/field_path.h"
#include "mongo/db/pipeline/pipeline.h"
#include "mongo/db/pipeline/tee_buffer.h"
#include "mongo/db/query/allowed_contexts.h"
#include "mongo/db/query/plan_summary_stats.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/str.h"
namespace mongo {
using boost::intrusive_ptr;
using std::pair;
using std::string;
using std::vector;
DocumentSourceFacet::DocumentSourceFacet(std::vector<FacetPipeline> facetPipelines,
const intrusive_ptr<ExpressionContext>& expCtx,
size_t bufferSizeBytes,
size_t maxOutputDocBytes)
: DocumentSource(kStageName, expCtx),
_teeBuffer(TeeBuffer::create(facetPipelines.size(), bufferSizeBytes)),
_facets(std::move(facetPipelines)),
_maxOutputDocSizeBytes(maxOutputDocBytes) {
for (size_t facetId = 0; facetId < _facets.size(); ++facetId) {
auto& facet = _facets[facetId];
facet.pipeline->addInitialSource(
DocumentSourceTeeConsumer::create(pExpCtx, facetId, _teeBuffer, kTeeConsumerStageName));
}
}
namespace {
/**
* Extracts the names of the facets and the vectors of raw BSONObjs representing the stages within
* that facet's pipeline.
*
* Throws a AssertionException if it fails to parse for any reason.
*/
vector<pair<string, vector<BSONObj>>> extractRawPipelines(const BSONElement& elem) {
uassert(40169,
str::stream() << "the $facet specification must be a non-empty object, but found: "
<< elem,
elem.type() == BSONType::Object && !elem.embeddedObject().isEmpty());
vector<pair<string, vector<BSONObj>>> rawFacetPipelines;
for (auto&& facetElem : elem.embeddedObject()) {
const auto facetName = facetElem.fieldNameStringData();
FieldPath::uassertValidFieldName(facetName);
uassert(40170,
str::stream() << "arguments to $facet must be arrays, " << facetName << " is type "
<< typeName(facetElem.type()),
facetElem.type() == BSONType::Array);
vector<BSONObj> rawPipeline;
for (auto&& subPipeElem : facetElem.Obj()) {
uassert(40171,
str::stream() << "elements of arrays in $facet spec must be non-empty objects, "
<< facetName << " argument contained an element of type "
<< typeName(subPipeElem.type()) << ": " << subPipeElem,
subPipeElem.type() == BSONType::Object);
rawPipeline.push_back(subPipeElem.embeddedObject());
}
rawFacetPipelines.emplace_back(facetName.toString(), std::move(rawPipeline));
}
return rawFacetPipelines;
}
/**
* Helper function to find the stage that violates the $facet requirement. The 'source' is not
* allowed either directly or because of some of the sources inside its sub-pipelines.
*/
std::string getStageNameNotAllowedInFacet(const DocumentSource& source,
const std::string& parentName) {
auto* subPipeline = source.getSubPipeline();
const std::string& sourceName = source.getSourceName();
if (!subPipeline) {
if (!parentName.empty()) {
return str::stream() << sourceName << " inside of " << parentName;
} else {
return str::stream() << sourceName;
}
} else {
for (const auto& substage : *subPipeline) {
auto stageConstraints = substage->constraints();
if (!stageConstraints.isAllowedInsideFacetStage()) {
return getStageNameNotAllowedInFacet(*substage, sourceName);
}
}
// If we reach this point, none of the sub-stages is violating the $facet requirement. The
// 'source' stage itself is not allowed.
return str::stream() << sourceName;
}
MONGO_UNREACHABLE_TASSERT(8045600);
}
} // namespace
std::unique_ptr<DocumentSourceFacet::LiteParsed> DocumentSourceFacet::LiteParsed::parse(
const NamespaceString& nss, const BSONElement& spec) {
std::vector<LiteParsedPipeline> liteParsedPipelines;
for (auto&& rawPipeline : extractRawPipelines(spec)) {
liteParsedPipelines.emplace_back(LiteParsedPipeline(nss, rawPipeline.second));
}
return std::make_unique<DocumentSourceFacet::LiteParsed>(spec.fieldName(),
std::move(liteParsedPipelines));
}
REGISTER_DOCUMENT_SOURCE(facet,
DocumentSourceFacet::LiteParsed::parse,
DocumentSourceFacet::createFromBson,
AllowedWithApiStrict::kAlways);
intrusive_ptr<DocumentSourceFacet> DocumentSourceFacet::create(
std::vector<FacetPipeline> facetPipelines,
const intrusive_ptr<ExpressionContext>& expCtx,
size_t bufferSizeBytes,
size_t maxOutputDocBytes) {
return new DocumentSourceFacet(
std::move(facetPipelines), expCtx, bufferSizeBytes, maxOutputDocBytes);
}
void DocumentSourceFacet::setSource(DocumentSource* source) {
_teeBuffer->setSource(source);
}
void DocumentSourceFacet::doDispose() {
for (auto&& facet : _facets) {
facet.pipeline.get_deleter().dismissDisposal();
facet.pipeline->dispose(pExpCtx->opCtx);
}
}
DocumentSource::GetNextResult DocumentSourceFacet::doGetNext() {
if (_done) {
return GetNextResult::makeEOF();
}
const size_t maxBytes = _maxOutputDocSizeBytes;
auto ensureUnderMemoryLimit = [usedBytes = 0ul, &maxBytes](long long additional) mutable {
usedBytes += additional;
uassert(4031700,
str::stream() << "document constructed by $facet is " << usedBytes
<< " bytes, which exceeds the limit of " << maxBytes << " bytes",
usedBytes <= maxBytes);
};
vector<vector<Value>> results(_facets.size());
bool allPipelinesEOF = false;
while (!allPipelinesEOF) {
allPipelinesEOF = true; // Set this to false if any pipeline isn't EOF.
for (size_t facetId = 0; facetId < _facets.size(); ++facetId) {
const auto& pipeline = _facets[facetId].pipeline;
auto next = pipeline->getSources().back()->getNext();
for (; next.isAdvanced(); next = pipeline->getSources().back()->getNext()) {
ensureUnderMemoryLimit(next.getDocument().getApproximateSize());
results[facetId].emplace_back(next.releaseDocument());
}
allPipelinesEOF = allPipelinesEOF && next.isEOF();
accumulatePipelinePlanSummaryStats(*pipeline, _stats.planSummaryStats);
}
}
MutableDocument resultDoc;
for (size_t facetId = 0; facetId < _facets.size(); ++facetId) {
resultDoc[_facets[facetId].name] = Value(std::move(results[facetId]));
}
_done = true; // We will only ever produce one result.
return resultDoc.freeze();
}
Value DocumentSourceFacet::serialize(const SerializationOptions& opts) const {
MutableDocument serialized;
for (auto&& facet : _facets) {
serialized[opts.serializeFieldPathFromString(facet.name)] =
Value(opts.verbosity ? facet.pipeline->writeExplainOps(opts)
: facet.pipeline->serialize(opts));
}
return Value(Document{{"$facet", serialized.freezeToValue()}});
}
void DocumentSourceFacet::addInvolvedCollections(
stdx::unordered_set<NamespaceString>* collectionNames) const {
for (auto&& facet : _facets) {
for (auto&& source : facet.pipeline->getSources()) {
source->addInvolvedCollections(collectionNames);
}
}
}
intrusive_ptr<DocumentSource> DocumentSourceFacet::optimize() {
for (auto&& facet : _facets) {
facet.pipeline->optimizePipeline();
}
return this;
}
void DocumentSourceFacet::detachFromOperationContext() {
for (auto&& facet : _facets) {
facet.pipeline->detachFromOperationContext();
}
}
void DocumentSourceFacet::reattachToOperationContext(OperationContext* opCtx) {
for (auto&& facet : _facets) {
facet.pipeline->reattachToOperationContext(opCtx);
}
}
bool DocumentSourceFacet::validateOperationContext(const OperationContext* opCtx) const {
return getContext()->opCtx == opCtx &&
std::all_of(_facets.begin(), _facets.end(), [opCtx](const auto& f) {
return f.pipeline->validateOperationContext(opCtx);
});
}
StageConstraints DocumentSourceFacet::constraints(Pipeline::SplitState state) const {
// Currently we don't split $facet to have a merger part and a shards part (see SERVER-24154).
// This means that if any stage in any of the $facet pipelines needs to run on mongoS, then the
// entire $facet stage must run there.
static const HostTypeRequirement kDefinitiveHost = HostTypeRequirement::kMongoS;
HostTypeRequirement host = HostTypeRequirement::kNone;
boost::optional<ShardId> mergeShardId;
// Iterate through each pipeline to determine the HostTypeRequirement for the $facet stage.
// Because we have already validated that there are no conflicting HostTypeRequirements during
// parsing, if we observe a host type of 'kMongos' in any of the pipelines then the entire
// $facet stage must run on mongos and iteration can stop. At the end of this process, 'host'
// will be the $facet's final HostTypeRequirement.
for (auto fi = _facets.begin(); fi != _facets.end() && host != kDefinitiveHost; fi++) {
const auto& sources = fi->pipeline->getSources();
for (auto si = sources.begin(); si != sources.end() && host != kDefinitiveHost; si++) {
const auto subConstraints = (*si)->constraints(state);
const auto hostReq = subConstraints.resolvedHostTypeRequirement(pExpCtx);
if (hostReq != HostTypeRequirement::kNone) {
host = hostReq;
}
// Capture the first merging shard requested by a subpipeline.
if (!mergeShardId) {
mergeShardId = subConstraints.mergeShardId;
}
}
}
// Clear the captured merging shard if 'host' is incompatible with merging on a shard.
if (!(host == HostTypeRequirement::kNone || host == HostTypeRequirement::kRunOnceAnyNode ||
host == HostTypeRequirement::kAnyShard)) {
mergeShardId = boost::none;
}
// Resolve the disk use, lookup, and transaction requirement of this $facet by iterating through
// the children in its facets.
StageConstraints constraints(StreamType::kBlocking,
PositionRequirement::kNone,
host,
StageConstraints::DiskUseRequirement::kNoDiskUse,
FacetRequirement::kNotAllowed,
StageConstraints::TransactionRequirement::kAllowed,
StageConstraints::LookupRequirement::kAllowed,
StageConstraints::UnionRequirement::kAllowed);
for (const auto& facet : _facets) {
constraints =
StageConstraints::getStrictestConstraints(facet.pipeline->getSources(), constraints);
}
if (mergeShardId) {
constraints.mergeShardId = mergeShardId;
}
return constraints;
}
bool DocumentSourceFacet::usedDisk() {
for (auto&& facet : _facets) {
if (facet.pipeline->usedDisk()) {
_stats.planSummaryStats.usedDisk = true;
break;
}
}
return _stats.planSummaryStats.usedDisk;
}
DepsTracker::State DocumentSourceFacet::getDependencies(DepsTracker* deps) const {
for (auto&& facet : _facets) {
auto subDepsTracker = facet.pipeline->getDependencies(deps->getUnavailableMetadata());
deps->fields.insert(subDepsTracker.fields.begin(), subDepsTracker.fields.end());
deps->needWholeDocument = deps->needWholeDocument || subDepsTracker.needWholeDocument;
// If the subpipeline needs any search metadata, the top level pipeline must know to
// generate it.
deps->searchMetadataDeps() |= subDepsTracker.searchMetadataDeps();
// The text score is the only type of metadata that could be needed by $facet.
deps->setNeedsMetadata(
DocumentMetadataFields::kTextScore,
deps->getNeedsMetadata(DocumentMetadataFields::kTextScore) ||
subDepsTracker.getNeedsMetadata(DocumentMetadataFields::kTextScore));
if (deps->needWholeDocument && deps->getNeedsMetadata(DocumentMetadataFields::kTextScore)) {
break;
}
}
// We will combine multiple documents into one, and the output document will have new fields, so
// we will stop looking for dependencies at this point.
return DepsTracker::State::EXHAUSTIVE_ALL;
}
void DocumentSourceFacet::addVariableRefs(std::set<Variables::Id>* refs) const {
for (auto&& facet : _facets) {
facet.pipeline->addVariableRefs(refs);
}
}
intrusive_ptr<DocumentSource> DocumentSourceFacet::createFromBson(
BSONElement elem, const intrusive_ptr<ExpressionContext>& expCtx) {
boost::optional<std::string> needsMongoS;
boost::optional<std::string> needsShard;
std::vector<FacetPipeline> facetPipelines;
for (auto&& rawFacet : extractRawPipelines(elem)) {
const auto facetName = rawFacet.first;
auto pipeline =
Pipeline::parseFacetPipeline(rawFacet.second, expCtx, [](const Pipeline& pipeline) {
auto sources = pipeline.getSources();
std::for_each(sources.begin(), sources.end(), [](auto& stage) {
auto stageConstraints = stage->constraints();
if (!stageConstraints.isAllowedInsideFacetStage()) {
uasserted(40600,
str::stream()
<< getStageNameNotAllowedInFacet(*stage, "")
<< " is not allowed to be used within a $facet stage");
}
// We expect a stage within a $facet stage to have these properties.
invariant(stageConstraints.requiredPosition ==
StageConstraints::PositionRequirement::kNone);
invariant(!stageConstraints.isIndependentOfAnyCollection);
});
});
// These checks potentially require that we check the catalog to determine where our data
// lives. In circumstances where we aren't actually running the query, we don't need to do
// this (and it can erroneously error - SERVER-83912).
if (expCtx->mongoProcessInterface->isExpectedToExecuteQueries()) {
// Validate that none of the facet pipelines have any conflicting HostTypeRequirements.
// This verifies both that all stages within each pipeline are consistent, and that the
// pipelines are consistent with one another.
if (!needsShard && pipeline->needsShard()) {
needsShard.emplace(facetName);
}
if (!needsMongoS && pipeline->needsMongosMerger()) {
needsMongoS.emplace(facetName);
}
uassert(ErrorCodes::IllegalOperation,
str::stream() << "$facet pipeline '" << *needsMongoS
<< "' must run on mongoS, but '" << *needsShard
<< "' requires a shard",
!(needsShard && needsMongoS));
}
facetPipelines.emplace_back(facetName, std::move(pipeline));
}
return DocumentSourceFacet::create(std::move(facetPipelines), expCtx);
}
} // namespace mongo