Pipeline.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. "use strict";
  2. /**
  3. * mongodb "commands" (sent via db.$cmd.findOne(...)) subclass to make a command. define a singleton object for it.
  4. * @class Pipeline
  5. * @namespace mungedb-aggregate.pipeline
  6. * @module mungedb-aggregate
  7. * @constructor
  8. **/
  9. // CONSTRUCTOR
  10. var Pipeline = module.exports = function Pipeline(theCtx){
  11. this.sources = null;
  12. this.explain = false;
  13. this.splitMongodPipeline = false;
  14. this.ctx = theCtx;
  15. this.SYNC_MODE = false;
  16. }, klass = Pipeline, base = Object, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  17. var DocumentSource = require("./documentSources/DocumentSource"),
  18. LimitDocumentSource = require('./documentSources/LimitDocumentSource'),
  19. MatchDocumentSource = require('./documentSources/MatchDocumentSource'),
  20. ProjectDocumentSource = require('./documentSources/ProjectDocumentSource'),
  21. SkipDocumentSource = require('./documentSources/SkipDocumentSource'),
  22. UnwindDocumentSource = require('./documentSources/UnwindDocumentSource'),
  23. GroupDocumentSource = require('./documentSources/GroupDocumentSource'),
  24. OutDocumentSource = require('./documentSources/OutDocumentSource'),
  25. GeoNearDocumentSource = require('./documentSources/GeoNearDocumentSource'),
  26. RedactDocumentSource = require('./documentSources/RedactDocumentSource'),
  27. SortDocumentSource = require('./documentSources/SortDocumentSource');
  28. klass.COMMAND_NAME = "aggregate";
  29. klass.PIPELINE_NAME = "pipeline";
  30. klass.EXPLAIN_NAME = "explain";
  31. klass.FROM_ROUTER_NAME = "fromRouter";
  32. klass.SERVER_PIPELINE_NAME = "serverPipeline";
  33. klass.MONGOS_PIPELINE_NAME = "mongosPipeline";
  34. klass.stageDesc = {};//attaching this to the class for test cases
  35. klass.stageDesc[GeoNearDocumentSource.geoNearName] = GeoNearDocumentSource.createFromJson;
  36. klass.stageDesc[GroupDocumentSource.groupName] = GroupDocumentSource.createFromJson;
  37. klass.stageDesc[LimitDocumentSource.limitName] = LimitDocumentSource.createFromJson;
  38. klass.stageDesc[MatchDocumentSource.matchName] = MatchDocumentSource.createFromJson;
  39. klass.stageDesc[OutDocumentSource.outName] = OutDocumentSource.createFromJson;
  40. klass.stageDesc[ProjectDocumentSource.projectName] = ProjectDocumentSource.createFromJson;
  41. klass.stageDesc[RedactDocumentSource.redactName] = ProjectDocumentSource.createFromJson;
  42. klass.stageDesc[SkipDocumentSource.skipName] = SkipDocumentSource.createFromJson;
  43. klass.stageDesc[SortDocumentSource.sortName] = SortDocumentSource.createFromJson;
  44. klass.stageDesc[UnwindDocumentSource.unwindName] = UnwindDocumentSource.createFromJson;
  45. klass.nStageDesc = Object.keys(klass.stageDesc).length;
  46. klass.optimizations = {};
  47. klass.optimizations.local = {};
  48. klass.optimizations.sharded = {};
  49. /**
  50. * Moves $match before $sort when they are placed next to one another
  51. * @static
  52. * @method moveMatchBeforeSort
  53. * @param pipelineInst An instance of a Pipeline
  54. **/
  55. klass.optimizations.local.moveMatchBeforeSort = function moveMatchBeforeSort(pipelineInst) {
  56. var sources = pipelineInst.sources;
  57. debugger
  58. for(var srcn = sources.length, srci = 1; srci < srcn; ++srci) {
  59. var source = sources[srci];
  60. if(source.constructor === MatchDocumentSource) {
  61. var previous = sources[srci - 1];
  62. if(previous && previous.constructor === SortDocumentSource) { //Added check that previous exists
  63. /* swap this item with the previous */
  64. sources[srci] = previous;
  65. sources[srci-1] = source;
  66. }
  67. }
  68. }
  69. };
  70. /**
  71. * Moves $limit before $skip when they are placed next to one another
  72. * @static
  73. * @method moveLimitBeforeSkip
  74. * @param pipelineInst An instance of a Pipeline
  75. **/
  76. klass.optimizations.local.moveLimitBeforeSkip = function moveLimitBeforeSkip(pipelineInst) {
  77. var sources = pipelineInst.sources;
  78. if(sources.length === 0) return;
  79. for(var i = sources.length - 1; i >= 1 /* not looking at 0 */; i--) {
  80. var limit = sources[i].constructor === LimitDocumentSource ? sources[i] : undefined,
  81. skip = sources[i-1].constructor === SkipDocumentSource ? sources[i-1] : undefined;
  82. if(limit && skip) {
  83. limit.setLimit(limit.getLimit() + skip.getSkip());
  84. sources[i-1] = limit;
  85. sources[i] = skip;
  86. // Start at back again. This is needed to handle cases with more than 1 $limit
  87. // (S means skip, L means limit)
  88. //
  89. // These two would work without second pass (assuming back to front ordering)
  90. // SL -> LS
  91. // SSL -> LSS
  92. //
  93. // The following cases need a second pass to handle the second limit
  94. // SLL -> LLS
  95. // SSLL -> LLSS
  96. // SLSL -> LLSS
  97. i = sources.length; // decremented before next pass
  98. }
  99. }
  100. };
  101. /**
  102. * Attempts to coalesce every pipeline stage into the previous pipeline stage, starting after the first
  103. * @static
  104. * @method coalesceAdjacent
  105. * @param pipelineInst An instance of a Pipeline
  106. **/
  107. klass.optimizations.local.coalesceAdjacent = function coalesceAdjacent(pipelineInst) {
  108. var sources = pipelineInst.sources;
  109. if(sources.length === 0) return;
  110. // move all sources to a temporary list
  111. var moveSrc = sources.pop(),
  112. tempSources = [];
  113. while(moveSrc) {
  114. tempSources.unshift(moveSrc);
  115. moveSrc = sources.pop();
  116. }
  117. // move the first one to the final list
  118. sources.push(tempSources[0]);
  119. // run through the sources, coalescing them or keeping them
  120. for(var tempn = tempSources.length, tempi = 1; tempi < tempn; ++tempi) {
  121. // If we can't coalesce the source with the last, then move it
  122. // to the final list, and make it the new last. (If we succeeded,
  123. // then we're still on the same last, and there's no need to move
  124. // or do anything with the source -- the destruction of tempSources
  125. // will take care of the rest.)
  126. var lastSource = sources[sources.length-1],
  127. tempSrc = tempSources[tempi];
  128. if(!(lastSource && tempSrc)) {
  129. throw new Error('Must have a last and current source'); // verify(lastSource && tempSrc);
  130. }
  131. if(!lastSource.coalesce(tempSrc)) sources.push(tempSrc);
  132. }
  133. };
  134. /**
  135. * Iterates over sources in the pipelineInst, optimizing each
  136. * @static
  137. * @method optimizeEachDocumentSource
  138. * @param pipelineInst An instance of a Pipeline
  139. **/
  140. klass.optimizations.local.optimizeEachDocumentSource = function optimizeEachDocumentSource(pipelineInst) {
  141. var sources = pipelineInst.sources;
  142. for(var srci = 0, srcn = sources.length; srci < srcn; ++srci) {
  143. sources[srci].optimize();
  144. }
  145. };
  146. /**
  147. * Auto-places a $match before a $redact when the $redact is the first item in a pipeline
  148. * @static
  149. * @method duplicateMatchBeforeInitalRedact
  150. * @param pipelineInst An instance of a Pipeline
  151. **/
  152. klass.optimizations.local.duplicateMatchBeforeInitalRedact = function duplicateMatchBeforeInitalRedact(pipelineInst) {
  153. var sources = pipelineInst.sources;
  154. if(sources.length >= 2 && sources[0].constructor === RedactDocumentSource) {
  155. if(sources[1].constructor === MatchDocumentSource) {
  156. var match = sources[1],
  157. redactSafePortion = match.redactSafePortion();
  158. if(Object.keys(redactSafePortion).length > 0) {
  159. sources.shift(MatchDocumentSource.createFromJson(redactSafePortion, pipelineInst.ctx));
  160. }
  161. }
  162. }
  163. };
  164. //SKIPPED: addRequiredPrivileges
  165. /**
  166. * Perform optimizations for a pipeline through sharding
  167. * @method splitForSharded
  168. **/
  169. proto.splitForSharded = function splitForSharded() {
  170. var shardPipeline = new Pipeline(ctx);
  171. shardPipeline.explain = this.explain;
  172. klass.optimizations.sharded.findSplitPoint(shardPipeline, this);
  173. klass.optimizations.sharded.moveFinalUnwindFromShardsToMerger(shardPipeline, this);
  174. klass.optimizations.sharded.limitFieldsSentFromShardsToMerger(shardPipeline, this);
  175. };
  176. /**
  177. * Split the source into Merge sources and Shard sources
  178. * @static
  179. * @method findSplitPoint
  180. * @param shardPipe Shard sources
  181. * @param mergePipe Merge sources
  182. */
  183. klass.optimizations.sharded.findSplitPoint = function findSplitPoint(shardPipe, mergePipe) {
  184. while(mergePipe.sources.length > 0) {
  185. var current = mergePipe.sources[0];
  186. mergePipe.sources.splice(0, 1);
  187. if (typeof current.isSplittable != "undefined") {
  188. shardPipe.sources.push(current);
  189. }
  190. else {
  191. var shardSource = current.getShardSource(),
  192. mergeSource = current.getMergeSource();
  193. if (typeof shardSource != "undefined") { shardPipe.sources.push(shardSource); } //push_back
  194. if (typeof mergeSource != "undefined") { mergePipe.sources.unshift(mergeSource); } //push_front
  195. break;
  196. }
  197. }
  198. };
  199. /**
  200. * Optimize pipeline through moving unwind to the end
  201. * @static
  202. * @method moveFinalUnwindFromShardsToMerger
  203. * @param shardPipe shard sources
  204. * @param mergePipe merge sources
  205. **/
  206. klass.optimizations.sharded.moveFinalUnwindFromShardsToMerger = function moveFinalUnwindFromShardsToMerger(shardPipe, mergePipe) {
  207. while(!shardPipe.sources.length > 0
  208. && shardPipe.sources[length-1].constructor === UnwindDocumentSource) {
  209. mergePipe.sources.unshift(shardPipe.sources[length-1]);
  210. shardPipe.sources.pop();
  211. }
  212. };
  213. klass.limitFieldsSentFromShardsToMerger = function limitFieldsSentFromShardsToMerger(shardPipe, mergePipe) {
  214. var mergeDeps = mergePipe.getDependencies(shardPipe.getInitialQuery());
  215. if (mergeDeps.needWholeDocument) {
  216. return;
  217. }
  218. if (mergeDeps.fields.length == 0) {
  219. mergeDeps.fields["_id"] = 0;
  220. }
  221. //NOTE: Deviation from Mongo: not setting mergeDeps.needTextScore because we aren't handling that (Document meta stuff)
  222. // HEURISTIC: only apply optimization if none of the shard stages have an exhaustive list of
  223. // field dependencies. While this may not be 100% ideal in all cases, it is simple and
  224. // avoids the worst cases by ensuring that:
  225. // 1) Optimization IS applied when the shards wouldn't have known their exhaustive list of
  226. // dependencies. This situation can happen when a $sort is before the first $project or
  227. // $group. Without the optimization, the shards would have to reify and transmit full
  228. // objects even though only a subset of fields are needed.
  229. // 2) Optimization IS NOT applied immediately following a $project or $group since it would
  230. // add an unnecessary project (and therefore a deep-copy).
  231. for (var i = 0; i < shardPipe.sources.length; i++) {
  232. if (shardPipe.sources.getDependencies() & DocumentSource.GetDepsReturn.EXHAUSTIVE_FIELDS)
  233. return;
  234. }
  235. // if we get here, add the project.
  236. shardPipe.sources.push(ProjectDocumentSource.createFromJson({"$project": mergeDeps.toProjection()[0]}, shardPipe.ctx));
  237. };
  238. /**
  239. * Create an `Array` of `DocumentSource`s from the given JSON pipeline
  240. * // NOTE: DEVIATION FROM MONGO: split out into a separate function to better allow extensions (was in parseCommand)
  241. * @static
  242. * @method parseDocumentSources
  243. * @param pipeline {Array} The JSON pipeline
  244. * @returns {Array} The parsed `DocumentSource`s
  245. **/
  246. klass.parseDocumentSources = function parseDocumentSources(pipeline, ctx){
  247. var sources = [];
  248. debugger
  249. for (var nSteps = pipeline.length, iStep = 0; iStep < nSteps; ++iStep) {
  250. // pull out the pipeline element as an object
  251. var pipeElement = pipeline[iStep];
  252. if (!(pipeElement instanceof Object)) throw new Error("pipeline element " + iStep + " is not an object; code 15942");
  253. var obj = pipeElement;
  254. // Parse a pipeline stage from 'obj'.
  255. if (Object.keys(obj).length !== 1) throw new Error("A pipeline stage specification object must contain exactly one field; code 16435");
  256. var stageName = Object.keys(obj)[0],
  257. stageSpec = obj[stageName];
  258. // Create a DocumentSource pipeline stage from 'stageSpec'.
  259. var desc = klass.stageDesc[stageName];
  260. if (!desc) throw new Error("Unrecognized pipeline stage name: '" + stageName + "'; code 16436");
  261. // Parse the stage
  262. var stage = desc(stageSpec, ctx);
  263. if (!stage) throw new Error("Stage must not be undefined!"); // verify(stage)
  264. sources.push(stage);
  265. if(stage.constructor === OutDocumentSource && iStep !== nSteps - 1) {
  266. throw new Error("$out can only be the final stage in the pipeline; code 16991");
  267. }
  268. }
  269. return sources;
  270. };
  271. /**
  272. * Create a pipeline from the command.
  273. * @static
  274. * @method parseCommand
  275. * @param cmdObj {Object} The command object sent from the client
  276. * @param cmdObj.aggregate {Array} the thing to aggregate against; // NOTE: DEVIATION FROM MONGO: expects an Array of inputs rather than a collection name
  277. * @param cmdObj.pipeline {Object} the JSON pipeline of `DocumentSource` specs
  278. * @param cmdObj.explain {Boolean} should explain?
  279. * @param cmdObj.fromRouter {Boolean} is from router?
  280. * @param cmdObj.splitMongodPipeline {Boolean} should split?
  281. * @param ctx {Object} Not used yet in mungedb-aggregate
  282. * @returns {Array} the pipeline, if created, otherwise a NULL reference
  283. **/
  284. klass.parseCommand = function parseCommand(cmdObj, ctx){
  285. var pipelineNamespace = require("./"),
  286. Pipeline = pipelineNamespace.Pipeline, // using require in case Pipeline gets replaced with an extension
  287. pipelineInst = new Pipeline(ctx);
  288. //gather the specification for the aggregation
  289. var pipeline;
  290. for(var fieldName in cmdObj){
  291. var cmdElement = cmdObj[fieldName];
  292. if(fieldName[0] == "$") continue;
  293. else if(fieldName == "cursor") continue;
  294. else if(fieldName == klass.COMMAND_NAME) continue; //look for the aggregation command
  295. else if(fieldName == klass.PIPELINE_NAME) pipeline = cmdElement; //check for the pipeline of JSON doc srcs
  296. else if(fieldName == klass.EXPLAIN_NAME) pipelineInst.explain = cmdElement; //check for explain option
  297. else if(fieldName == klass.FROM_ROUTER_NAME) ctx.inShard = cmdElement; //if the request came from the router, we're in a shard
  298. else if(fieldName == "allowDiskUsage") {
  299. if(typeof cmdElement !== 'boolean') throw new Error("allowDiskUsage must be a bool, not a " + typeof allowDiskUsage+ "; uassert code 16949");
  300. }
  301. else throw new Error("unrecognized field " + JSON.stringify(fieldName));
  302. }
  303. /**
  304. * If we get here, we've harvested the fields we expect for a pipeline
  305. * Set up the specified document source pipeline.
  306. **/
  307. // NOTE: DEVIATION FROM MONGO: split this into a separate function to simplify and better allow for extensions (now in parseDocumentSources)
  308. pipelineInst.sources = Pipeline.parseDocumentSources(pipeline, ctx);
  309. klass.optimizations.local.moveMatchBeforeSort(pipelineInst);
  310. klass.optimizations.local.moveLimitBeforeSkip(pipelineInst);
  311. klass.optimizations.local.coalesceAdjacent(pipelineInst);
  312. klass.optimizations.local.optimizeEachDocumentSource(pipelineInst);
  313. klass.optimizations.local.duplicateMatchBeforeInitalRedact(pipelineInst);
  314. return pipelineInst;
  315. };
  316. // sync callback for Pipeline#run if omitted
  317. klass.SYNC_CALLBACK = function(err, results){
  318. if (err) throw err;
  319. return results.result;
  320. };
  321. function ifError(err) {
  322. if (err) throw err;
  323. }
  324. /**
  325. * Gets the initial $match query when $match is the first pipeline stage
  326. * @method run
  327. * @param inputSource {DocumentSource} The input document source for the pipeline
  328. * @param [callback] {Function} Optional callback function if using async extensions
  329. * @return {Object} An empty object or the match spec
  330. **/
  331. proto.getInitialQuery = function getInitialQuery() {
  332. var sources = this.sources;
  333. if(sources.length === 0) {
  334. return {};
  335. }
  336. /* look for an initial $match */
  337. var match = sources[0].constructor === MatchDocumentSource ? sources[0] : undefined;
  338. if(!match) return {};
  339. return match.getQuery();
  340. };
  341. /**
  342. * Creates the JSON representation of the pipeline
  343. * @method run
  344. * @param inputSource {DocumentSource} The input document source for the pipeline
  345. * @param [callback] {Function} Optional callback function if using async extensions
  346. * @return {Object} An empty object or the match spec
  347. **/
  348. proto.serialize = function serialize() {
  349. var serialized = {},
  350. array = [];
  351. // create an array out of the pipeline operations
  352. this.sources.forEach(function(source) {
  353. source.serializeToArray(array);
  354. });
  355. serialized[klass.COMMAND_NAME] = this.ctx && this.ctx.ns && this.ctx.ns.coll ? this.ctx.ns.coll : '';
  356. serialized[klass.PIPELINE_NAME] = array;
  357. if(this.explain) serialized[klass.EXPLAIN_NAME] = this.explain;
  358. return serialized;
  359. };
  360. /**
  361. * Points each source at its previous source
  362. * @method stitch
  363. **/
  364. proto.stitch = function stitch() {
  365. if(this.sources.length <= 0) throw new Error("should not have an empty pipeline; massert code 16600");
  366. /* chain together the sources we found */
  367. var prevSource = this.sources[0];
  368. for(var srci = 1, srcn = this.sources.length; srci < srcn; srci++) {
  369. var tempSource = this.sources[srci];
  370. tempSource.setSource(prevSource);
  371. prevSource = tempSource;
  372. }
  373. };
  374. /**
  375. * Run the pipeline
  376. * @method run
  377. * @param callback {Function} Optional. Run the pipeline in async mode; callback(err, result)
  378. * @return result {Object} The result of executing the pipeline
  379. **/
  380. proto.run = function run(callback) {
  381. // should not get here in the explain case
  382. if(this.explain) throw new Error("Should not be running a pipeline in explain mode!");
  383. /* NOTE: DEVIATION FROM MONGO SOURCE. WE'RE SUPPORTING SYNC AND ASYNC */
  384. if(this.SYNC_MODE) {
  385. callback();
  386. return this._runSync();
  387. } else {
  388. return this._runAsync(callback);
  389. }
  390. };
  391. /**
  392. * Get the last document source in the pipeline
  393. * @method _getFinalSource
  394. * @return {Object} The DocumentSource at the end of the pipeline
  395. * @private
  396. **/
  397. proto._getFinalSource = function _getFinalSource() {
  398. return this.sources[this.sources.length - 1];
  399. };
  400. /**
  401. * Run the pipeline synchronously
  402. * @method _runSync
  403. * @return {Object} The results object {result:resultArray}
  404. * @private
  405. **/
  406. proto._runSync = function _runSync(callback) {
  407. var resultArray = [],
  408. finalSource = this._getFinalSource(),
  409. handleErr = function(err) {
  410. if(err) throw err;
  411. },
  412. next;
  413. while((next = finalSource.getNext(handleErr)) !== DocumentSource.EOF) {
  414. resultArray.push(next);
  415. }
  416. return {result:resultArray};
  417. };
  418. /**
  419. * Run the pipeline asynchronously
  420. * @method _runAsync
  421. * @param callback {Function} callback(err, resultObject)
  422. * @private
  423. **/
  424. proto._runAsync = function _runAsync(callback) {
  425. var resultArray = [],
  426. finalSource = this._getFinalSource(),
  427. gotNext = function(err, doc) {
  428. if(err) return callback(err);
  429. if(doc !== DocumentSource.EOF) {
  430. resultArray.push(doc);
  431. return setImmediate(function() { //setImmediate to avoid callstack size issues
  432. finalSource.getNext(gotNext);
  433. });
  434. } else {
  435. return callback(null, {result:resultArray});
  436. }
  437. };
  438. finalSource.getNext(gotNext);
  439. };
  440. /**
  441. * Get the pipeline explanation
  442. * @method writeExplainOps
  443. * @return {Array} An array of source explanations
  444. **/
  445. proto.writeExplainOps = function writeExplainOps() {
  446. var array = [];
  447. this.sources.forEach(function(source) {
  448. source.serializeToArray(array, /*explain=*/true);
  449. });
  450. return array;
  451. };
  452. /**
  453. * Set the source of documents for the pipeline
  454. * @method addInitialSource
  455. * @param source {DocumentSource}
  456. **/
  457. proto.addInitialSource = function addInitialSource(source) {
  458. this.sources.unshift(source);
  459. };
  460. //SKIPPED: canRunInMongos
  461. proto.getDependencies = function getDependencies (initialQuery) {
  462. var deps, knowAllFields = false;
  463. //NOTE: Deviation from Mongo -- We aren't using Meta and textscore
  464. for (var i=0; i < sources.length() && !knowAllFields; i++) {
  465. var localDeps,
  466. status = sources[i].getDependencies(localDeps);
  467. if (status == DocumentSource.GetDepsReturn.NOT_SUPPORTED) {
  468. // Assume this stage needs everything. We may still know something about our
  469. // dependencies if an earlier stage returned either EXHAUSTIVE_FIELDS or
  470. // EXHAUSTIVE_META.
  471. break;
  472. }
  473. if (!knowAllFields) {
  474. //C++ insert this range: deps.fields.insert(localDeps.fields.begin(), localDeps.fields.end());
  475. for (var j = 0; j < localDeps.fields.keys.length; j++) {
  476. var key = localDeps.fields.keys[i];
  477. deps.fields[key] = localDeps.fields[key];
  478. }
  479. if (localDeps.needWholeDocument)
  480. deps.needWholeDocument = true;
  481. knowAllFields = status & DocumentSource.GetDepsReturn.EXHAUSTIVE_FIELDS;
  482. }
  483. }
  484. if (!knowAllFields)
  485. deps.needWholeDocument = true; // don't know all fields we need
  486. return deps;
  487. };