Pipeline.js 19 KB

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