CursorDocumentSource.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. "use strict";
  2. var async = require('async'),
  3. Value = require('../Value'),
  4. Runner = require('../../query/Runner'),
  5. DocumentSource = require('./DocumentSource'),
  6. LimitDocumentSource = require('./LimitDocumentSource');
  7. /**
  8. * Constructs and returns Documents from the BSONObj objects produced by a supplied Runner.
  9. * An object of this type may only be used by one thread, see SERVER-6123.
  10. *
  11. * This is usually put at the beginning of a chain of document sources
  12. * in order to fetch data from the database.
  13. *
  14. * @class CursorDocumentSource
  15. * @namespace mungedb-aggregate.pipeline.documentSources
  16. * @module mungedb-aggregate
  17. * @constructor
  18. * @param {CursorDocumentSource.CursorWithContext} cursorWithContext the cursor to use to fetch data
  19. **/
  20. var CursorDocumentSource = module.exports = CursorDocumentSource = function CursorDocumentSource(namespace, runner, expCtx){
  21. base.call(this, expCtx);
  22. this._docsAddedToBatches = 0;
  23. this._ns = namespace;
  24. this._runner = runner;
  25. }, klass = CursorDocumentSource, base = DocumentSource, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  26. klass.MaxDocumentsToReturnToClientAtOnce = 150; //DEVIATION: we are using documents instead of bytes
  27. proto._currentBatch = [];
  28. proto._currentBatchIndex = 0;
  29. // BSONObj members must outlive _projection and cursor.
  30. proto._query = undefined;
  31. proto._sort = undefined;
  32. proto._projection = undefined;
  33. proto._dependencies = undefined;
  34. proto._limit = undefined;
  35. proto._docsAddedToBatches = undefined; // for _limit enforcement
  36. proto._ns = undefined;
  37. proto._runner = undefined; // PipelineRunner holds a weak_ptr to this.
  38. proto.isValidInitialSource = function(){
  39. return true;
  40. };
  41. /**
  42. * Release the Cursor and the read lock it requires, but without changing the other data.
  43. * Releasing the lock is required for proper concurrency, see SERVER-6123. This
  44. * functionality is also used by the explain version of pipeline execution.
  45. *
  46. * @method dispose
  47. **/
  48. proto.dispose = function dispose() {
  49. if (this._runner) this._runner.reset();
  50. this._currentBatch = [];
  51. };
  52. /**
  53. * Get the source's name.
  54. * @method getSourceName
  55. * @returns {String} the string name of the source as a constant string; this is static, and there's no need to worry about adopting it
  56. **/
  57. proto.getSourceName = function getSourceName() {
  58. return "$cursor";
  59. };
  60. /**
  61. * Returns the next Document if there is one
  62. *
  63. * @method getNext
  64. **/
  65. proto.getNext = function getNext(callback) {
  66. if (this.expCtx && this.expCtx.checkForInterrupt && this.expCtx.checkForInterrupt()){
  67. return callback(new Error('Interrupted'));
  68. }
  69. var self = this;
  70. if (self._currentBatchIndex >= self._currentBatch.length) {
  71. self._currentBatchIndex = 0;
  72. self._currentBatch = [];
  73. return self.loadBatch(function(err){
  74. if (err) return callback(err);
  75. if (self._currentBatch.length === 0)
  76. return callback(null, null);
  77. return callback(null, self._currentBatch[self._currentBatchIndex++]);
  78. });
  79. }
  80. return callback(null, self._currentBatch[self._currentBatchIndex++]);
  81. };
  82. /**
  83. * Attempt to coalesce this DocumentSource with any $limits that it encounters
  84. *
  85. * @method coalesce
  86. * @param {DocumentSource} nextSource the next source in the document processing chain.
  87. * @returns {Boolean} whether or not the attempt to coalesce was successful or not; if the attempt was not successful, nothing has been changed
  88. **/
  89. proto.coalesce = function coalesce(nextSource) {
  90. // Note: Currently we assume the $limit is logically after any $sort or
  91. // $match. If we ever pull in $match or $sort using this method, we
  92. // will need to keep track of the order of the sub-stages.
  93. if (!this._limit) {
  94. if (nextSource instanceof LimitDocumentSource) {
  95. this._limit = nextSource;
  96. return this._limit;
  97. }
  98. return false;// false if next is not a $limit
  99. }
  100. else {
  101. return this._limit.coalesce(nextSource);
  102. }
  103. return false;
  104. };
  105. /**
  106. * Record the query that was specified for the cursor this wraps, if
  107. * any.
  108. *
  109. * This should be captured after any optimizations are applied to
  110. * the pipeline so that it reflects what is really used.
  111. *
  112. * This gets used for explain output.
  113. *
  114. * @method setQuery
  115. * @param {Object} pBsonObj the query to record
  116. **/
  117. proto.setQuery = function setQuery(query) {
  118. this._query = query;
  119. };
  120. /**
  121. * Record the sort that was specified for the cursor this wraps, if
  122. * any.
  123. *
  124. * This should be captured after any optimizations are applied to
  125. * the pipeline so that it reflects what is really used.
  126. *
  127. * This gets used for explain output.
  128. *
  129. * @method setSort
  130. * @param {Object} pBsonObj the query to record
  131. **/
  132. proto.setSort = function setSort(sort) {
  133. this._sort = sort;
  134. };
  135. /**
  136. * Informs this object of projection and dependency information.
  137. *
  138. * @method setProjection
  139. * @param {Object} projection
  140. **/
  141. proto.setProjection = function setProjection(projection, deps) {
  142. this._projection = projection;
  143. this._dependencies = deps;
  144. };
  145. /**
  146. *
  147. * @method setSource
  148. * @param source {DocumentSource} the underlying source to use
  149. * @param callback {Function} a `mungedb-aggregate`-specific extension to the API to half-way support reading from async sources
  150. **/
  151. proto.setSource = function setSource(theSource) {
  152. throw new Error('this doesnt take a source');
  153. };
  154. proto.serialize = function serialize(explain) {
  155. // we never parse a documentSourceCursor, so we only serialize for explain
  156. if (!explain)
  157. return {};
  158. var out = {};
  159. out[this.getSourceName()] = {
  160. query: this._query,
  161. sort: this._sort ? this._sort : null,
  162. limit: this._limit ? this._limit.getLimit() : null,
  163. fields: this._projection ? this._projection : null,
  164. plan: this._runner.getInfo(explain)
  165. };
  166. return out;
  167. };
  168. /**
  169. * returns -1 for no limit
  170. *
  171. * @method getLimit
  172. **/
  173. proto.getLimit = function getLimit() {
  174. return this._limit ? this._limit.getLimit() : -1;
  175. };
  176. /**
  177. * Load a batch of documents from the Runner into the internal array
  178. *
  179. * @method loadBatch
  180. **/
  181. proto.loadBatch = function loadBatch(callback) {
  182. if (!this._runner) {
  183. this.dispose();
  184. return callback;
  185. }
  186. this._runner.restoreState();
  187. var self = this,
  188. whileBreak = false, // since we are in an async loop instead of a normal while loop, need to mimic the
  189. whileReturn = false; // functionality. These flags are similar to saying 'break' or 'return' from inside the loop
  190. return async.whilst(
  191. function test(){
  192. return !whileBreak && !whileReturn;
  193. },
  194. function(next) {
  195. return self._runner.getNext(function(err, obj, state){
  196. if (err) return next(err);
  197. if (state === Runner.RunnerState.RUNNER_ADVANCED) {
  198. if (self._dependencies) {
  199. self._currentBatch.push(self._dependencies.extractFields(obj));
  200. } else {
  201. self._currentBatch.push(obj);
  202. }
  203. if (self._limit) {
  204. if (++self._docsAddedToBatches === self._limit.getLimit()) {
  205. whileBreak = true;
  206. return next();
  207. }
  208. //this was originally a 'verify' in the mongo code
  209. if (self._docsAddedToBatches > self._limit.getLimit()){
  210. return next(new Error('documents collected past the end of the limit'));
  211. }
  212. }
  213. if (self._currentBatch >= klass.MaxDocumentsToReturnToClientAtOnce) {
  214. // End self batch and prepare Runner for yielding.
  215. self._runner.saveState();
  216. whileReturn = true;
  217. }
  218. } else {
  219. whileBreak = true;
  220. }
  221. return next();
  222. });
  223. },
  224. function(err){
  225. if (!whileReturn){
  226. self._runner.reset();
  227. }
  228. callback(err);
  229. }
  230. );
  231. };