12c9c277e7ad709e2acee7e415571f89768514f9
[aai/esr-gui.git] /
1 "use strict";
2
3 var Long = require('bson').Long
4   , Logger = require('./connection/logger')
5   , MongoError = require('./error')
6   , f = require('util').format;
7
8 /**
9  * This is a cursor results callback
10  *
11  * @callback resultCallback
12  * @param {error} error An error object. Set to null if no error present
13  * @param {object} document
14  */
15
16 /**
17  * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB
18  * allowing for iteration over the results returned from the underlying query.
19  *
20  * **CURSORS Cannot directly be instantiated**
21  * @example
22  * var Server = require('mongodb-core').Server
23  *   , ReadPreference = require('mongodb-core').ReadPreference
24  *   , assert = require('assert');
25  *
26  * var server = new Server({host: 'localhost', port: 27017});
27  * // Wait for the connection event
28  * server.on('connect', function(server) {
29  *   assert.equal(null, err);
30  *
31  *   // Execute the write
32  *   var cursor = _server.cursor('integration_tests.inserts_example4', {
33  *       find: 'integration_tests.example4'
34  *     , query: {a:1}
35  *   }, {
36  *     readPreference: new ReadPreference('secondary');
37  *   });
38  *
39  *   // Get the first document
40  *   cursor.next(function(err, doc) {
41  *     assert.equal(null, err);
42  *     server.destroy();
43  *   });
44  * });
45  *
46  * // Start connecting
47  * server.connect();
48  */
49
50 /**
51  * Creates a new Cursor, not to be used directly
52  * @class
53  * @param {object} bson An instance of the BSON parser
54  * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
55  * @param {{object}|Long} cmd The selector (can be a command or a cursorId)
56  * @param {object} [options=null] Optional settings.
57  * @param {object} [options.batchSize=1000] Batchsize for the operation
58  * @param {array} [options.documents=[]] Initial documents list for cursor
59  * @param {object} [options.transforms=null] Transform methods for the cursor results
60  * @param {function} [options.transforms.query] Transform the value returned from the initial query
61  * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next
62  * @param {object} topology The server topology instance.
63  * @param {object} topologyOptions The server topology options.
64  * @return {Cursor} A cursor instance
65  * @property {number} cursorBatchSize The current cursorBatchSize for the cursor
66  * @property {number} cursorLimit The current cursorLimit for the cursor
67  * @property {number} cursorSkip The current cursorSkip for the cursor
68  */
69 var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) {
70   options = options || {};
71   // Cursor reference
72   var self = this;
73   // Initial query
74   var query = null;
75
76   // Cursor pool
77   this.pool = null;
78   // Cursor server
79   this.server = null;
80
81   // Do we have a not connected handler
82   this.disconnectHandler = options.disconnectHandler;
83
84   // Set local values
85   this.bson = bson;
86   this.ns = ns;
87   this.cmd = cmd;
88   this.options = options;
89   this.topology = topology;
90
91   // All internal state
92   this.cursorState = {
93       cursorId: null
94     , cmd: cmd
95     , documents: options.documents || []
96     , cursorIndex: 0
97     , dead: false
98     , killed: false
99     , init: false
100     , notified: false
101     , limit: options.limit || cmd.limit || 0
102     , skip: options.skip || cmd.skip || 0
103     , batchSize: options.batchSize || cmd.batchSize || 1000
104     , currentLimit: 0
105     // Result field name if not a cursor (contains the array of results)
106     , transforms: options.transforms
107   }
108
109   // Add promoteLong to cursor state
110   if(typeof topologyOptions.promoteLongs == 'boolean') {
111     this.cursorState.promoteLongs = topologyOptions.promoteLongs;
112   } else if(typeof options.promoteLongs == 'boolean') {
113     this.cursorState.promoteLongs = options.promoteLongs;
114   }
115
116   // Add promoteValues to cursor state
117   if(typeof topologyOptions.promoteValues == 'boolean') {
118     this.cursorState.promoteValues = topologyOptions.promoteValues;
119   } else if(typeof options.promoteValues == 'boolean') {
120     this.cursorState.promoteValues = options.promoteValues;
121   }
122
123   // Add promoteBuffers to cursor state
124   if(typeof topologyOptions.promoteBuffers == 'boolean') {
125     this.cursorState.promoteBuffers = topologyOptions.promoteBuffers;
126   } else if(typeof options.promoteBuffers == 'boolean') {
127     this.cursorState.promoteBuffers = options.promoteBuffers;
128   }
129
130   // Logger
131   this.logger = Logger('Cursor', topologyOptions);
132
133   //
134   // Did we pass in a cursor id
135   if(typeof cmd == 'number') {
136     this.cursorState.cursorId = Long.fromNumber(cmd);
137     this.cursorState.lastCursorId = this.cursorState.cursorId;
138   } else if(cmd instanceof Long) {
139     this.cursorState.cursorId = cmd;
140     this.cursorState.lastCursorId = cmd;
141   }
142 }
143
144 Cursor.prototype.setCursorBatchSize = function(value) {
145   this.cursorState.batchSize = value;
146 }
147
148 Cursor.prototype.cursorBatchSize = function() {
149   return this.cursorState.batchSize;
150 }
151
152 Cursor.prototype.setCursorLimit = function(value) {
153   this.cursorState.limit = value;
154 }
155
156 Cursor.prototype.cursorLimit = function() {
157   return this.cursorState.limit;
158 }
159
160 Cursor.prototype.setCursorSkip = function(value) {
161   this.cursorState.skip = value;
162 }
163
164 Cursor.prototype.cursorSkip = function() {
165   return this.cursorState.skip;
166 }
167
168 //
169 // Handle callback (including any exceptions thrown)
170 var handleCallback = function(callback, err, result) {
171   try {
172     callback(err, result);
173   } catch(err) {
174     process.nextTick(function() {
175       throw err;
176     });
177   }
178 }
179
180 // Internal methods
181 Cursor.prototype._find = function(callback) {
182   var self = this;
183
184   if(self.logger.isDebug()) {
185     self.logger.debug(f("issue initial query [%s] with flags [%s]"
186       , JSON.stringify(self.cmd)
187       , JSON.stringify(self.query)));
188   }
189
190   var queryCallback = function(err, r) {
191     if(err) return callback(err);
192
193     // Get the raw message
194     var result = r.message;
195
196     // Query failure bit set
197     if(result.queryFailure) {
198       return callback(MongoError.create(result.documents[0]), null);
199     }
200
201     // Check if we have a command cursor
202     if(Array.isArray(result.documents) && result.documents.length == 1
203       && (!self.cmd.find || (self.cmd.find && self.cmd.virtual == false))
204       && (result.documents[0].cursor != 'string'
205         || result.documents[0]['$err']
206         || result.documents[0]['errmsg']
207         || Array.isArray(result.documents[0].result))
208       ) {
209
210       // We have a an error document return the error
211       if(result.documents[0]['$err']
212         || result.documents[0]['errmsg']) {
213         return callback(MongoError.create(result.documents[0]), null);
214       }
215
216       // We have a cursor document
217       if(result.documents[0].cursor != null
218         && typeof result.documents[0].cursor != 'string') {
219           var id = result.documents[0].cursor.id;
220           // If we have a namespace change set the new namespace for getmores
221           if(result.documents[0].cursor.ns) {
222             self.ns = result.documents[0].cursor.ns;
223           }
224           // Promote id to long if needed
225           self.cursorState.cursorId = typeof id == 'number' ? Long.fromNumber(id) : id;
226           self.cursorState.lastCursorId = self.cursorState.cursorId;
227           // If we have a firstBatch set it
228           if(Array.isArray(result.documents[0].cursor.firstBatch)) {
229             self.cursorState.documents = result.documents[0].cursor.firstBatch;//.reverse();
230           }
231
232           // Return after processing command cursor
233           return callback(null, null);
234       }
235
236       if(Array.isArray(result.documents[0].result)) {
237         self.cursorState.documents = result.documents[0].result;
238         self.cursorState.cursorId = Long.ZERO;
239         return callback(null, null);
240       }
241     }
242
243     // Otherwise fall back to regular find path
244     self.cursorState.cursorId = result.cursorId;
245     self.cursorState.documents = result.documents;
246     self.cursorState.lastCursorId = result.cursorId;
247
248     // Transform the results with passed in transformation method if provided
249     if(self.cursorState.transforms && typeof self.cursorState.transforms.query == 'function') {
250       self.cursorState.documents = self.cursorState.transforms.query(result);
251     }
252
253     // Return callback
254     callback(null, null);
255   }
256
257   // Options passed to the pool
258   var queryOptions = {};
259
260   // If we have a raw query decorate the function
261   if(self.options.raw || self.cmd.raw) {
262     // queryCallback.raw = self.options.raw || self.cmd.raw;
263     queryOptions.raw = self.options.raw || self.cmd.raw;
264   }
265
266   // Do we have documentsReturnedIn set on the query
267   if(typeof self.query.documentsReturnedIn == 'string') {
268     // queryCallback.documentsReturnedIn = self.query.documentsReturnedIn;
269     queryOptions.documentsReturnedIn = self.query.documentsReturnedIn;
270   }
271
272   // Add promote Long value if defined
273   if(typeof self.cursorState.promoteLongs == 'boolean') {
274     queryOptions.promoteLongs = self.cursorState.promoteLongs;
275   }
276
277   // Add promote values if defined
278   if(typeof self.cursorState.promoteValues == 'boolean') {
279     queryOptions.promoteValues = self.cursorState.promoteValues;
280   }
281
282   // Add promote values if defined
283   if(typeof self.cursorState.promoteBuffers == 'boolean') {
284     queryOptions.promoteBuffers = self.cursorState.promoteBuffers;
285   }
286
287   // Write the initial command out
288   self.server.s.pool.write(self.query, queryOptions, queryCallback);
289 }
290
291 Cursor.prototype._getmore = function(callback) {
292   if(this.logger.isDebug()) this.logger.debug(f("schedule getMore call for query [%s]", JSON.stringify(this.query)))
293   // Determine if it's a raw query
294   var raw = this.options.raw || this.cmd.raw;
295
296   // Set the current batchSize
297   var batchSize = this.cursorState.batchSize;
298   if(this.cursorState.limit > 0
299     && ((this.cursorState.currentLimit + batchSize) > this.cursorState.limit)) {
300     batchSize = this.cursorState.limit - this.cursorState.currentLimit;
301   }
302
303   // Default pool
304   var pool = this.server.s.pool;
305
306   // We have a wire protocol handler
307   this.server.wireProtocolHandler.getMore(this.bson, this.ns, this.cursorState, batchSize, raw, pool, this.options, callback);
308 }
309
310 Cursor.prototype._killcursor = function(callback) {
311   // Set cursor to dead
312   this.cursorState.dead = true;
313   this.cursorState.killed = true;
314   // Remove documents
315   this.cursorState.documents = [];
316
317   // If no cursor id just return
318   if(this.cursorState.cursorId == null || this.cursorState.cursorId.isZero() || this.cursorState.init == false) {
319     if(callback) callback(null, null);
320     return;
321   }
322
323   // Default pool
324   var pool = this.server.s.pool;
325   // Execute command
326   this.server.wireProtocolHandler.killCursor(this.bson, this.ns, this.cursorState.cursorId, pool, callback);
327 }
328
329 /**
330  * Clone the cursor
331  * @method
332  * @return {Cursor}
333  */
334 Cursor.prototype.clone = function() {
335   return this.topology.cursor(this.ns, this.cmd, this.options);
336 }
337
338 /**
339  * Checks if the cursor is dead
340  * @method
341  * @return {boolean} A boolean signifying if the cursor is dead or not
342  */
343 Cursor.prototype.isDead = function() {
344   return this.cursorState.dead == true;
345 }
346
347 /**
348  * Checks if the cursor was killed by the application
349  * @method
350  * @return {boolean} A boolean signifying if the cursor was killed by the application
351  */
352 Cursor.prototype.isKilled = function() {
353   return this.cursorState.killed == true;
354 }
355
356 /**
357  * Checks if the cursor notified it's caller about it's death
358  * @method
359  * @return {boolean} A boolean signifying if the cursor notified the callback
360  */
361 Cursor.prototype.isNotified = function() {
362   return this.cursorState.notified == true;
363 }
364
365 /**
366  * Returns current buffered documents length
367  * @method
368  * @return {number} The number of items in the buffered documents
369  */
370 Cursor.prototype.bufferedCount = function() {
371   return this.cursorState.documents.length - this.cursorState.cursorIndex;
372 }
373
374 /**
375  * Returns current buffered documents
376  * @method
377  * @return {Array} An array of buffered documents
378  */
379 Cursor.prototype.readBufferedDocuments = function(number) {
380   var unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex;
381   var length = number < unreadDocumentsLength ? number : unreadDocumentsLength;
382   var elements = this.cursorState.documents.slice(this.cursorState.cursorIndex, this.cursorState.cursorIndex + length);
383
384   // Transform the doc with passed in transformation method if provided
385   if(this.cursorState.transforms && typeof this.cursorState.transforms.doc == 'function') {
386     // Transform all the elements
387     for(var i = 0; i < elements.length; i++) {
388       elements[i] = this.cursorState.transforms.doc(elements[i]);
389     }
390   }
391
392   // Ensure we do not return any more documents than the limit imposed
393   // Just return the number of elements up to the limit
394   if(this.cursorState.limit > 0 && (this.cursorState.currentLimit + elements.length) > this.cursorState.limit) {
395     elements = elements.slice(0, (this.cursorState.limit - this.cursorState.currentLimit));
396     this.kill();
397   }
398
399   // Adjust current limit
400   this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length;
401   this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length;
402
403   // Return elements
404   return elements;
405 }
406
407 /**
408  * Kill the cursor
409  * @method
410  * @param {resultCallback} callback A callback function
411  */
412 Cursor.prototype.kill = function(callback) {
413   this._killcursor(callback);
414 }
415
416 /**
417  * Resets the cursor
418  * @method
419  * @return {null}
420  */
421 Cursor.prototype.rewind = function() {
422   if(this.cursorState.init) {
423     if(!this.cursorState.dead) {
424       this.kill();
425     }
426
427     this.cursorState.currentLimit = 0;
428     this.cursorState.init = false;
429     this.cursorState.dead = false;
430     this.cursorState.killed = false;
431     this.cursorState.notified = false;
432     this.cursorState.documents = [];
433     this.cursorState.cursorId = null;
434     this.cursorState.cursorIndex = 0;
435   }
436 }
437
438 /**
439  * Validate if the pool is dead and return error
440  */
441 var isConnectionDead = function(self, callback) {
442   if(self.pool
443     && self.pool.isDestroyed()) {
444     self.cursorState.notified = true;
445     self.cursorState.killed = true;
446     self.cursorState.documents = [];
447     self.cursorState.cursorIndex = 0;
448     callback(MongoError.create(f('connection to host %s:%s was destroyed', self.pool.host, self.pool.port)))
449     return true;
450   }
451
452   return false;
453 }
454
455 /**
456  * Validate if the cursor is dead but was not explicitly killed by user
457  */
458 var isCursorDeadButNotkilled = function(self, callback) {
459   // Cursor is dead but not marked killed, return null
460   if(self.cursorState.dead && !self.cursorState.killed) {
461     self.cursorState.notified = true;
462     self.cursorState.killed = true;
463     self.cursorState.documents = [];
464     self.cursorState.cursorIndex = 0;
465     handleCallback(callback, null, null);
466     return true;
467   }
468
469   return false;
470 }
471
472 /**
473  * Validate if the cursor is dead and was killed by user
474  */
475 var isCursorDeadAndKilled = function(self, callback) {
476   if(self.cursorState.dead && self.cursorState.killed) {
477     handleCallback(callback, MongoError.create("cursor is dead"));
478     return true;
479   }
480
481   return false;
482 }
483
484 /**
485  * Validate if the cursor was killed by the user
486  */
487 var isCursorKilled = function(self, callback) {
488   if(self.cursorState.killed) {
489     self.cursorState.notified = true;
490     self.cursorState.documents = [];
491     self.cursorState.cursorIndex = 0;
492     handleCallback(callback, null, null);
493     return true;
494   }
495
496   return false;
497 }
498
499 /**
500  * Mark cursor as being dead and notified
501  */
502 var setCursorDeadAndNotified = function(self, callback) {
503   self.cursorState.dead = true;
504   self.cursorState.notified = true;
505   self.cursorState.documents = [];
506   self.cursorState.cursorIndex = 0;
507   handleCallback(callback, null, null);
508 }
509
510 /**
511  * Mark cursor as being notified
512  */
513 var setCursorNotified = function(self, callback) {
514   self.cursorState.notified = true;
515   self.cursorState.documents = [];
516   self.cursorState.cursorIndex = 0;
517   handleCallback(callback, null, null);
518 }
519
520 var push = Array.prototype.push;
521
522 var nextFunction = function(self, callback) {
523   // We have notified about it
524   if(self.cursorState.notified) {
525     return callback(new Error('cursor is exhausted'));
526   }
527
528   // Cursor is killed return null
529   if(isCursorKilled(self, callback)) return;
530
531   // Cursor is dead but not marked killed, return null
532   if(isCursorDeadButNotkilled(self, callback)) return;
533
534   // We have a dead and killed cursor, attempting to call next should error
535   if(isCursorDeadAndKilled(self, callback)) return;
536
537   // We have just started the cursor
538   if(!self.cursorState.init) {
539     // Topology is not connected, save the call in the provided store to be
540     // Executed at some point when the handler deems it's reconnected
541     if(!self.topology.isConnected(self.options) && self.disconnectHandler != null) {
542       if (self.topology.isDestroyed()) {
543         // Topology was destroyed, so don't try to wait for it to reconnect
544         return callback(new MongoError('Topology was destroyed'));
545       }
546       return self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback);
547     }
548
549     try {
550       self.server = self.topology.getServer(self.options);
551     } catch(err) {
552       // Handle the error and add object to next method call
553       if(self.disconnectHandler != null) {
554         return self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback);
555       }
556
557       // Otherwise return the error
558       return callback(err);
559     }
560
561     // Set as init
562     self.cursorState.init = true;
563
564     // Server does not support server
565     if(self.cmd
566       && self.cmd.collation
567       && self.server.ismaster.maxWireVersion < 5) {
568       return callback(new MongoError(f('server %s does not support collation', self.server.name)));
569     }
570
571     try {
572       self.query = self.server.wireProtocolHandler.command(self.bson, self.ns, self.cmd, self.cursorState, self.topology, self.options);
573     } catch(err) {
574       return callback(err);
575     }
576   }
577
578   // If we don't have a cursorId execute the first query
579   if(self.cursorState.cursorId == null) {
580     // Check if pool is dead and return if not possible to
581     // execute the query against the db
582     if(isConnectionDead(self, callback)) return;
583
584     // Check if topology is destroyed
585     if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor')));
586
587     // query, cmd, options, cursorState, callback
588     self._find(function(err, r) {
589       if(err) return handleCallback(callback, err, null);
590
591       if(self.cursorState.documents.length == 0
592         && self.cursorState.cursorId && self.cursorState.cursorId.isZero()
593         && !self.cmd.tailable && !self.cmd.awaitData) {
594         return setCursorNotified(self, callback);
595       }
596
597       nextFunction(self, callback);
598     });
599   } else if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) {
600     // Ensure we kill the cursor on the server
601     self.kill();
602     // Set cursor in dead and notified state
603     return setCursorDeadAndNotified(self, callback);
604   } else if(self.cursorState.cursorIndex == self.cursorState.documents.length
605       && !Long.ZERO.equals(self.cursorState.cursorId)) {
606       // Ensure an empty cursor state
607       self.cursorState.documents = [];
608       self.cursorState.cursorIndex = 0;
609
610       // Check if topology is destroyed
611       if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor')));
612
613       // Check if connection is dead and return if not possible to
614       // execute a getmore on this connection
615       if(isConnectionDead(self, callback)) return;
616
617       // Execute the next get more
618       self._getmore(function(err, doc, connection) {
619         if(err) return handleCallback(callback, err);
620
621         // Save the returned connection to ensure all getMore's fire over the same connection
622         self.connection = connection;
623
624         // Tailable cursor getMore result, notify owner about it
625         // No attempt is made here to retry, this is left to the user of the
626         // core module to handle to keep core simple
627         if(self.cursorState.documents.length == 0
628           && self.cmd.tailable && Long.ZERO.equals(self.cursorState.cursorId)) {
629           // No more documents in the tailed cursor
630           return handleCallback(callback, MongoError.create({
631               message: "No more documents in tailed cursor"
632             , tailable: self.cmd.tailable
633             , awaitData: self.cmd.awaitData
634           }));
635         } else if(self.cursorState.documents.length == 0
636           && self.cmd.tailable && !Long.ZERO.equals(self.cursorState.cursorId)) {
637           return nextFunction(self, callback);
638         }
639
640         if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) {
641           return setCursorDeadAndNotified(self, callback);
642         }
643
644         nextFunction(self, callback);
645       });
646   } else if(self.cursorState.documents.length == self.cursorState.cursorIndex
647     && self.cmd.tailable && Long.ZERO.equals(self.cursorState.cursorId)) {
648       return handleCallback(callback, MongoError.create({
649           message: "No more documents in tailed cursor"
650         , tailable: self.cmd.tailable
651         , awaitData: self.cmd.awaitData
652       }));
653   } else if(self.cursorState.documents.length == self.cursorState.cursorIndex
654       && Long.ZERO.equals(self.cursorState.cursorId)) {
655       setCursorDeadAndNotified(self, callback);
656   } else {
657     if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) {
658       // Ensure we kill the cursor on the server
659       self.kill();
660       // Set cursor in dead and notified state
661       return setCursorDeadAndNotified(self, callback);
662     }
663
664     // Increment the current cursor limit
665     self.cursorState.currentLimit += 1;
666
667     // Get the document
668     var doc = self.cursorState.documents[self.cursorState.cursorIndex++];
669
670     // Doc overflow
671     if(doc.$err) {
672       // Ensure we kill the cursor on the server
673       self.kill();
674       // Set cursor in dead and notified state
675       return setCursorDeadAndNotified(self, function() {
676         handleCallback(callback, new MongoError(doc.$err));
677       });
678     }
679
680     // Transform the doc with passed in transformation method if provided
681     if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function') {
682       doc = self.cursorState.transforms.doc(doc);
683     }
684
685     // Return the document
686     handleCallback(callback, null, doc);
687   }
688 }
689
690 /**
691  * Retrieve the next document from the cursor
692  * @method
693  * @param {resultCallback} callback A callback function
694  */
695 Cursor.prototype.next = function(callback) {
696   nextFunction(this, callback);
697 }
698
699 module.exports = Cursor;