CursorDocumentSource.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. "use strict";
  2. var async = require("async"),
  3. Runner = require("../../query/Runner"),
  4. DocumentSource = require("./DocumentSource"),
  5. LimitDocumentSource = require("./LimitDocumentSource");
  6. /**
  7. * Constructs and returns Documents from the BSONObj objects produced by a supplied Runner.
  8. * An object of this type may only be used by one thread, see SERVER-6123.
  9. *
  10. * This is usually put at the beginning of a chain of document sources
  11. * in order to fetch data from the database.
  12. *
  13. * @class CursorDocumentSource
  14. * @namespace mungedb-aggregate.pipeline.documentSources
  15. * @module mungedb-aggregate
  16. * @constructor
  17. * @param ns {String}
  18. * @param runner {Runner}
  19. * @param expCtx {Object}
  20. */
  21. var CursorDocumentSource = module.exports = CursorDocumentSource = function CursorDocumentSource(ns, runner, expCtx){
  22. base.call(this, expCtx);
  23. this._docsAddedToBatches = 0; // for _limit enforcement
  24. this._ns = ns;
  25. this._runner = runner;
  26. this._currentBatch = [];
  27. this._currentBatchIndex = 0; //NOTE: DEVIATION FROM MONGO: they do not track index
  28. // BSONObj members must outlive _projection and cursor.
  29. this._query = undefined;
  30. this._sort = undefined;
  31. this._projection = undefined;
  32. this._dependencies = undefined;
  33. this._limit = undefined;
  34. this._firstRun = true; //NOTE: DEVIATION FROM MONGO: to ensure that the callstack does not get too large doing things syncronously
  35. }, klass = CursorDocumentSource, base = DocumentSource, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}}); //jshint ignore:line
  36. proto.getSourceName = function getSourceName() {
  37. return "$cursor";
  38. };
  39. proto.getNext = function getNext() {
  40. if (this.expCtx && this.expCtx.checkForInterrupt) this.expCtx.checkForInterrupt();
  41. if (this._currentBatchIndex >= this._currentBatch.length) {
  42. this._currentBatchIndex = 0;
  43. this._currentBatch = [];
  44. this._loadBatch();
  45. if (this._currentBatch.length === 0)
  46. return null;
  47. }
  48. var out = this._currentBatch[this._currentBatchIndex];
  49. this._currentBatchIndex++;
  50. return out;
  51. };
  52. proto.dispose = function dispose() {
  53. // Can't call in to Runner or ClientCursor registries from this function since it will be
  54. // called when an agg cursor is killed which would cause a deadlock.
  55. this._runner = undefined;
  56. this._currentBatch = [];
  57. };
  58. proto._loadBatch = function _loadBatch() {
  59. if (!this._runner) {
  60. this.dispose();
  61. return;
  62. }
  63. this._runner.restoreState();
  64. var obj;
  65. while ((obj = this._runner.getNext()) && this._runner._state === Runner.RunnerState.RUNNER_ADVANCED) {
  66. if (this._dependencies) {
  67. this._currentBatch.push(this._dependencies.extractFields(obj));
  68. } else {
  69. this._currentBatch.push(obj);
  70. }
  71. if (this._limit) {
  72. if (++this._docsAddedToBatches === this._limit.getLimit()) {
  73. break;
  74. }
  75. if (this._docsAddedToBatches > this._limit.getLimit()) return new Error("Assertion failure: end of limit");
  76. }
  77. var memUsageDocs = this._currentBatch.length;
  78. if (memUsageDocs >= klass.MaxDocumentsToReturnToClientAtOnce) {
  79. // End self batch and prepare Runner for yielding.
  80. this._runner.saveState();
  81. return;
  82. }
  83. }
  84. var state = this._runner._state;
  85. // If we got here, there won't be any more documents, so destroy the runner. Can't use
  86. // dispose since we want to keep the _currentBatch.
  87. this._runner = undefined;
  88. if (state === Runner.RunnerState.RUNNER_DEAD)
  89. throw new Error("collection or index disappeared when cursor yielded; uassert code 16028");
  90. if (state === Runner.RunnerState.RUNNER_ERROR)
  91. throw new Error("cursor encountered an error; uassert code 17285");
  92. if (state !== Runner.RunnerState.RUNNER_EOF && state !== Runner.RunnerState.RUNNER_ADVANCED){
  93. throw new Error("Unexpected return from Runner::getNext " + JSON.stringify(state) + "; massert code 17286");
  94. }
  95. };
  96. proto.setSource = function setSource(theSource) {
  97. // this doesn't take a source
  98. throw new Error("Assertion error: this doesnt take a source");
  99. };
  100. /**
  101. * returns -1 for no limit
  102. * @method getLimit
  103. */
  104. proto.getLimit = function getLimit() {
  105. return this._limit ? this._limit.getLimit() : -1;
  106. };
  107. proto.coalesce = function coalesce(nextSource) {
  108. // Note: Currently we assume the $limit is logically after any $sort or
  109. // $match. If we ever pull in $match or $sort using this method, we
  110. // will need to keep track of the order of the sub-stages.
  111. if (!this._limit) {
  112. this._limit = nextSource instanceof LimitDocumentSource ? nextSource : undefined;
  113. return Boolean(this._limit); // false if next is not a $limit
  114. } else {
  115. return this._limit.coalesce(nextSource);
  116. }
  117. return false;
  118. };
  119. function extractInfo(o) { //NOTE: DEVIATION FROM MONGO: skipping a lot of explain for now
  120. return o;
  121. }
  122. proto.serialize = function serialize(explain) { //NOTE: DEVIATION FROM MONGO: parts of this not implemented, may want later
  123. // we never parse a documentSourceCursor, so we only serialize for explain
  124. if (!explain)
  125. return null;
  126. var plan;
  127. // explainStatus = {code:ErrorCodes.INTERNAL_ERROR, description:""};
  128. //NOTE: DEVIATION FROM MONGO: our `Runner#getInfo()` API is a little broken
  129. //TODO: fix our `Runner#getInfo()` API to match their API
  130. {
  131. if (!this._runner)
  132. throw new Error("No _runner. Were we disposed before explained?; massert code 17392");
  133. this._runner.restoreState();
  134. var explainRaw = {};
  135. explainRaw = this._runner.getInfo(explain, null);
  136. if (explainRaw) //TODO: use this instead: if (explainStatus.code === ErrorCodes.OK)
  137. plan = explainRaw;
  138. this._runner.saveState();
  139. }
  140. var out = {};
  141. out.query = this._query;
  142. if (this._sort && Object.keys(this._sort).length > 0)
  143. out.sort = this._sort;
  144. if (this._limit)
  145. out.limit = this._limit.getLimit();
  146. if (this._projection && Object.keys(this._projection).length > 0)
  147. out.fields = this._projection;
  148. if (true) { //TODO: use this instead: if (explainStatus.code === ErrorCodes.OK) {
  149. out.plan = extractInfo(plan);
  150. } else {
  151. out.planError = "ERROR EXPLAINING PLAN"; //TODO: use this instead: explainStatus
  152. }
  153. var doc = {};
  154. doc[this.getSourceName()] = out;
  155. return doc;
  156. };
  157. /**
  158. * Create a document source based on a passed-in Runner.
  159. *
  160. * This is usually put at the beginning of a chain of document sources
  161. * in order to fetch data from the database.
  162. *
  163. * @method create
  164. * @static
  165. * @param ns {String}
  166. * @param runner {Runner}
  167. * @param expCtx {Object}
  168. */
  169. klass.create = function create(ns, runner, expCtx) {
  170. return new CursorDocumentSource(ns, runner, expCtx);
  171. };
  172. /**
  173. * Informs this object of projection and dependency information.
  174. *
  175. * @method setProjection
  176. * @param projection A projection specification describing the fields needed by the rest of
  177. * the pipeline.
  178. * @param deps The output of DepsTracker::toParsedDeps
  179. */
  180. proto.setProjection = function setProjection(projection, deps) {
  181. this._projection = projection;
  182. this._dependencies = deps;
  183. };
  184. proto.isValidInitialSource = function(){
  185. return true;
  186. };
  187. /**
  188. * Record the query that was specified for the cursor this wraps, if
  189. * any.
  190. *
  191. * This should be captured after any optimizations are applied to
  192. * the pipeline so that it reflects what is really used.
  193. *
  194. * This gets used for explain output.
  195. *
  196. * @method setQuery
  197. * @param {Object} pBsonObj the query to record
  198. */
  199. proto.setQuery = function setQuery(query) {
  200. this._query = query;
  201. };
  202. /**
  203. * Record the sort that was specified for the cursor this wraps, if
  204. * any.
  205. *
  206. * This should be captured after any optimizations are applied to
  207. * the pipeline so that it reflects what is really used.
  208. *
  209. * This gets used for explain output.
  210. *
  211. * @method setSort
  212. * @param {Object} pBsonObj the sort to record
  213. */
  214. proto.setSort = function setSort(sort) {
  215. this._sort = sort;
  216. };
  217. klass.MaxDocumentsToReturnToClientAtOnce = 150; //NOTE: DEVIATION FROM MONGO: put this here and using MaxDocuments instead of MaxBytes