f59f35075a654fa05172c0eea91e61f708cef337
[aai/esr-gui.git] /
1 "use strict";
2
3 var Insert = require('./commands').Insert
4   , Update = require('./commands').Update
5   , Remove = require('./commands').Remove
6   , copy = require('../connection/utils').copy
7   , retrieveBSON = require('../connection/utils').retrieveBSON
8   , KillCursor = require('../connection/commands').KillCursor
9   , GetMore = require('../connection/commands').GetMore
10   , Query = require('../connection/commands').Query
11   , f = require('util').format
12   , CommandResult = require('../connection/command_result')
13   , MongoError = require('../error')
14   , getReadPreference = require('./shared').getReadPreference;
15
16 var BSON = retrieveBSON(),
17   Long = BSON.Long;
18
19 // Write concern fields
20 var writeConcernFields = ['w', 'wtimeout', 'j', 'fsync'];
21
22 var WireProtocol = function() {}
23
24 //
25 // Needs to support legacy mass insert as well as ordered/unordered legacy
26 // emulation
27 //
28 WireProtocol.prototype.insert = function(pool, ismaster, ns, bson, ops, options, callback) {
29   options = options || {};
30   // Default is ordered execution
31   var ordered = typeof options.ordered == 'boolean' ? options.ordered : true;
32   ops = Array.isArray(ops) ? ops :[ops];
33
34   // If we have more than a 1000 ops fails
35   if(ops.length > 1000) return callback(new MongoError("exceeded maximum write batch size of 1000"));
36
37   // Write concern
38   var writeConcern = options.writeConcern || {w:1};
39
40   // We are unordered
41   if(!ordered || writeConcern.w == 0) {
42     return executeUnordered('insert', Insert, ismaster, ns, bson, pool, ops, options, callback);
43   }
44
45   return executeOrdered('insert', Insert, ismaster, ns, bson, pool, ops, options, callback);
46 }
47
48 WireProtocol.prototype.update = function(pool, ismaster, ns, bson, ops, options, callback) {
49   options = options || {};
50   // Default is ordered execution
51   var ordered = typeof options.ordered == 'boolean' ? options.ordered : true;
52   ops = Array.isArray(ops) ? ops :[ops];
53
54   // Write concern
55   var writeConcern = options.writeConcern || {w:1};
56
57   // We are unordered
58   if(!ordered || writeConcern.w == 0) {
59     return executeUnordered('update', Update, ismaster, ns, bson, pool, ops, options, callback);
60   }
61
62   return executeOrdered('update', Update, ismaster, ns, bson, pool, ops, options, callback);
63 }
64
65 WireProtocol.prototype.remove = function(pool, ismaster, ns, bson, ops, options, callback) {
66   options = options || {};
67   // Default is ordered execution
68   var ordered = typeof options.ordered == 'boolean' ? options.ordered : true;
69   ops = Array.isArray(ops) ? ops :[ops];
70
71   // Write concern
72   var writeConcern = options.writeConcern || {w:1};
73
74   // We are unordered
75   if(!ordered || writeConcern.w == 0) {
76     return executeUnordered('remove', Remove, ismaster, ns, bson, pool, ops, options, callback);
77   }
78
79   return executeOrdered('remove', Remove, ismaster, ns, bson, pool, ops, options, callback);
80 }
81
82 WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callback) {
83   // Create a kill cursor command
84   var killCursor = new KillCursor(bson, [cursorId]);
85   // Execute the kill cursor command
86   if(pool && pool.isConnected()) {
87     pool.write(killCursor, {
88       immediateRelease:true, noResponse: true
89     });
90   }
91
92   // Callback
93   if(typeof callback == 'function') callback(null, null);
94 }
95
96 WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, options, callback) {
97   // Create getMore command
98   var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize});
99
100   // Query callback
101   var queryCallback = function(err, result) {
102     if(err) return callback(err);
103     // Get the raw message
104     var r = result.message;
105
106     // If we have a timed out query or a cursor that was killed
107     if((r.responseFlags & (1 << 0)) != 0) {
108       return callback(new MongoError("cursor does not exist, was killed or timed out"), null);
109     }
110
111     // Ensure we have a Long valie cursor id
112     var cursorId = typeof r.cursorId == 'number'
113       ? Long.fromNumber(r.cursorId)
114       : r.cursorId;
115
116     // Set all the values
117     cursorState.documents = r.documents;
118     cursorState.cursorId = cursorId;
119
120     // Return
121     callback(null, null, r.connection);
122   }
123
124   // If we have a raw query decorate the function
125   if(raw) {
126     queryCallback.raw = raw;
127   }
128
129   // Check if we need to promote longs
130   if(typeof cursorState.promoteLongs == 'boolean') {
131     queryCallback.promoteLongs = cursorState.promoteLongs;
132   }
133
134   if(typeof cursorState.promoteValues == 'boolean') {
135     queryCallback.promoteValues = cursorState.promoteValues;
136   }
137
138   if(typeof cursorState.promoteBuffers == 'boolean') {
139     queryCallback.promoteBuffers = cursorState.promoteBuffers;
140   }
141
142   // Write out the getMore command
143   connection.write(getMore, queryCallback);
144 }
145
146 WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) {
147   // Establish type of command
148   if(cmd.find) {
149     return setupClassicFind(bson, ns, cmd, cursorState, topology, options)
150   } else if(cursorState.cursorId != null) {
151     return;
152   } else if(cmd) {
153     return setupCommand(bson, ns, cmd, cursorState, topology, options);
154   } else {
155     throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd)));
156   }
157 }
158
159 //
160 // Execute a find command
161 var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) {
162   // Ensure we have at least some options
163   options = options || {};
164   // Get the readPreference
165   var readPreference = getReadPreference(cmd, options);
166   // Set the optional batchSize
167   cursorState.batchSize = cmd.batchSize || cursorState.batchSize;
168   var numberToReturn = 0;
169
170   // Unpack the limit and batchSize values
171   if(cursorState.limit == 0) {
172     numberToReturn = cursorState.batchSize;
173   } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) {
174     numberToReturn = cursorState.limit;
175   } else {
176     numberToReturn = cursorState.batchSize;
177   }
178
179   var numberToSkip = cursorState.skip || 0;
180   // Build actual find command
181   var findCmd = {};
182   // Using special modifier
183   var usesSpecialModifier = false;
184
185   // We have a Mongos topology, check if we need to add a readPreference
186   if(topology.type == 'mongos' && readPreference) {
187     findCmd['$readPreference'] = readPreference.toJSON();
188     usesSpecialModifier = true;
189   }
190
191   // Add special modifiers to the query
192   if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true;
193   if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true;
194   if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true;
195   if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true;
196   if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true;
197   if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true;
198   if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true;
199   if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true;
200   if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true;
201   if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true;
202
203   if(cmd.explain) {
204         // nToReturn must be 0 (match all) or negative (match N and close cursor)
205         // nToReturn > 0 will give explain results equivalent to limit(0)
206     numberToReturn = -Math.abs(cmd.limit || 0);
207     usesSpecialModifier = true;
208     findCmd['$explain'] = true;
209   }
210
211   // If we have a special modifier
212   if(usesSpecialModifier) {
213     findCmd['$query'] = cmd.query;
214   } else {
215     findCmd = cmd.query;
216   }
217
218   // Throw on majority readConcern passed in
219   if(cmd.readConcern && cmd.readConcern.level != 'local') {
220     throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level));
221   }
222
223   // Remove readConcern, ensure no failing commands
224   if(cmd.readConcern) {
225     cmd = copy(cmd);
226     delete cmd['readConcern'];
227   }
228
229   // Set up the serialize and ignoreUndefined fields
230   var serializeFunctions = typeof options.serializeFunctions == 'boolean'
231     ? options.serializeFunctions : false;
232   var ignoreUndefined = typeof options.ignoreUndefined == 'boolean'
233     ? options.ignoreUndefined : false;
234
235   // Build Query object
236   var query = new Query(bson, ns, findCmd, {
237       numberToSkip: numberToSkip, numberToReturn: numberToReturn
238     , checkKeys: false, returnFieldSelector: cmd.fields
239     , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined
240   });
241
242   // Set query flags
243   query.slaveOk = readPreference.slaveOk();
244
245   // Set up the option bits for wire protocol
246   if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable;
247   if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay;
248   if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout;
249   if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData;
250   if(typeof cmd.partial == 'boolean') query.partial = cmd.partial;
251   // Return the query
252   return query;
253 }
254
255 //
256 // Set up a command cursor
257 var setupCommand = function(bson, ns, cmd, cursorState, topology, options) {
258   // Set empty options object
259   options = options || {}
260   // Get the readPreference
261   var readPreference = getReadPreference(cmd, options);
262   // Final query
263   var finalCmd = {};
264   for(var name in cmd) {
265     finalCmd[name] = cmd[name];
266   }
267
268   // Build command namespace
269   var parts = ns.split(/\./);
270
271   // Throw on majority readConcern passed in
272   if(cmd.readConcern && cmd.readConcern.level != 'local') {
273     throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level));
274   }
275
276   // Remove readConcern, ensure no failing commands
277   if(cmd.readConcern) delete cmd['readConcern'];
278
279   // Serialize functions
280   var serializeFunctions = typeof options.serializeFunctions == 'boolean'
281     ? options.serializeFunctions : false;
282
283   // Set up the serialize and ignoreUndefined fields
284   var ignoreUndefined = typeof options.ignoreUndefined == 'boolean'
285     ? options.ignoreUndefined : false;
286
287   // We have a Mongos topology, check if we need to add a readPreference
288   if(topology.type == 'mongos'
289     && readPreference
290     && readPreference.preference != 'primary') {
291     finalCmd = {
292       '$query': finalCmd,
293       '$readPreference': readPreference.toJSON()
294     };
295   }
296
297   // Build Query object
298   var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, {
299       numberToSkip: 0, numberToReturn: -1
300     , checkKeys: false, serializeFunctions: serializeFunctions
301     , ignoreUndefined: ignoreUndefined
302   });
303
304   // Set query flags
305   query.slaveOk = readPreference.slaveOk();
306
307   // Return the query
308   return query;
309 }
310
311 var hasWriteConcern = function(writeConcern) {
312   if(writeConcern.w
313     || writeConcern.wtimeout
314     || writeConcern.j == true
315     || writeConcern.fsync == true
316     || Object.keys(writeConcern).length == 0) {
317     return true;
318   }
319   return false;
320 }
321
322 var cloneWriteConcern = function(writeConcern) {
323   var wc = {};
324   if(writeConcern.w != null) wc.w = writeConcern.w;
325   if(writeConcern.wtimeout != null) wc.wtimeout = writeConcern.wtimeout;
326   if(writeConcern.j != null) wc.j = writeConcern.j;
327   if(writeConcern.fsync != null) wc.fsync = writeConcern.fsync;
328   return wc;
329 }
330
331 //
332 // Aggregate up all the results
333 //
334 var aggregateWriteOperationResults = function(opType, ops, results, connection) {
335   var finalResult = { ok: 1, n: 0 }
336   if(opType == 'update') {
337     finalResult.nModified = 0;
338   }
339
340   // Map all the results coming back
341   for(var i = 0; i < results.length; i++) {
342     var result = results[i];
343     var op = ops[i];
344
345     if((result.upserted || (result.updatedExisting == false)) && finalResult.upserted == null) {
346       finalResult.upserted = [];
347     }
348
349     // Push the upserted document to the list of upserted values
350     if(result.upserted) {
351       finalResult.upserted.push({index: i, _id: result.upserted});
352     }
353
354     // We have an upsert where we passed in a _id
355     if(result.updatedExisting == false && result.n == 1 && result.upserted == null) {
356       finalResult.upserted.push({index: i, _id: op.q._id});
357     } else if(result.updatedExisting == true) {
358       finalResult.nModified += result.n;
359     }
360
361     // We have an insert command
362     if(result.ok == 1 && opType == 'insert' && result.err == null) {
363       finalResult.n = finalResult.n + 1;
364     }
365
366     // We have a command error
367     if(result != null && result.ok == 0 || result.err || result.errmsg) {
368       if(result.ok == 0) finalResult.ok = 0;
369       finalResult.code = result.code;
370       finalResult.errmsg = result.errmsg || result.err || result.errMsg;
371
372       // Check if we have a write error
373       if(result.code == 11000
374         || result.code == 11001
375         || result.code == 12582
376         || result.code == 16544
377         || result.code == 16538
378         || result.code == 16542
379         || result.code == 14
380         || result.code == 13511) {
381         if(finalResult.writeErrors == null) finalResult.writeErrors = [];
382         finalResult.writeErrors.push({
383             index: i
384           , code: result.code
385           , errmsg: result.errmsg || result.err || result.errMsg
386         });
387       } else {
388         finalResult.writeConcernError = {
389             code: result.code
390           , errmsg: result.errmsg || result.err || result.errMsg
391         }
392       }
393     } else if(typeof result.n == 'number') {
394       finalResult.n += result.n;
395     } else {
396       finalResult.n += 1;
397     }
398
399     // Result as expected
400     if(result != null && result.lastOp) finalResult.lastOp = result.lastOp;
401   }
402
403   // Return finalResult aggregated results
404   return new CommandResult(finalResult, connection);
405 }
406
407 //
408 // Execute all inserts in an ordered manner
409 //
410 var executeOrdered = function(opType ,command, ismaster, ns, bson, pool, ops, options, callback) {
411   var _ops = ops.slice(0);
412   // Collect all the getLastErrors
413   var getLastErrors = [];
414   // Execute an operation
415   var executeOp = function(list, _callback) {
416     // No more items in the list
417     if(list.length == 0) {
418       return process.nextTick(function() {
419         _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null));
420       });
421     }
422
423     // Get the first operation
424     var doc = list.shift();
425     // Create an insert command
426     var op = new command(Query.getRequestId(), ismaster, bson, ns, [doc], options);
427     // Write concern
428     var optionWriteConcern = options.writeConcern || {w:1};
429     // Final write concern
430     var writeConcern = cloneWriteConcern(optionWriteConcern);
431
432     // Get the db name
433     var db = ns.split('.').shift();
434
435     try {
436       // Add binary message to list of commands to execute
437       var commands = [op];
438
439       // Add getLastOrdered
440       var getLastErrorCmd = {getlasterror: 1};
441       // Merge all the fields
442       for(var i = 0; i < writeConcernFields.length; i++) {
443         if(writeConcern[writeConcernFields[i]] != null) {
444           getLastErrorCmd[writeConcernFields[i]] = writeConcern[writeConcernFields[i]];
445         }
446       }
447
448       // Create a getLastError command
449       var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1});
450       // Add getLastError command to list of ops to execute
451       commands.push(getLastErrorOp);
452
453       // getLastError callback
454       var getLastErrorCallback = function(err, result) {
455         if(err) return callback(err);
456         // Get the document
457         var doc = result.result;
458         // Save the getLastError document
459         getLastErrors.push(doc);
460
461         // If we have an error terminate
462         if(doc.ok == 0 || doc.err || doc.errmsg) {
463           return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, result.connection));
464         }
465
466         // Execute the next op in the list
467         executeOp(list, callback);
468       }
469
470       // Write both commands out at the same time
471       pool.write(commands, getLastErrorCallback);
472     } catch(err) {
473       // We have a serialization error, rewrite as a write error to have same behavior as modern
474       // write commands
475       getLastErrors.push({ ok: 1, errmsg: typeof err == 'string' ? err : err.message, code: 14 });
476       // Return due to an error
477       process.nextTick(function() {
478         _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null));
479       });
480     }
481   }
482
483   // Execute the operations
484   executeOp(_ops, callback);
485 }
486
487 var executeUnordered = function(opType, command, ismaster, ns, bson, pool, ops, options, callback) {
488   // Total operations to write
489   var totalOps = ops.length;
490   // Collect all the getLastErrors
491   var getLastErrors = [];
492   // Write concern
493   var optionWriteConcern = options.writeConcern || {w:1};
494   // Final write concern
495   var writeConcern = cloneWriteConcern(optionWriteConcern);
496   // Driver level error
497   var error;
498
499   // Execute all the operations
500   for(var i = 0; i < ops.length; i++) {
501     // Create an insert command
502     var op = new command(Query.getRequestId(), ismaster, bson, ns, [ops[i]], options);
503     // Get db name
504     var db = ns.split('.').shift();
505
506     try {
507       // Add binary message to list of commands to execute
508       var commands = [op];
509
510       // If write concern 0 don't fire getLastError
511       if(hasWriteConcern(writeConcern)) {
512         var getLastErrorCmd = {getlasterror: 1};
513         // Merge all the fields
514         for(var j = 0; j < writeConcernFields.length; j++) {
515           if(writeConcern[writeConcernFields[j]] != null)
516             getLastErrorCmd[writeConcernFields[j]] = writeConcern[writeConcernFields[j]];
517         }
518
519         // Create a getLastError command
520         var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1});
521         // Add getLastError command to list of ops to execute
522         commands.push(getLastErrorOp);
523
524         // Give the result from getLastError the right index
525         var callbackOp = function(_index) {
526           return function(err, result) {
527             if(err) error = err;
528             // Update the number of operations executed
529             totalOps = totalOps - 1;
530             // Save the getLastError document
531             if(!err) getLastErrors[_index] = result.result;
532             // Check if we are done
533             if(totalOps == 0) {
534               process.nextTick(function() {
535                 if(error) return callback(error);
536                 callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, result.connection));
537               });
538             }
539           }
540         }
541
542         // Write both commands out at the same time
543         pool.write(commands, callbackOp(i));
544       } else {
545         pool.write(commands, {immediateRelease:true, noResponse:true});
546       }
547     } catch(err) {
548       // Update the number of operations executed
549       totalOps = totalOps - 1;
550       // We have a serialization error, rewrite as a write error to have same behavior as modern
551       // write commands
552       getLastErrors[i] = { ok: 1, errmsg: typeof err == 'string' ? err : err.message, code: 14 };
553       // Check if we are done
554       if(totalOps == 0) {
555         callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null));
556       }
557     }
558   }
559
560   // Empty w:0 return
561   if(writeConcern
562     && writeConcern.w == 0 && callback) {
563     callback(null, new CommandResult({ok:1}, null));
564   }
565 }
566
567 module.exports = WireProtocol;