{"version":3,"sources":["meteor://💻app/packages/mongo/mongo_driver.js","meteor://💻app/packages/mongo/oplog_tailing.js","meteor://💻app/packages/mongo/observe_multiplex.js","meteor://💻app/packages/mongo/doc_fetcher.js","meteor://💻app/packages/mongo/polling_observe_driver.js","meteor://💻app/packages/mongo/oplog_observe_driver.js","meteor://💻app/packages/mongo/local_collection_driver.js","meteor://💻app/packages/mongo/remote_collection_driver.js","meteor://💻app/packages/mongo/collection.js","meteor://💻app/packages/mongo/connection_options.js"],"names":["module1","module","DocFetcher","link","v","MongoDB","NpmModuleMongodb","Future","Npm","require","MongoInternals","NpmModules","mongodb","version","NpmModuleMongodbVersion","NpmModule","replaceNames","filter","thing","_","isArray","map","bind","ret","each","value","key","Timestamp","prototype","clone","makeMongoLegal","name","unmakeMongoLegal","substr","replaceMongoAtomWithMeteor","document","Binary","buffer","Uint8Array","ObjectID","Mongo","toHexString","Decimal128","Decimal","toString","size","EJSON","fromJSONValue","undefined","replaceMeteorAtomWithMongo","isBinary","Buffer","from","fromString","_isCustomType","toJSONValue","replaceTypes","atomTransformer","replacedTopLevelAtom","val","valReplaced","MongoConnection","url","options","self","_observeMultiplexers","_onFailoverHook","Hook","mongoOptions","Object","assign","autoReconnect","reconnectTries","Infinity","ignoreUndefined","useNewUrlParser","_connectionOptions","test","native_parser","has","poolSize","db","_primary","_oplogHandle","_docFetcher","connectFuture","connect","Meteor","bindEnvironment","err","client","serverConfig","isMasterDoc","primary","on","kind","doc","callback","me","resolver","wait","oplogUrl","Package","OplogHandle","databaseName","close","Error","oplogHandle","stop","wrap","rawCollection","collectionName","future","collection","_createCappedCollection","byteSize","maxDocuments","createCollection","capped","max","_maybeBeginWrite","fence","DDPServer","_CurrentWriteFence","get","beginWrite","committed","_onFailover","register","writeCallback","write","refresh","result","refreshErr","bindEnvironmentForWrite","_insert","collection_name","sendError","e","_expectedByTest","LocalCollection","_isPlainObject","id","_id","insert","safe","_refresh","selector","refreshKey","specificIds","_idsMatchedBySelector","extend","_remove","wrappedCallback","driverResult","transformResult","numberAffected","remove","_dropCollection","cb","dropCollection","drop","_dropDatabase","dropDatabase","_update","mod","Function","mongoOpts","upsert","multi","fullResult","mongoSelector","mongoMod","isModify","_isModificationMod","_forbidReplace","knownId","newDoc","_createUpsertDocument","insertedId","generatedId","simulateUpsertWithInsertedId","error","_returnObject","hasOwnProperty","$setOnInsert","update","meteorResult","mongoResult","upserted","length","n","NUM_OPTIMISTIC_TRIES","_isCannotChangeIdError","errmsg","indexOf","mongoOptsForUpdate","mongoOptsForInsert","replacementWithId","tries","doUpdate","doConditionalInsert","method","wrapAsync","apply","arguments","find","Cursor","CursorDescription","findOne","limit","fetch","_ensureIndex","index","indexName","ensureIndex","_dropIndex","dropIndex","Collection","_rewriteSelector","mongo","cursorDescription","_mongo","_cursorDescription","_synchronousCursor","Symbol","iterator","tailable","_createSynchronousCursor","selfForIteration","useTransform","rewind","getTransform","transform","_publishCursor","sub","_getCollectionName","observe","callbacks","_observeFromObserveChanges","observeChanges","methods","ordered","_observeChangesCallbacksAreOrdered","exceptionName","forEach","_observeChanges","pick","cursorOptions","sort","skip","projection","fields","awaitdata","numberOfRetries","OPLOG_COLLECTION","ts","oplogReplay","dbCursor","maxTimeMs","maxTimeMS","hint","SynchronousCursor","_dbCursor","_selfForIteration","_transform","wrapTransform","_synchronousCount","count","_visitedIds","_IdMap","_rawNextObjectPromise","Promise","resolve","reject","next","_nextObjectPromise","set","_nextObjectPromiseWithTimeout","timeoutMS","nextObjectPromise","timeoutErr","timeoutPromise","timer","setTimeout","race","catch","_nextObject","await","thisArg","_rewind","call","res","push","identity","applySkipLimit","getRawObjects","results","done","tail","docCallback","cursor","stopped","lastTS","loop","newSelector","$gt","defer","_observeChangesTailable","observeKey","stringify","multiplexer","observeDriver","firstHandle","_noYieldsAllowed","ObserveMultiplexer","onStop","observeHandle","ObserveHandle","matcher","sorter","canUseOplog","all","_testOnlyPollCallback","Minimongo","Matcher","OplogObserveDriver","cursorSupported","Sorter","f","driverClass","PollingObserveDriver","mongoHandle","_observeDriver","addHandleAndSendInitialAdds","listenAll","listenCallback","listeners","forEachTrigger","trigger","_InvalidationCrossbar","listen","listener","triggerCallback","addedBefore","added","MongoTimestamp","Connection","TOO_FAR_BEHIND","process","env","METEOR_OPLOG_TOO_FAR_BEHIND","TAIL_TIMEOUT","METEOR_OPLOG_TAIL_TIMEOUT","showTS","getHighBits","getLowBits","idForOp","op","o","o2","dbName","_oplogUrl","_dbName","_oplogLastEntryConnection","_oplogTailConnection","_stopped","_tailHandle","_readyFuture","_crossbar","_Crossbar","factPackage","factName","_baseOplogSelector","ns","RegExp","_escapeRegExp","join","$or","$in","$exists","_catchingUpFutures","_lastProcessedTS","_onSkippedEntriesHook","debugPrintExceptions","_entryQueue","_DoubleEndedQueue","_workerActive","_startTailing","onOplogEntry","originalCallback","notification","_debug","listenHandle","onSkippedEntries","waitUntilCaughtUp","lastEntry","$natural","_sleepForMs","lessThanOrEqual","insertAfter","greaterThan","splice","mongodbUri","parse","database","admin","command","ismaster","setName","lastOplogEntry","oplogSelector","_maybeStartWorker","return","handleDoc","applyOps","nextTimestamp","add","ONE","startsWith","slice","fire","isEmpty","pop","clear","_setLastProcessedTS","shift","sequencer","_defineTooFarBehind","_resetTooFarBehind","Facts","incrementServerFact","_ordered","_onStop","_queue","_SynchronousQueue","_handles","_cache","_CachingChangeObserver","_addHandleTasksScheduledButNotPerformed","callbackNames","callbackName","_applyCallback","toArray","handle","safeToRunTask","runTask","_sendAdds","removeHandle","_ready","_stop","fromQueryError","ready","queueTask","queryError","throw","onFlush","isResolved","args","applyChange","keys","handleId","_addedBefore","_added","docs","nextObserveHandleId","_multiplexer","before","export","Fiber","constructor","mongoConnection","_mongoConnection","_callbacksForOp","Map","check","String","delete","run","POLLING_THROTTLE_MS","METEOR_POLLING_THROTTLE_MS","POLLING_INTERVAL_MS","METEOR_POLLING_INTERVAL_MS","_mongoHandle","_stopCallbacks","_results","_pollsScheduledButNotStarted","_pendingWrites","_ensurePollIsScheduled","throttle","_unthrottledEnsurePollIsScheduled","pollingThrottleMs","_taskQueue","listenersHandle","pollingInterval","pollingIntervalMs","_pollingInterval","intervalHandle","setInterval","clearInterval","_pollMongo","_suspendPolling","_resumePolling","first","newResults","oldResults","writesForCycle","code","JSON","message","Array","_diffQueryChanges","w","c","PHASE","QUERYING","FETCHING","STEADY","SwitchedToQuery","finishIfNeedToPollQuery","currentId","_usesOplog","comparator","getComparator","heapOptions","IdMap","_limit","_comparator","_sorter","_unpublishedBuffer","MinMaxHeap","_published","MaxHeap","_safeAppendToBuffer","_stopHandles","_registerPhaseChange","_matcher","_projectionFn","_compileProjection","_sharedProjection","combineIntoProjection","_sharedProjectionFn","_needToFetch","_currentlyFetching","_fetchGeneration","_requeryWhenDoneThisQuery","_writesToCommitWhenWeReachSteady","_needToPollQuery","_phase","_handleOplogEntryQuerying","_handleOplogEntrySteadyOrFetching","fired","_oplogObserveDrivers","onBeforeFire","drivers","driver","_runInitialQuery","_addPublished","overflowingDocId","maxElementId","overflowingDoc","equals","removed","_addBuffered","_removePublished","empty","newDocId","minElementId","_removeBuffered","_changePublished","oldDoc","projectedNew","projectedOld","changed","DiffSequence","makeChangedFields","maxBufferedId","_addMatching","maxPublished","maxBuffered","toPublish","canAppendToBuffer","canInsertIntoBuffer","toBuffer","_removeMatching","_handleDoc","matchesNow","documentMatches","publishedBefore","bufferedBefore","cachedBefore","minBuffered","staysInPublished","staysInBuffer","_fetchModifiedDocuments","thisGeneration","waiting","fut","_beSteady","writes","isReplace","canDirectlyModifyDoc","modifierCanBeDirectlyApplied","_modify","canBecomeTrueByModifier","affectedByModifier","_runQuery","initial","_doneQuerying","_pollQuery","newBuffer","_cursorForQuery","i","_publishNewResults","optionsOverwrite","description","idsToRemove","console","_oplogEntryHandle","_listenersHandle","phase","now","Date","timeDiff","_phaseStartTime","disableOplog","_disableOplog","_checkSupportedProjection","hasWhere","hasGeoQuery","modifier","operation","field","LocalCollectionDriver","noConnCollections","create","open","conn","ensureCollection","_mongo_livedata_collections","collections","RemoteCollectionDriver","mongo_url","m","defaultRemoteCollectionDriver","once","connectionOptions","mongoUrl","MONGO_URL","MONGO_OPLOG_URL","connection","manager","idGeneration","_driver","_preventAutopublish","_makeNewID","src","DDP","randomStream","Random","insecure","hexString","_connection","isClient","server","_collection","_name","_maybeSetUpReplication","defineMutationMethods","_defineMutationMethods","useExisting","_suppressSameNameError","autopublish","publish","is_auto","registerStore","ok","beginUpdate","batchSize","reset","pauseObservers","msg","mongoId","MongoID","idParse","replace","$unset","$set","endUpdate","resumeObservers","saveOriginals","retrieveOriginals","getDoc","_getCollection","warn","log","_getFindSelector","_getFindOptions","Match","Optional","ObjectIncluding","OneOf","Number","fallbackId","_selectorIsId","getPrototypeOf","getOwnPropertyDescriptors","generateId","_isRemoteCollection","enclosing","_CurrentMethodInvocation","chooseReturnValueFromCollectionResult","wrapCallback","_callMutatorMethod","optionsAndCallback","popCallbackFromArgs","rawDatabase","convertResult","AllowDeny","CollectionPrototype","setConnectionOptions"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAMA,OAAO,GAACC,MAAd;AAAqB,IAAIC,UAAJ;AAAeF,OAAO,CAACG,IAAR,CAAa,kBAAb,EAAgC;AAACD,YAAU,CAACE,CAAD,EAAG;AAACF,cAAU,GAACE,CAAX;AAAa;;AAA5B,CAAhC,EAA8D,CAA9D;;AAApC;;;;;;;;AASA,IAAIC,OAAO,GAAGC,gBAAd;;AACA,IAAIC,MAAM,GAAGC,GAAG,CAACC,OAAJ,CAAY,eAAZ,CAAb;;AAGAC,cAAc,GAAG,EAAjB;AAEAA,cAAc,CAACC,UAAf,GAA4B;AAC1BC,SAAO,EAAE;AACPC,WAAO,EAAEC,uBADF;AAEPb,UAAM,EAAEI;AAFD;AADiB,CAA5B,C,CAOA;AACA;AACA;AACA;;AACAK,cAAc,CAACK,SAAf,GAA2BV,OAA3B,C,CAEA;AACA;;AACA,IAAIW,YA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A/B;AAEA;;;;AAGAvK,KAAK,CAACkL,UAAN,CAAiBX,MAAjB,GAA0BvK,KAAK,CAACuK,MAAhC;AAEA;;;;AAGAvK,KAAK,CAACkL,UAAN,CAAiBnL,QAAjB,GAA4BC,KAAK,CAACD,QAAlC;AAEA;;;;AAGAgD,MAAM,CAACmI,UAAP,GAAoBlL,KAAK,CAACkL,UAA1B,C,CAEA;;AACArJ,MAAM,CAACC,MAAP,CACEiB,MAAM,CAACmI,UAAP,CAAkB9L,SADpB,EAEEkrB,SAAS,CAACC,mBAFZ;;AAKA,SAASJ,mBAAT,CAA6BjQ,IAA7B,EAAmC;AACjC;AACA;AACA,MAAIA,IAAI,CAAC5Q,MAAL,KACC4Q,IAAI,CAACA,IAAI,CAAC5Q,MAAL,GAAc,CAAf,CAAJ,KAA0B9I,SAA1B,IACA0Z,IAAI,CAACA,IAAI,CAAC5Q,MAAL,GAAc,CAAf,CAAJ,YAAiCxB,QAFlC,CAAJ,EAEiD;AAC/C,WAAOoS,IAAI,CAACnC,GAAL,EAAP;AACD;AACF,C;;;;;;;;;;;ACzwBD;;;;;;AAMA/X,KAAK,CAACwqB,oBAAN,GAA6B,SAASA,oBAAT,CAA+BjpB,OAA/B,EAAwC;AACnE4Z,OAAK,CAAC5Z,OAAD,EAAUM,MAAV,CAAL;AACA7B,OAAK,CAACoC,kBAAN,GAA2Bb,OAA3B;AACD,CAHD,C","file":"/packages/mongo.js","sourcesContent":["/**\n * Provide a synchronous Collection API using fibers, backed by\n * MongoDB. This is only for use on the server, and mostly identical\n * to the client API.\n *\n * NOTE: the public API methods must be run within a fiber. If you call\n * these outside of a fiber they will explode!\n */\n\nvar MongoDB = NpmModuleMongodb;\nvar Future = Npm.require('fibers/future');\nimport { DocFetcher } from \"./doc_fetcher.js\";\n\nMongoInternals = {};\n\nMongoInternals.NpmModules = {\n mongodb: {\n version: NpmModuleMongodbVersion,\n module: MongoDB\n }\n};\n\n// Older version of what is now available via\n// MongoInternals.NpmModules.mongodb.module. It was never documented, but\n// people do use it.\n// XXX COMPAT WITH 1.0.3.2\nMongoInternals.NpmModule = MongoDB;\n\n// This is used to add or remove EJSON from the beginning of everything nested\n// inside an EJSON custom type. It should only be called on pure JSON!\nvar replaceNames = function (filter, thing) {\n if (typeof thing === \"object\" && thing !== null) {\n if (_.isArray(thing)) {\n return _.map(thing, _.bind(replaceNames, null, filter));\n }\n var ret = {};\n _.each(thing, function (value, key) {\n ret[filter(key)] = replaceNames(filter, value);\n });\n return ret;\n }\n return thing;\n};\n\n// Ensure that EJSON.clone keeps a Timestamp as a Timestamp (instead of just\n// doing a structural clone).\n// XXX how ok is this? what if there are multiple copies of MongoDB loaded?\nMongoDB.Timestamp.prototype.clone = function () {\n // Timestamps should be immutable.\n return this;\n};\n\nvar makeMongoLegal = function (name) { return \"EJSON\" + name; };\nvar unmakeMongoLegal = function (name) { return name.substr(5); };\n\nvar replaceMongoAtomWithMeteor = function (document) {\n if (document instanceof MongoDB.Binary) {\n var buffer = document.value(true);\n return new Uint8Array(buffer);\n }\n if (document instanceof MongoDB.ObjectID) {\n return new Mongo.ObjectID(document.toHexString());\n }\n if (document instanceof MongoDB.Decimal128) {\n return Decimal(document.toString());\n }\n if (document[\"EJSON$type\"] && document[\"EJSON$value\"] && _.size(document) === 2) {\n return EJSON.fromJSONValue(replaceNames(unmakeMongoLegal, document));\n }\n if (document instanceof MongoDB.Timestamp) {\n // For now, the Meteor representation of a Mongo timestamp type (not a date!\n // this is a weird internal thing used in the oplog!) is the same as the\n // Mongo representation. We need to do this explicitly or else we would do a\n // structural clone and lose the prototype.\n return document;\n }\n return undefined;\n};\n\nvar replaceMeteorAtomWithMongo = function (document) {\n if (EJSON.isBinary(document)) {\n // This does more copies than we'd like, but is necessary because\n // MongoDB.BSON only looks like it takes a Uint8Array (and doesn't actually\n // serialize it correctly).\n return new MongoDB.Binary(Buffer.from(document));\n }\n if (document instanceof Mongo.ObjectID) {\n return new MongoDB.ObjectID(document.toHexString());\n }\n if (document instanceof MongoDB.Timestamp) {\n // For now, the Meteor representation of a Mongo timestamp type (not a date!\n // this is a weird internal thing used in the oplog!) is the same as the\n // Mongo representation. We need to do this explicitly or else we would do a\n // structural clone and lose the prototype.\n return document;\n }\n if (document instanceof Decimal) {\n return MongoDB.Decimal128.fromString(document.toString());\n }\n if (EJSON._isCustomType(document)) {\n return replaceNames(makeMongoLegal, EJSON.toJSONValue(document));\n }\n // It is not ordinarily possible to stick dollar-sign keys into mongo\n // so we don't bother checking for things that need escaping at this time.\n return undefined;\n};\n\nvar replaceTypes = function (document, atomTransformer) {\n if (typeof document !== 'object' || document === null)\n return document;\n\n var replacedTopLevelAtom = atomTransformer(document);\n if (replacedTopLevelAtom !== undefined)\n return replacedTopLevelAtom;\n\n var ret = document;\n _.each(document, function (val, key) {\n var valReplaced = replaceTypes(val, atomTransformer);\n if (val !== valReplaced) {\n // Lazy clone. Shallow copy.\n if (ret === document)\n ret = _.clone(document);\n ret[key] = valReplaced;\n }\n });\n return ret;\n};\n\n\nMongoConnection = function (url, options) {\n var self = this;\n options = options || {};\n self._observeMultiplexers = {};\n self._onFailoverHook = new Hook;\n\n var mongoOptions = Object.assign({\n // Reconnect on error.\n autoReconnect: true,\n // Try to reconnect forever, instead of stopping after 30 tries (the\n // default), with each attempt separated by 1000ms.\n reconnectTries: Infinity,\n ignoreUndefined: true,\n // Required to silence deprecation warnings with mongodb@3.1.1.\n useNewUrlParser: true,\n }, Mongo._connectionOptions);\n\n // Disable the native parser by default, unless specifically enabled\n // in the mongo URL.\n // - The native driver can cause errors which normally would be\n // thrown, caught, and handled into segfaults that take down the\n // whole app.\n // - Binary modules don't yet work when you bundle and move the bundle\n // to a different platform (aka deploy)\n // We should revisit this after binary npm module support lands.\n if (!(/[\\?&]native_?[pP]arser=/.test(url))) {\n mongoOptions.native_parser = false;\n }\n\n // Internally the oplog connections specify their own poolSize\n // which we don't want to overwrite with any user defined value\n if (_.has(options, 'poolSize')) {\n // If we just set this for \"server\", replSet will override it. If we just\n // set it for replSet, it will be ignored if we're not using a replSet.\n mongoOptions.poolSize = options.poolSize;\n }\n\n self.db = null;\n // We keep track of the ReplSet's primary, so that we can trigger hooks when\n // it changes. The Node driver's joined callback seems to fire way too\n // often, which is why we need to track it ourselves.\n self._primary = null;\n self._oplogHandle = null;\n self._docFetcher = null;\n\n\n var connectFuture = new Future;\n MongoDB.connect(\n url,\n mongoOptions,\n Meteor.bindEnvironment(\n function (err, client) {\n if (err) {\n throw err;\n }\n\n var db = client.db();\n\n // First, figure out what the current primary is, if any.\n if (db.serverConfig.isMasterDoc) {\n self._primary = db.serverConfig.isMasterDoc.primary;\n }\n\n db.serverConfig.on(\n 'joined', Meteor.bindEnvironment(function (kind, doc) {\n if (kind === 'primary') {\n if (doc.primary !== self._primary) {\n self._primary = doc.primary;\n self._onFailoverHook.each(function (callback) {\n callback();\n return true;\n });\n }\n } else if (doc.me === self._primary) {\n // The thing we thought was primary is now something other than\n // primary. Forget that we thought it was primary. (This means\n // that if a server stops being primary and then starts being\n // primary again without another server becoming primary in the\n // middle, we'll correctly count it as a failover.)\n self._primary = null;\n }\n }));\n\n // Allow the constructor to return.\n connectFuture['return']({ client, db });\n },\n connectFuture.resolver() // onException\n )\n );\n\n // Wait for the connection to be successful (throws on failure) and assign the\n // results (`client` and `db`) to `self`.\n Object.assign(self, connectFuture.wait());\n\n if (options.oplogUrl && ! Package['disable-oplog']) {\n self._oplogHandle = new OplogHandle(options.oplogUrl, self.db.databaseName);\n self._docFetcher = new DocFetcher(self);\n }\n};\n\nMongoConnection.prototype.close = function() {\n var self = this;\n\n if (! self.db)\n throw Error(\"close called before Connection created?\");\n\n // XXX probably untested\n var oplogHandle = self._oplogHandle;\n self._oplogHandle = null;\n if (oplogHandle)\n oplogHandle.stop();\n\n // Use Future.wrap so that errors get thrown. This happens to\n // work even outside a fiber since the 'close' method is not\n // actually asynchronous.\n Future.wrap(_.bind(self.client.close, self.client))(true).wait();\n};\n\n// Returns the Mongo Collection object; may yield.\nMongoConnection.prototype.rawCollection = function (collectionName) {\n var self = this;\n\n if (! self.db)\n throw Error(\"rawCollection called before Connection created?\");\n\n var future = new Future;\n self.db.collection(collectionName, future.resolver());\n return future.wait();\n};\n\nMongoConnection.prototype._createCappedCollection = function (\n collectionName, byteSize, maxDocuments) {\n var self = this;\n\n if (! self.db)\n throw Error(\"_createCappedCollection called before Connection created?\");\n\n var future = new Future();\n self.db.createCollection(\n collectionName,\n { capped: true, size: byteSize, max: maxDocuments },\n future.resolver());\n future.wait();\n};\n\n// This should be called synchronously with a write, to create a\n// transaction on the current write fence, if any. After we can read\n// the write, and after observers have been notified (or at least,\n// after the observer notifiers have added themselves to the write\n// fence), you should call 'committed()' on the object returned.\nMongoConnection.prototype._maybeBeginWrite = function () {\n var fence = DDPServer._CurrentWriteFence.get();\n if (fence) {\n return fence.beginWrite();\n } else {\n return {committed: function () {}};\n }\n};\n\n// Internal interface: adds a callback which is called when the Mongo primary\n// changes. Returns a stop handle.\nMongoConnection.prototype._onFailover = function (callback) {\n return this._onFailoverHook.register(callback);\n};\n\n\n//////////// Public API //////////\n\n// The write methods block until the database has confirmed the write (it may\n// not be replicated or stable on disk, but one server has confirmed it) if no\n// callback is provided. If a callback is provided, then they call the callback\n// when the write is confirmed. They return nothing on success, and raise an\n// exception on failure.\n//\n// After making a write (with insert, update, remove), observers are\n// notified asynchronously. If you want to receive a callback once all\n// of the observer notifications have landed for your write, do the\n// writes inside a write fence (set DDPServer._CurrentWriteFence to a new\n// _WriteFence, and then set a callback on the write fence.)\n//\n// Since our execution environment is single-threaded, this is\n// well-defined -- a write \"has been made\" if it's returned, and an\n// observer \"has been notified\" if its callback has returned.\n\nvar writeCallback = function (write, refresh, callback) {\n return function (err, result) {\n if (! err) {\n // XXX We don't have to run this on error, right?\n try {\n refresh();\n } catch (refreshErr) {\n if (callback) {\n callback(refreshErr);\n return;\n } else {\n throw refreshErr;\n }\n }\n }\n write.committed();\n if (callback) {\n callback(err, result);\n } else if (err) {\n throw err;\n }\n };\n};\n\nvar bindEnvironmentForWrite = function (callback) {\n return Meteor.bindEnvironment(callback, \"Mongo write\");\n};\n\nMongoConnection.prototype._insert = function (collection_name, document,\n callback) {\n var self = this;\n\n var sendError = function (e) {\n if (callback)\n return callback(e);\n throw e;\n };\n\n if (collection_name === \"___meteor_failure_test_collection\") {\n var e = new Error(\"Failure test\");\n e._expectedByTest = true;\n sendError(e);\n return;\n }\n\n if (!(LocalCollection._isPlainObject(document) &&\n !EJSON._isCustomType(document))) {\n sendError(new Error(\n \"Only plain objects may be inserted into MongoDB\"));\n return;\n }\n\n var write = self._maybeBeginWrite();\n var refresh = function () {\n Meteor.refresh({collection: collection_name, id: document._id });\n };\n callback = bindEnvironmentForWrite(writeCallback(write, refresh, callback));\n try {\n var collection = self.rawCollection(collection_name);\n collection.insert(replaceTypes(document, replaceMeteorAtomWithMongo),\n {safe: true}, callback);\n } catch (err) {\n write.committed();\n throw err;\n }\n};\n\n// Cause queries that may be affected by the selector to poll in this write\n// fence.\nMongoConnection.prototype._refresh = function (collectionName, selector) {\n var refreshKey = {collection: collectionName};\n // If we know which documents we're removing, don't poll queries that are\n // specific to other documents. (Note that multiple notifications here should\n // not cause multiple polls, since all our listener is doing is enqueueing a\n // poll.)\n var specificIds = LocalCollection._idsMatchedBySelector(selector);\n if (specificIds) {\n _.each(specificIds, function (id) {\n Meteor.refresh(_.extend({id: id}, refreshKey));\n });\n } else {\n Meteor.refresh(refreshKey);\n }\n};\n\nMongoConnection.prototype._remove = function (collection_name, selector,\n callback) {\n var self = this;\n\n if (collection_name === \"___meteor_failure_test_collection\") {\n var e = new Error(\"Failure test\");\n e._expectedByTest = true;\n if (callback) {\n return callback(e);\n } else {\n throw e;\n }\n }\n\n var write = self._maybeBeginWrite();\n var refresh = function () {\n self._refresh(collection_name, selector);\n };\n callback = bindEnvironmentForWrite(writeCallback(write, refresh, callback));\n\n try {\n var collection = self.rawCollection(collection_name);\n var wrappedCallback = function(err, driverResult) {\n callback(err, transformResult(driverResult).numberAffected);\n };\n collection.remove(replaceTypes(selector, replaceMeteorAtomWithMongo),\n {safe: true}, wrappedCallback);\n } catch (err) {\n write.committed();\n throw err;\n }\n};\n\nMongoConnection.prototype._dropCollection = function (collectionName, cb) {\n var self = this;\n\n var write = self._maybeBeginWrite();\n var refresh = function () {\n Meteor.refresh({collection: collectionName, id: null,\n dropCollection: true});\n };\n cb = bindEnvironmentForWrite(writeCallback(write, refresh, cb));\n\n try {\n var collection = self.rawCollection(collectionName);\n collection.drop(cb);\n } catch (e) {\n write.committed();\n throw e;\n }\n};\n\n// For testing only. Slightly better than `c.rawDatabase().dropDatabase()`\n// because it lets the test's fence wait for it to be complete.\nMongoConnection.prototype._dropDatabase = function (cb) {\n var self = this;\n\n var write = self._maybeBeginWrite();\n var refresh = function () {\n Meteor.refresh({ dropDatabase: true });\n };\n cb = bindEnvironmentForWrite(writeCallback(write, refresh, cb));\n\n try {\n self.db.dropDatabase(cb);\n } catch (e) {\n write.committed();\n throw e;\n }\n};\n\nMongoConnection.prototype._update = function (collection_name, selector, mod,\n options, callback) {\n var self = this;\n\n if (! callback && options instanceof Function) {\n callback = options;\n options = null;\n }\n\n if (collection_name === \"___meteor_failure_test_collection\") {\n var e = new Error(\"Failure test\");\n e._expectedByTest = true;\n if (callback) {\n return callback(e);\n } else {\n throw e;\n }\n }\n\n // explicit safety check. null and undefined can crash the mongo\n // driver. Although the node driver and minimongo do 'support'\n // non-object modifier in that they don't crash, they are not\n // meaningful operations and do not do anything. Defensively throw an\n // error here.\n if (!mod || typeof mod !== 'object')\n throw new Error(\"Invalid modifier. Modifier must be an object.\");\n\n if (!(LocalCollection._isPlainObject(mod) &&\n !EJSON._isCustomType(mod))) {\n throw new Error(\n \"Only plain objects may be used as replacement\" +\n \" documents in MongoDB\");\n }\n\n if (!options) options = {};\n\n var write = self._maybeBeginWrite();\n var refresh = function () {\n self._refresh(collection_name, selector);\n };\n callback = writeCallback(write, refresh, callback);\n try {\n var collection = self.rawCollection(collection_name);\n var mongoOpts = {safe: true};\n // explictly enumerate options that minimongo supports\n if (options.upsert) mongoOpts.upsert = true;\n if (options.multi) mongoOpts.multi = true;\n // Lets you get a more more full result from MongoDB. Use with caution:\n // might not work with C.upsert (as opposed to C.update({upsert:true}) or\n // with simulated upsert.\n if (options.fullResult) mongoOpts.fullResult = true;\n\n var mongoSelector = replaceTypes(selector, replaceMeteorAtomWithMongo);\n var mongoMod = replaceTypes(mod, replaceMeteorAtomWithMongo);\n\n var isModify = LocalCollection._isModificationMod(mongoMod);\n\n if (options._forbidReplace && !isModify) {\n var err = new Error(\"Invalid modifier. Replacements are forbidden.\");\n if (callback) {\n return callback(err);\n } else {\n throw err;\n }\n }\n\n // We've already run replaceTypes/replaceMeteorAtomWithMongo on\n // selector and mod. We assume it doesn't matter, as far as\n // the behavior of modifiers is concerned, whether `_modify`\n // is run on EJSON or on mongo-converted EJSON.\n\n // Run this code up front so that it fails fast if someone uses\n // a Mongo update operator we don't support.\n let knownId;\n if (options.upsert) {\n try {\n let newDoc = LocalCollection._createUpsertDocument(selector, mod);\n knownId = newDoc._id;\n } catch (err) {\n if (callback) {\n return callback(err);\n } else {\n throw err;\n }\n }\n }\n\n if (options.upsert &&\n ! isModify &&\n ! knownId &&\n options.insertedId &&\n ! (options.insertedId instanceof Mongo.ObjectID &&\n options.generatedId)) {\n // In case of an upsert with a replacement, where there is no _id defined\n // in either the query or the replacement doc, mongo will generate an id itself.\n // Therefore we need this special strategy if we want to control the id ourselves.\n\n // We don't need to do this when:\n // - This is not a replacement, so we can add an _id to $setOnInsert\n // - The id is defined by query or mod we can just add it to the replacement doc\n // - The user did not specify any id preference and the id is a Mongo ObjectId,\n // then we can just let Mongo generate the id\n\n simulateUpsertWithInsertedId(\n collection, mongoSelector, mongoMod, options,\n // This callback does not need to be bindEnvironment'ed because\n // simulateUpsertWithInsertedId() wraps it and then passes it through\n // bindEnvironmentForWrite.\n function (error, result) {\n // If we got here via a upsert() call, then options._returnObject will\n // be set and we should return the whole object. Otherwise, we should\n // just return the number of affected docs to match the mongo API.\n if (result && ! options._returnObject) {\n callback(error, result.numberAffected);\n } else {\n callback(error, result);\n }\n }\n );\n } else {\n\n if (options.upsert && !knownId && options.insertedId && isModify) {\n if (!mongoMod.hasOwnProperty('$setOnInsert')) {\n mongoMod.$setOnInsert = {};\n }\n knownId = options.insertedId;\n Object.assign(mongoMod.$setOnInsert, replaceTypes({_id: options.insertedId}, replaceMeteorAtomWithMongo));\n }\n\n collection.update(\n mongoSelector, mongoMod, mongoOpts,\n bindEnvironmentForWrite(function (err, result) {\n if (! err) {\n var meteorResult = transformResult(result);\n if (meteorResult && options._returnObject) {\n // If this was an upsert() call, and we ended up\n // inserting a new doc and we know its id, then\n // return that id as well.\n if (options.upsert && meteorResult.insertedId) {\n if (knownId) {\n meteorResult.insertedId = knownId;\n } else if (meteorResult.insertedId instanceof MongoDB.ObjectID) {\n meteorResult.insertedId = new Mongo.ObjectID(meteorResult.insertedId.toHexString());\n }\n }\n\n callback(err, meteorResult);\n } else {\n callback(err, meteorResult.numberAffected);\n }\n } else {\n callback(err);\n }\n }));\n }\n } catch (e) {\n write.committed();\n throw e;\n }\n};\n\nvar transformResult = function (driverResult) {\n var meteorResult = { numberAffected: 0 };\n if (driverResult) {\n var mongoResult = driverResult.result;\n\n // On updates with upsert:true, the inserted values come as a list of\n // upserted values -- even with options.multi, when the upsert does insert,\n // it only inserts one element.\n if (mongoResult.upserted) {\n meteorResult.numberAffected += mongoResult.upserted.length;\n\n if (mongoResult.upserted.length == 1) {\n meteorResult.insertedId = mongoResult.upserted[0]._id;\n }\n } else {\n meteorResult.numberAffected = mongoResult.n;\n }\n }\n\n return meteorResult;\n};\n\n\nvar NUM_OPTIMISTIC_TRIES = 3;\n\n// exposed for testing\nMongoConnection._isCannotChangeIdError = function (err) {\n\n // Mongo 3.2.* returns error as next Object:\n // {name: String, code: Number, errmsg: String}\n // Older Mongo returns:\n // {name: String, code: Number, err: String}\n var error = err.errmsg || err.err;\n\n // We don't use the error code here\n // because the error code we observed it producing (16837) appears to be\n // a far more generic error code based on examining the source.\n if (error.indexOf('The _id field cannot be changed') === 0\n || error.indexOf(\"the (immutable) field '_id' was found to have been altered to _id\") !== -1) {\n return true;\n }\n\n return false;\n};\n\nvar simulateUpsertWithInsertedId = function (collection, selector, mod,\n options, callback) {\n // STRATEGY: First try doing an upsert with a generated ID.\n // If this throws an error about changing the ID on an existing document\n // then without affecting the database, we know we should probably try\n // an update without the generated ID. If it affected 0 documents,\n // then without affecting the database, we the document that first\n // gave the error is probably removed and we need to try an insert again\n // We go back to step one and repeat.\n // Like all \"optimistic write\" schemes, we rely on the fact that it's\n // unlikely our writes will continue to be interfered with under normal\n // circumstances (though sufficiently heavy contention with writers\n // disagreeing on the existence of an object will cause writes to fail\n // in theory).\n\n var insertedId = options.insertedId; // must exist\n var mongoOptsForUpdate = {\n safe: true,\n multi: options.multi\n };\n var mongoOptsForInsert = {\n safe: true,\n upsert: true\n };\n\n var replacementWithId = Object.assign(\n replaceTypes({_id: insertedId}, replaceMeteorAtomWithMongo),\n mod);\n\n var tries = NUM_OPTIMISTIC_TRIES;\n\n var doUpdate = function () {\n tries--;\n if (! tries) {\n callback(new Error(\"Upsert failed after \" + NUM_OPTIMISTIC_TRIES + \" tries.\"));\n } else {\n collection.update(selector, mod, mongoOptsForUpdate,\n bindEnvironmentForWrite(function (err, result) {\n if (err) {\n callback(err);\n } else if (result && result.result.n != 0) {\n callback(null, {\n numberAffected: result.result.n\n });\n } else {\n doConditionalInsert();\n }\n }));\n }\n };\n\n var doConditionalInsert = function () {\n collection.update(selector, replacementWithId, mongoOptsForInsert,\n bindEnvironmentForWrite(function (err, result) {\n if (err) {\n // figure out if this is a\n // \"cannot change _id of document\" error, and\n // if so, try doUpdate() again, up to 3 times.\n if (MongoConnection._isCannotChangeIdError(err)) {\n doUpdate();\n } else {\n callback(err);\n }\n } else {\n callback(null, {\n numberAffected: result.result.upserted.length,\n insertedId: insertedId,\n });\n }\n }));\n };\n\n doUpdate();\n};\n\n_.each([\"insert\", \"update\", \"remove\", \"dropCollection\", \"dropDatabase\"], function (method) {\n MongoConnection.prototype[method] = function (/* arguments */) {\n var self = this;\n return Meteor.wrapAsync(self[\"_\" + method]).apply(self, arguments);\n };\n});\n\n// XXX MongoConnection.upsert() does not return the id of the inserted document\n// unless you set it explicitly in the selector or modifier (as a replacement\n// doc).\nMongoConnection.prototype.upsert = function (collectionName, selector, mod,\n options, callback) {\n var self = this;\n if (typeof options === \"function\" && ! callback) {\n callback = options;\n options = {};\n }\n\n return self.update(collectionName, selector, mod,\n _.extend({}, options, {\n upsert: true,\n _returnObject: true\n }), callback);\n};\n\nMongoConnection.prototype.find = function (collectionName, selector, options) {\n var self = this;\n\n if (arguments.length === 1)\n selector = {};\n\n return new Cursor(\n self, new CursorDescription(collectionName, selector, options));\n};\n\nMongoConnection.prototype.findOne = function (collection_name, selector,\n options) {\n var self = this;\n if (arguments.length === 1)\n selector = {};\n\n options = options || {};\n options.limit = 1;\n return self.find(collection_name, selector, options).fetch()[0];\n};\n\n// We'll actually design an index API later. For now, we just pass through to\n// Mongo's, but make it synchronous.\nMongoConnection.prototype._ensureIndex = function (collectionName, index,\n options) {\n var self = this;\n\n // We expect this function to be called at startup, not from within a method,\n // so we don't interact with the write fence.\n var collection = self.rawCollection(collectionName);\n var future = new Future;\n var indexName = collection.ensureIndex(index, options, future.resolver());\n future.wait();\n};\nMongoConnection.prototype._dropIndex = function (collectionName, index) {\n var self = this;\n\n // This function is only used by test code, not within a method, so we don't\n // interact with the write fence.\n var collection = self.rawCollection(collectionName);\n var future = new Future;\n var indexName = collection.dropIndex(index, future.resolver());\n future.wait();\n};\n\n// CURSORS\n\n// There are several classes which relate to cursors:\n//\n// CursorDescription represents the arguments used to construct a cursor:\n// collectionName, selector, and (find) options. Because it is used as a key\n// for cursor de-dup, everything in it should either be JSON-stringifiable or\n// not affect observeChanges output (eg, options.transform functions are not\n// stringifiable but do not affect observeChanges).\n//\n// SynchronousCursor is a wrapper around a MongoDB cursor\n// which includes fully-synchronous versions of forEach, etc.\n//\n// Cursor is the cursor object returned from find(), which implements the\n// documented Mongo.Collection cursor API. It wraps a CursorDescription and a\n// SynchronousCursor (lazily: it doesn't contact Mongo until you call a method\n// like fetch or forEach on it).\n//\n// ObserveHandle is the \"observe handle\" returned from observeChanges. It has a\n// reference to an ObserveMultiplexer.\n//\n// ObserveMultiplexer allows multiple identical ObserveHandles to be driven by a\n// single observe driver.\n//\n// There are two \"observe drivers\" which drive ObserveMultiplexers:\n// - PollingObserveDriver caches the results of a query and reruns it when\n// necessary.\n// - OplogObserveDriver follows the Mongo operation log to directly observe\n// database changes.\n// Both implementations follow the same simple interface: when you create them,\n// they start sending observeChanges callbacks (and a ready() invocation) to\n// their ObserveMultiplexer, and you stop them by calling their stop() method.\n\nCursorDescription = function (collectionName, selector, options) {\n var self = this;\n self.collectionName = collectionName;\n self.selector = Mongo.Collection._rewriteSelector(selector);\n self.options = options || {};\n};\n\nCursor = function (mongo, cursorDescription) {\n var self = this;\n\n self._mongo = mongo;\n self._cursorDescription = cursorDescription;\n self._synchronousCursor = null;\n};\n\n_.each(['forEach', 'map', 'fetch', 'count', Symbol.iterator], function (method) {\n Cursor.prototype[method] = function () {\n var self = this;\n\n // You can only observe a tailable cursor.\n if (self._cursorDescription.options.tailable)\n throw new Error(\"Cannot call \" + method + \" on a tailable cursor\");\n\n if (!self._synchronousCursor) {\n self._synchronousCursor = self._mongo._createSynchronousCursor(\n self._cursorDescription, {\n // Make sure that the \"self\" argument to forEach/map callbacks is the\n // Cursor, not the SynchronousCursor.\n selfForIteration: self,\n useTransform: true\n });\n }\n\n return self._synchronousCursor[method].apply(\n self._synchronousCursor, arguments);\n };\n});\n\n// Since we don't actually have a \"nextObject\" interface, there's really no\n// reason to have a \"rewind\" interface. All it did was make multiple calls\n// to fetch/map/forEach return nothing the second time.\n// XXX COMPAT WITH 0.8.1\nCursor.prototype.rewind = function () {\n};\n\nCursor.prototype.getTransform = function () {\n return this._cursorDescription.options.transform;\n};\n\n// When you call Meteor.publish() with a function that returns a Cursor, we need\n// to transmute it into the equivalent subscription. This is the function that\n// does that.\n\nCursor.prototype._publishCursor = function (sub) {\n var self = this;\n var collection = self._cursorDescription.collectionName;\n return Mongo.Collection._publishCursor(self, sub, collection);\n};\n\n// Used to guarantee that publish functions return at most one cursor per\n// collection. Private, because we might later have cursors that include\n// documents from multiple collections somehow.\nCursor.prototype._getCollectionName = function () {\n var self = this;\n return self._cursorDescription.collectionName;\n};\n\nCursor.prototype.observe = function (callbacks) {\n var self = this;\n return LocalCollection._observeFromObserveChanges(self, callbacks);\n};\n\nCursor.prototype.observeChanges = function (callbacks) {\n var self = this;\n var methods = [\n 'addedAt',\n 'added',\n 'changedAt',\n 'changed',\n 'removedAt',\n 'removed',\n 'movedTo'\n ];\n var ordered = LocalCollection._observeChangesCallbacksAreOrdered(callbacks);\n\n // XXX: Can we find out if callbacks are from observe?\n var exceptionName = ' observe/observeChanges callback';\n methods.forEach(function (method) {\n if (callbacks[method] && typeof callbacks[method] == \"function\") {\n callbacks[method] = Meteor.bindEnvironment(callbacks[method], method + exceptionName);\n }\n });\n\n return self._mongo._observeChanges(\n self._cursorDescription, ordered, callbacks);\n};\n\nMongoConnection.prototype._createSynchronousCursor = function(\n cursorDescription, options) {\n var self = this;\n options = _.pick(options || {}, 'selfForIteration', 'useTransform');\n\n var collection = self.rawCollection(cursorDescription.collectionName);\n var cursorOptions = cursorDescription.options;\n var mongoOptions = {\n sort: cursorOptions.sort,\n limit: cursorOptions.limit,\n skip: cursorOptions.skip,\n projection: cursorOptions.fields\n };\n\n // Do we want a tailable cursor (which only works on capped collections)?\n if (cursorOptions.tailable) {\n // We want a tailable cursor...\n mongoOptions.tailable = true;\n // ... and for the server to wait a bit if any getMore has no data (rather\n // than making us put the relevant sleeps in the client)...\n mongoOptions.awaitdata = true;\n // ... and to keep querying the server indefinitely rather than just 5 times\n // if there's no more data.\n mongoOptions.numberOfRetries = -1;\n // And if this is on the oplog collection and the cursor specifies a 'ts',\n // then set the undocumented oplog replay flag, which does a special scan to\n // find the first document (instead of creating an index on ts). This is a\n // very hard-coded Mongo flag which only works on the oplog collection and\n // only works with the ts field.\n if (cursorDescription.collectionName === OPLOG_COLLECTION &&\n cursorDescription.selector.ts) {\n mongoOptions.oplogReplay = true;\n }\n }\n\n var dbCursor = collection.find(\n replaceTypes(cursorDescription.selector, replaceMeteorAtomWithMongo),\n mongoOptions);\n\n if (typeof cursorOptions.maxTimeMs !== 'undefined') {\n dbCursor = dbCursor.maxTimeMS(cursorOptions.maxTimeMs);\n }\n if (typeof cursorOptions.hint !== 'undefined') {\n dbCursor = dbCursor.hint(cursorOptions.hint);\n }\n\n return new SynchronousCursor(dbCursor, cursorDescription, options);\n};\n\nvar SynchronousCursor = function (dbCursor, cursorDescription, options) {\n var self = this;\n options = _.pick(options || {}, 'selfForIteration', 'useTransform');\n\n self._dbCursor = dbCursor;\n self._cursorDescription = cursorDescription;\n // The \"self\" argument passed to forEach/map callbacks. If we're wrapped\n // inside a user-visible Cursor, we want to provide the outer cursor!\n self._selfForIteration = options.selfForIteration || self;\n if (options.useTransform && cursorDescription.options.transform) {\n self._transform = LocalCollection.wrapTransform(\n cursorDescription.options.transform);\n } else {\n self._transform = null;\n }\n\n self._synchronousCount = Future.wrap(dbCursor.count.bind(dbCursor));\n self._visitedIds = new LocalCollection._IdMap;\n};\n\n_.extend(SynchronousCursor.prototype, {\n // Returns a Promise for the next object from the underlying cursor (before\n // the Mongo->Meteor type replacement).\n _rawNextObjectPromise: function () {\n const self = this;\n return new Promise((resolve, reject) => {\n self._dbCursor.next((err, doc) => {\n if (err) {\n reject(err);\n } else {\n resolve(doc);\n }\n });\n });\n },\n\n // Returns a Promise for the next object from the cursor, skipping those whose\n // IDs we've already seen and replacing Mongo atoms with Meteor atoms.\n _nextObjectPromise: async function () {\n var self = this;\n\n while (true) {\n var doc = await self._rawNextObjectPromise();\n\n if (!doc) return null;\n doc = replaceTypes(doc, replaceMongoAtomWithMeteor);\n\n if (!self._cursorDescription.options.tailable && _.has(doc, '_id')) {\n // Did Mongo give us duplicate documents in the same cursor? If so,\n // ignore this one. (Do this before the transform, since transform might\n // return some unrelated value.) We don't do this for tailable cursors,\n // because we want to maintain O(1) memory usage. And if there isn't _id\n // for some reason (maybe it's the oplog), then we don't do this either.\n // (Be careful to do this for falsey but existing _id, though.)\n if (self._visitedIds.has(doc._id)) continue;\n self._visitedIds.set(doc._id, true);\n }\n\n if (self._transform)\n doc = self._transform(doc);\n\n return doc;\n }\n },\n\n // Returns a promise which is resolved with the next object (like with\n // _nextObjectPromise) or rejected if the cursor doesn't return within\n // timeoutMS ms.\n _nextObjectPromiseWithTimeout: function (timeoutMS) {\n const self = this;\n if (!timeoutMS) {\n return self._nextObjectPromise();\n }\n const nextObjectPromise = self._nextObjectPromise();\n const timeoutErr = new Error('Client-side timeout waiting for next object');\n const timeoutPromise = new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(timeoutErr);\n }, timeoutMS);\n });\n return Promise.race([nextObjectPromise, timeoutPromise])\n .catch((err) => {\n if (err === timeoutErr) {\n self.close();\n }\n throw err;\n });\n },\n\n _nextObject: function () {\n var self = this;\n return self._nextObjectPromise().await();\n },\n\n forEach: function (callback, thisArg) {\n var self = this;\n\n // Get back to the beginning.\n self._rewind();\n\n // We implement the loop ourself instead of using self._dbCursor.each,\n // because \"each\" will call its callback outside of a fiber which makes it\n // much more complex to make this function synchronous.\n var index = 0;\n while (true) {\n var doc = self._nextObject();\n if (!doc) return;\n callback.call(thisArg, doc, index++, self._selfForIteration);\n }\n },\n\n // XXX Allow overlapping callback executions if callback yields.\n map: function (callback, thisArg) {\n var self = this;\n var res = [];\n self.forEach(function (doc, index) {\n res.push(callback.call(thisArg, doc, index, self._selfForIteration));\n });\n return res;\n },\n\n _rewind: function () {\n var self = this;\n\n // known to be synchronous\n self._dbCursor.rewind();\n\n self._visitedIds = new LocalCollection._IdMap;\n },\n\n // Mostly usable for tailable cursors.\n close: function () {\n var self = this;\n\n self._dbCursor.close();\n },\n\n fetch: function () {\n var self = this;\n return self.map(_.identity);\n },\n\n count: function (applySkipLimit = false) {\n var self = this;\n return self._synchronousCount(applySkipLimit).wait();\n },\n\n // This method is NOT wrapped in Cursor.\n getRawObjects: function (ordered) {\n var self = this;\n if (ordered) {\n return self.fetch();\n } else {\n var results = new LocalCollection._IdMap;\n self.forEach(function (doc) {\n results.set(doc._id, doc);\n });\n return results;\n }\n }\n});\n\nSynchronousCursor.prototype[Symbol.iterator] = function () {\n var self = this;\n\n // Get back to the beginning.\n self._rewind();\n\n return {\n next() {\n const doc = self._nextObject();\n return doc ? {\n value: doc\n } : {\n done: true\n };\n }\n };\n};\n\n// Tails the cursor described by cursorDescription, most likely on the\n// oplog. Calls docCallback with each document found. Ignores errors and just\n// restarts the tail on error.\n//\n// If timeoutMS is set, then if we don't get a new document every timeoutMS,\n// kill and restart the cursor. This is primarily a workaround for #8598.\nMongoConnection.prototype.tail = function (cursorDescription, docCallback, timeoutMS) {\n var self = this;\n if (!cursorDescription.options.tailable)\n throw new Error(\"Can only tail a tailable cursor\");\n\n var cursor = self._createSynchronousCursor(cursorDescription);\n\n var stopped = false;\n var lastTS;\n var loop = function () {\n var doc = null;\n while (true) {\n if (stopped)\n return;\n try {\n doc = cursor._nextObjectPromiseWithTimeout(timeoutMS).await();\n } catch (err) {\n // There's no good way to figure out if this was actually an error from\n // Mongo, or just client-side (including our own timeout error). Ah\n // well. But either way, we need to retry the cursor (unless the failure\n // was because the observe got stopped).\n doc = null;\n }\n // Since we awaited a promise above, we need to check again to see if\n // we've been stopped before calling the callback.\n if (stopped)\n return;\n if (doc) {\n // If a tailable cursor contains a \"ts\" field, use it to recreate the\n // cursor on error. (\"ts\" is a standard that Mongo uses internally for\n // the oplog, and there's a special flag that lets you do binary search\n // on it instead of needing to use an index.)\n lastTS = doc.ts;\n docCallback(doc);\n } else {\n var newSelector = _.clone(cursorDescription.selector);\n if (lastTS) {\n newSelector.ts = {$gt: lastTS};\n }\n cursor = self._createSynchronousCursor(new CursorDescription(\n cursorDescription.collectionName,\n newSelector,\n cursorDescription.options));\n // Mongo failover takes many seconds. Retry in a bit. (Without this\n // setTimeout, we peg the CPU at 100% and never notice the actual\n // failover.\n Meteor.setTimeout(loop, 100);\n break;\n }\n }\n };\n\n Meteor.defer(loop);\n\n return {\n stop: function () {\n stopped = true;\n cursor.close();\n }\n };\n};\n\nMongoConnection.prototype._observeChanges = function (\n cursorDescription, ordered, callbacks) {\n var self = this;\n\n if (cursorDescription.options.tailable) {\n return self._observeChangesTailable(cursorDescription, ordered, callbacks);\n }\n\n // You may not filter out _id when observing changes, because the id is a core\n // part of the observeChanges API.\n if (cursorDescription.options.fields &&\n (cursorDescription.options.fields._id === 0 ||\n cursorDescription.options.fields._id === false)) {\n throw Error(\"You may not observe a cursor with {fields: {_id: 0}}\");\n }\n\n var observeKey = EJSON.stringify(\n _.extend({ordered: ordered}, cursorDescription));\n\n var multiplexer, observeDriver;\n var firstHandle = false;\n\n // Find a matching ObserveMultiplexer, or create a new one. This next block is\n // guaranteed to not yield (and it doesn't call anything that can observe a\n // new query), so no other calls to this function can interleave with it.\n Meteor._noYieldsAllowed(function () {\n if (_.has(self._observeMultiplexers, observeKey)) {\n multiplexer = self._observeMultiplexers[observeKey];\n } else {\n firstHandle = true;\n // Create a new ObserveMultiplexer.\n multiplexer = new ObserveMultiplexer({\n ordered: ordered,\n onStop: function () {\n delete self._observeMultiplexers[observeKey];\n observeDriver.stop();\n }\n });\n self._observeMultiplexers[observeKey] = multiplexer;\n }\n });\n\n var observeHandle = new ObserveHandle(multiplexer, callbacks);\n\n if (firstHandle) {\n var matcher, sorter;\n var canUseOplog = _.all([\n function () {\n // At a bare minimum, using the oplog requires us to have an oplog, to\n // want unordered callbacks, and to not want a callback on the polls\n // that won't happen.\n return self._oplogHandle && !ordered &&\n !callbacks._testOnlyPollCallback;\n }, function () {\n // We need to be able to compile the selector. Fall back to polling for\n // some newfangled $selector that minimongo doesn't support yet.\n try {\n matcher = new Minimongo.Matcher(cursorDescription.selector);\n return true;\n } catch (e) {\n // XXX make all compilation errors MinimongoError or something\n // so that this doesn't ignore unrelated exceptions\n return false;\n }\n }, function () {\n // ... and the selector itself needs to support oplog.\n return OplogObserveDriver.cursorSupported(cursorDescription, matcher);\n }, function () {\n // And we need to be able to compile the sort, if any. eg, can't be\n // {$natural: 1}.\n if (!cursorDescription.options.sort)\n return true;\n try {\n sorter = new Minimongo.Sorter(cursorDescription.options.sort);\n return true;\n } catch (e) {\n // XXX make all compilation errors MinimongoError or something\n // so that this doesn't ignore unrelated exceptions\n return false;\n }\n }], function (f) { return f(); }); // invoke each function\n\n var driverClass = canUseOplog ? OplogObserveDriver : PollingObserveDriver;\n observeDriver = new driverClass({\n cursorDescription: cursorDescription,\n mongoHandle: self,\n multiplexer: multiplexer,\n ordered: ordered,\n matcher: matcher, // ignored by polling\n sorter: sorter, // ignored by polling\n _testOnlyPollCallback: callbacks._testOnlyPollCallback\n });\n\n // This field is only set for use in tests.\n multiplexer._observeDriver = observeDriver;\n }\n\n // Blocks until the initial adds have been sent.\n multiplexer.addHandleAndSendInitialAdds(observeHandle);\n\n return observeHandle;\n};\n\n// Listen for the invalidation messages that will trigger us to poll the\n// database for changes. If this selector specifies specific IDs, specify them\n// here, so that updates to different specific IDs don't cause us to poll.\n// listenCallback is the same kind of (notification, complete) callback passed\n// to InvalidationCrossbar.listen.\n\nlistenAll = function (cursorDescription, listenCallback) {\n var listeners = [];\n forEachTrigger(cursorDescription, function (trigger) {\n listeners.push(DDPServer._InvalidationCrossbar.listen(\n trigger, listenCallback));\n });\n\n return {\n stop: function () {\n _.each(listeners, function (listener) {\n listener.stop();\n });\n }\n };\n};\n\nforEachTrigger = function (cursorDescription, triggerCallback) {\n var key = {collection: cursorDescription.collectionName};\n var specificIds = LocalCollection._idsMatchedBySelector(\n cursorDescription.selector);\n if (specificIds) {\n _.each(specificIds, function (id) {\n triggerCallback(_.extend({id: id}, key));\n });\n triggerCallback(_.extend({dropCollection: true, id: null}, key));\n } else {\n triggerCallback(key);\n }\n // Everyone cares about the database being dropped.\n triggerCallback({ dropDatabase: true });\n};\n\n// observeChanges for tailable cursors on capped collections.\n//\n// Some differences from normal cursors:\n// - Will never produce anything other than 'added' or 'addedBefore'. If you\n// do update a document that has already been produced, this will not notice\n// it.\n// - If you disconnect and reconnect from Mongo, it will essentially restart\n// the query, which will lead to duplicate results. This is pretty bad,\n// but if you include a field called 'ts' which is inserted as\n// new MongoInternals.MongoTimestamp(0, 0) (which is initialized to the\n// current Mongo-style timestamp), we'll be able to find the place to\n// restart properly. (This field is specifically understood by Mongo with an\n// optimization which allows it to find the right place to start without\n// an index on ts. It's how the oplog works.)\n// - No callbacks are triggered synchronously with the call (there's no\n// differentiation between \"initial data\" and \"later changes\"; everything\n// that matches the query gets sent asynchronously).\n// - De-duplication is not implemented.\n// - Does not yet interact with the write fence. Probably, this should work by\n// ignoring removes (which don't work on capped collections) and updates\n// (which don't affect tailable cursors), and just keeping track of the ID\n// of the inserted object, and closing the write fence once you get to that\n// ID (or timestamp?). This doesn't work well if the document doesn't match\n// the query, though. On the other hand, the write fence can close\n// immediately if it does not match the query. So if we trust minimongo\n// enough to accurately evaluate the query against the write fence, we\n// should be able to do this... Of course, minimongo doesn't even support\n// Mongo Timestamps yet.\nMongoConnection.prototype._observeChangesTailable = function (\n cursorDescription, ordered, callbacks) {\n var self = this;\n\n // Tailable cursors only ever call added/addedBefore callbacks, so it's an\n // error if you didn't provide them.\n if ((ordered && !callbacks.addedBefore) ||\n (!ordered && !callbacks.added)) {\n throw new Error(\"Can't observe an \" + (ordered ? \"ordered\" : \"unordered\")\n + \" tailable cursor without a \"\n + (ordered ? \"addedBefore\" : \"added\") + \" callback\");\n }\n\n return self.tail(cursorDescription, function (doc) {\n var id = doc._id;\n delete doc._id;\n // The ts is an implementation detail. Hide it.\n delete doc.ts;\n if (ordered) {\n callbacks.addedBefore(id, doc, null);\n } else {\n callbacks.added(id, doc);\n }\n });\n};\n\n// XXX We probably need to find a better way to expose this. Right now\n// it's only used by tests, but in fact you need it in normal\n// operation to interact with capped collections.\nMongoInternals.MongoTimestamp = MongoDB.Timestamp;\n\nMongoInternals.Connection = MongoConnection;\n","var Future = Npm.require('fibers/future');\n\nimport { NpmModuleMongodb } from \"meteor/npm-mongo\";\nconst { Timestamp } = NpmModuleMongodb;\n\nOPLOG_COLLECTION = 'oplog.rs';\n\nvar TOO_FAR_BEHIND = process.env.METEOR_OPLOG_TOO_FAR_BEHIND || 2000;\nvar TAIL_TIMEOUT = +process.env.METEOR_OPLOG_TAIL_TIMEOUT || 30000;\n\nvar showTS = function (ts) {\n return \"Timestamp(\" + ts.getHighBits() + \", \" + ts.getLowBits() + \")\";\n};\n\nidForOp = function (op) {\n if (op.op === 'd')\n return op.o._id;\n else if (op.op === 'i')\n return op.o._id;\n else if (op.op === 'u')\n return op.o2._id;\n else if (op.op === 'c')\n throw Error(\"Operator 'c' doesn't supply an object with id: \" +\n EJSON.stringify(op));\n else\n throw Error(\"Unknown op: \" + EJSON.stringify(op));\n};\n\nOplogHandle = function (oplogUrl, dbName) {\n var self = this;\n self._oplogUrl = oplogUrl;\n self._dbName = dbName;\n\n self._oplogLastEntryConnection = null;\n self._oplogTailConnection = null;\n self._stopped = false;\n self._tailHandle = null;\n self._readyFuture = new Future();\n self._crossbar = new DDPServer._Crossbar({\n factPackage: \"mongo-livedata\", factName: \"oplog-watchers\"\n });\n self._baseOplogSelector = {\n ns: new RegExp(\"^(?:\" + [\n Meteor._escapeRegExp(self._dbName + \".\"),\n Meteor._escapeRegExp(\"admin.$cmd\"),\n ].join(\"|\") + \")\"),\n\n $or: [\n { op: { $in: ['i', 'u', 'd'] } },\n // drop collection\n { op: 'c', 'o.drop': { $exists: true } },\n { op: 'c', 'o.dropDatabase': 1 },\n { op: 'c', 'o.applyOps': { $exists: true } },\n ]\n };\n\n // Data structures to support waitUntilCaughtUp(). Each oplog entry has a\n // MongoTimestamp object on it (which is not the same as a Date --- it's a\n // combination of time and an incrementing counter; see\n // http://docs.mongodb.org/manual/reference/bson-types/#timestamps).\n //\n // _catchingUpFutures is an array of {ts: MongoTimestamp, future: Future}\n // objects, sorted by ascending timestamp. _lastProcessedTS is the\n // MongoTimestamp of the last oplog entry we've processed.\n //\n // Each time we call waitUntilCaughtUp, we take a peek at the final oplog\n // entry in the db. If we've already processed it (ie, it is not greater than\n // _lastProcessedTS), waitUntilCaughtUp immediately returns. Otherwise,\n // waitUntilCaughtUp makes a new Future and inserts it along with the final\n // timestamp entry that it read, into _catchingUpFutures. waitUntilCaughtUp\n // then waits on that future, which is resolved once _lastProcessedTS is\n // incremented to be past its timestamp by the worker fiber.\n //\n // XXX use a priority queue or something else that's faster than an array\n self._catchingUpFutures = [];\n self._lastProcessedTS = null;\n\n self._onSkippedEntriesHook = new Hook({\n debugPrintExceptions: \"onSkippedEntries callback\"\n });\n\n self._entryQueue = new Meteor._DoubleEndedQueue();\n self._workerActive = false;\n\n self._startTailing();\n};\n\n_.extend(OplogHandle.prototype, {\n stop: function () {\n var self = this;\n if (self._stopped)\n return;\n self._stopped = true;\n if (self._tailHandle)\n self._tailHandle.stop();\n // XXX should close connections too\n },\n onOplogEntry: function (trigger, callback) {\n var self = this;\n if (self._stopped)\n throw new Error(\"Called onOplogEntry on stopped handle!\");\n\n // Calling onOplogEntry requires us to wait for the tailing to be ready.\n self._readyFuture.wait();\n\n var originalCallback = callback;\n callback = Meteor.bindEnvironment(function (notification) {\n originalCallback(notification);\n }, function (err) {\n Meteor._debug(\"Error in oplog callback\", err);\n });\n var listenHandle = self._crossbar.listen(trigger, callback);\n return {\n stop: function () {\n listenHandle.stop();\n }\n };\n },\n // Register a callback to be invoked any time we skip oplog entries (eg,\n // because we are too far behind).\n onSkippedEntries: function (callback) {\n var self = this;\n if (self._stopped)\n throw new Error(\"Called onSkippedEntries on stopped handle!\");\n return self._onSkippedEntriesHook.register(callback);\n },\n // Calls `callback` once the oplog has been processed up to a point that is\n // roughly \"now\": specifically, once we've processed all ops that are\n // currently visible.\n // XXX become convinced that this is actually safe even if oplogConnection\n // is some kind of pool\n waitUntilCaughtUp: function () {\n var self = this;\n if (self._stopped)\n throw new Error(\"Called waitUntilCaughtUp on stopped handle!\");\n\n // Calling waitUntilCaughtUp requries us to wait for the oplog connection to\n // be ready.\n self._readyFuture.wait();\n var lastEntry;\n\n while (!self._stopped) {\n // We need to make the selector at least as restrictive as the actual\n // tailing selector (ie, we need to specify the DB name) or else we might\n // find a TS that won't show up in the actual tail stream.\n try {\n lastEntry = self._oplogLastEntryConnection.findOne(\n OPLOG_COLLECTION, self._baseOplogSelector,\n {fields: {ts: 1}, sort: {$natural: -1}});\n break;\n } catch (e) {\n // During failover (eg) if we get an exception we should log and retry\n // instead of crashing.\n Meteor._debug(\"Got exception while reading last entry\", e);\n Meteor._sleepForMs(100);\n }\n }\n\n if (self._stopped)\n return;\n\n if (!lastEntry) {\n // Really, nothing in the oplog? Well, we've processed everything.\n return;\n }\n\n var ts = lastEntry.ts;\n if (!ts)\n throw Error(\"oplog entry without ts: \" + EJSON.stringify(lastEntry));\n\n if (self._lastProcessedTS && ts.lessThanOrEqual(self._lastProcessedTS)) {\n // We've already caught up to here.\n return;\n }\n\n\n // Insert the future into our list. Almost always, this will be at the end,\n // but it's conceivable that if we fail over from one primary to another,\n // the oplog entries we see will go backwards.\n var insertAfter = self._catchingUpFutures.length;\n while (insertAfter - 1 > 0 && self._catchingUpFutures[insertAfter - 1].ts.greaterThan(ts)) {\n insertAfter--;\n }\n var f = new Future;\n self._catchingUpFutures.splice(insertAfter, 0, {ts: ts, future: f});\n f.wait();\n },\n _startTailing: function () {\n var self = this;\n // First, make sure that we're talking to the local database.\n var mongodbUri = Npm.require('mongodb-uri');\n if (mongodbUri.parse(self._oplogUrl).database !== 'local') {\n throw Error(\"$MONGO_OPLOG_URL must be set to the 'local' database of \" +\n \"a Mongo replica set\");\n }\n\n // We make two separate connections to Mongo. The Node Mongo driver\n // implements a naive round-robin connection pool: each \"connection\" is a\n // pool of several (5 by default) TCP connections, and each request is\n // rotated through the pools. Tailable cursor queries block on the server\n // until there is some data to return (or until a few seconds have\n // passed). So if the connection pool used for tailing cursors is the same\n // pool used for other queries, the other queries will be delayed by seconds\n // 1/5 of the time.\n //\n // The tail connection will only ever be running a single tail command, so\n // it only needs to make one underlying TCP connection.\n self._oplogTailConnection = new MongoConnection(\n self._oplogUrl, {poolSize: 1});\n // XXX better docs, but: it's to get monotonic results\n // XXX is it safe to say \"if there's an in flight query, just use its\n // results\"? I don't think so but should consider that\n self._oplogLastEntryConnection = new MongoConnection(\n self._oplogUrl, {poolSize: 1});\n\n // Now, make sure that there actually is a repl set here. If not, oplog\n // tailing won't ever find anything!\n // More on the isMasterDoc\n // https://docs.mongodb.com/manual/reference/command/isMaster/\n var f = new Future;\n self._oplogLastEntryConnection.db.admin().command(\n { ismaster: 1 }, f.resolver());\n var isMasterDoc = f.wait();\n\n if (!(isMasterDoc && isMasterDoc.setName)) {\n throw Error(\"$MONGO_OPLOG_URL must be set to the 'local' database of \" +\n \"a Mongo replica set\");\n }\n\n // Find the last oplog entry.\n var lastOplogEntry = self._oplogLastEntryConnection.findOne(\n OPLOG_COLLECTION, {}, {sort: {$natural: -1}, fields: {ts: 1}});\n\n var oplogSelector = _.clone(self._baseOplogSelector);\n if (lastOplogEntry) {\n // Start after the last entry that currently exists.\n oplogSelector.ts = {$gt: lastOplogEntry.ts};\n // If there are any calls to callWhenProcessedLatest before any other\n // oplog entries show up, allow callWhenProcessedLatest to call its\n // callback immediately.\n self._lastProcessedTS = lastOplogEntry.ts;\n }\n\n var cursorDescription = new CursorDescription(\n OPLOG_COLLECTION, oplogSelector, {tailable: true});\n\n // Start tailing the oplog.\n //\n // We restart the low-level oplog query every 30 seconds if we didn't get a\n // doc. This is a workaround for #8598: the Node Mongo driver has at least\n // one bug that can lead to query callbacks never getting called (even with\n // an error) when leadership failover occur.\n self._tailHandle = self._oplogTailConnection.tail(\n cursorDescription,\n function (doc) {\n self._entryQueue.push(doc);\n self._maybeStartWorker();\n },\n TAIL_TIMEOUT\n );\n self._readyFuture.return();\n },\n\n _maybeStartWorker: function () {\n var self = this;\n if (self._workerActive) return;\n self._workerActive = true;\n\n Meteor.defer(function () {\n // May be called recursively in case of transactions.\n function handleDoc(doc) {\n if (doc.ns === \"admin.$cmd\") {\n if (doc.o.applyOps) {\n // This was a successful transaction, so we need to apply the\n // operations that were involved.\n let nextTimestamp = doc.ts;\n doc.o.applyOps.forEach(op => {\n // See https://github.com/meteor/meteor/issues/10420.\n if (!op.ts) {\n op.ts = nextTimestamp;\n nextTimestamp = nextTimestamp.add(Timestamp.ONE);\n }\n handleDoc(op);\n });\n return;\n }\n throw new Error(\"Unknown command \" + EJSON.stringify(doc));\n }\n\n const trigger = {\n dropCollection: false,\n dropDatabase: false,\n op: doc,\n };\n\n if (typeof doc.ns === \"string\" &&\n doc.ns.startsWith(self._dbName + \".\")) {\n trigger.collection = doc.ns.slice(self._dbName.length + 1);\n }\n\n // Is it a special command and the collection name is hidden\n // somewhere in operator?\n if (trigger.collection === \"$cmd\") {\n if (doc.o.dropDatabase) {\n delete trigger.collection;\n trigger.dropDatabase = true;\n } else if (_.has(doc.o, \"drop\")) {\n trigger.collection = doc.o.drop;\n trigger.dropCollection = true;\n trigger.id = null;\n } else {\n throw Error(\"Unknown command \" + EJSON.stringify(doc));\n }\n\n } else {\n // All other ops have an id.\n trigger.id = idForOp(doc);\n }\n\n self._crossbar.fire(trigger);\n }\n\n try {\n while (! self._stopped &&\n ! self._entryQueue.isEmpty()) {\n // Are we too far behind? Just tell our observers that they need to\n // repoll, and drop our queue.\n if (self._entryQueue.length > TOO_FAR_BEHIND) {\n var lastEntry = self._entryQueue.pop();\n self._entryQueue.clear();\n\n self._onSkippedEntriesHook.each(function (callback) {\n callback();\n return true;\n });\n\n // Free any waitUntilCaughtUp() calls that were waiting for us to\n // pass something that we just skipped.\n self._setLastProcessedTS(lastEntry.ts);\n continue;\n }\n\n const doc = self._entryQueue.shift();\n\n // Fire trigger(s) for this doc.\n handleDoc(doc);\n\n // Now that we've processed this operation, process pending\n // sequencers.\n if (doc.ts) {\n self._setLastProcessedTS(doc.ts);\n } else {\n throw Error(\"oplog entry without ts: \" + EJSON.stringify(doc));\n }\n }\n } finally {\n self._workerActive = false;\n }\n });\n },\n\n _setLastProcessedTS: function (ts) {\n var self = this;\n self._lastProcessedTS = ts;\n while (!_.isEmpty(self._catchingUpFutures) && self._catchingUpFutures[0].ts.lessThanOrEqual(self._lastProcessedTS)) {\n var sequencer = self._catchingUpFutures.shift();\n sequencer.future.return();\n }\n },\n\n //Methods used on tests to dinamically change TOO_FAR_BEHIND\n _defineTooFarBehind: function(value) {\n TOO_FAR_BEHIND = value;\n },\n _resetTooFarBehind: function() {\n TOO_FAR_BEHIND = process.env.METEOR_OPLOG_TOO_FAR_BEHIND || 2000;\n }\n});\n","var Future = Npm.require('fibers/future');\n\nObserveMultiplexer = function (options) {\n var self = this;\n\n if (!options || !_.has(options, 'ordered'))\n throw Error(\"must specified ordered\");\n\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"mongo-livedata\", \"observe-multiplexers\", 1);\n\n self._ordered = options.ordered;\n self._onStop = options.onStop || function () {};\n self._queue = new Meteor._SynchronousQueue();\n self._handles = {};\n self._readyFuture = new Future;\n self._cache = new LocalCollection._CachingChangeObserver({\n ordered: options.ordered});\n // Number of addHandleAndSendInitialAdds tasks scheduled but not yet\n // running. removeHandle uses this to know if it's time to call the onStop\n // callback.\n self._addHandleTasksScheduledButNotPerformed = 0;\n\n _.each(self.callbackNames(), function (callbackName) {\n self[callbackName] = function (/* ... */) {\n self._applyCallback(callbackName, _.toArray(arguments));\n };\n });\n};\n\n_.extend(ObserveMultiplexer.prototype, {\n addHandleAndSendInitialAdds: function (handle) {\n var self = this;\n\n // Check this before calling runTask (even though runTask does the same\n // check) so that we don't leak an ObserveMultiplexer on error by\n // incrementing _addHandleTasksScheduledButNotPerformed and never\n // decrementing it.\n if (!self._queue.safeToRunTask())\n throw new Error(\"Can't call observeChanges from an observe callback on the same query\");\n ++self._addHandleTasksScheduledButNotPerformed;\n\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"mongo-livedata\", \"observe-handles\", 1);\n\n self._queue.runTask(function () {\n self._handles[handle._id] = handle;\n // Send out whatever adds we have so far (whether or not we the\n // multiplexer is ready).\n self._sendAdds(handle);\n --self._addHandleTasksScheduledButNotPerformed;\n });\n // *outside* the task, since otherwise we'd deadlock\n self._readyFuture.wait();\n },\n\n // Remove an observe handle. If it was the last observe handle, call the\n // onStop callback; you cannot add any more observe handles after this.\n //\n // This is not synchronized with polls and handle additions: this means that\n // you can safely call it from within an observe callback, but it also means\n // that we have to be careful when we iterate over _handles.\n removeHandle: function (id) {\n var self = this;\n\n // This should not be possible: you can only call removeHandle by having\n // access to the ObserveHandle, which isn't returned to user code until the\n // multiplex is ready.\n if (!self._ready())\n throw new Error(\"Can't remove handles until the multiplex is ready\");\n\n delete self._handles[id];\n\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"mongo-livedata\", \"observe-handles\", -1);\n\n if (_.isEmpty(self._handles) &&\n self._addHandleTasksScheduledButNotPerformed === 0) {\n self._stop();\n }\n },\n _stop: function (options) {\n var self = this;\n options = options || {};\n\n // It shouldn't be possible for us to stop when all our handles still\n // haven't been returned from observeChanges!\n if (! self._ready() && ! options.fromQueryError)\n throw Error(\"surprising _stop: not ready\");\n\n // Call stop callback (which kills the underlying process which sends us\n // callbacks and removes us from the connection's dictionary).\n self._onStop();\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"mongo-livedata\", \"observe-multiplexers\", -1);\n\n // Cause future addHandleAndSendInitialAdds calls to throw (but the onStop\n // callback should make our connection forget about us).\n self._handles = null;\n },\n\n // Allows all addHandleAndSendInitialAdds calls to return, once all preceding\n // adds have been processed. Does not block.\n ready: function () {\n var self = this;\n self._queue.queueTask(function () {\n if (self._ready())\n throw Error(\"can't make ObserveMultiplex ready twice!\");\n self._readyFuture.return();\n });\n },\n\n // If trying to execute the query results in an error, call this. This is\n // intended for permanent errors, not transient network errors that could be\n // fixed. It should only be called before ready(), because if you called ready\n // that meant that you managed to run the query once. It will stop this\n // ObserveMultiplex and cause addHandleAndSendInitialAdds calls (and thus\n // observeChanges calls) to throw the error.\n queryError: function (err) {\n var self = this;\n self._queue.runTask(function () {\n if (self._ready())\n throw Error(\"can't claim query has an error after it worked!\");\n self._stop({fromQueryError: true});\n self._readyFuture.throw(err);\n });\n },\n\n // Calls \"cb\" once the effects of all \"ready\", \"addHandleAndSendInitialAdds\"\n // and observe callbacks which came before this call have been propagated to\n // all handles. \"ready\" must have already been called on this multiplexer.\n onFlush: function (cb) {\n var self = this;\n self._queue.queueTask(function () {\n if (!self._ready())\n throw Error(\"only call onFlush on a multiplexer that will be ready\");\n cb();\n });\n },\n callbackNames: function () {\n var self = this;\n if (self._ordered)\n return [\"addedBefore\", \"changed\", \"movedBefore\", \"removed\"];\n else\n return [\"added\", \"changed\", \"removed\"];\n },\n _ready: function () {\n return this._readyFuture.isResolved();\n },\n _applyCallback: function (callbackName, args) {\n var self = this;\n self._queue.queueTask(function () {\n // If we stopped in the meantime, do nothing.\n if (!self._handles)\n return;\n\n // First, apply the change to the cache.\n // XXX We could make applyChange callbacks promise not to hang on to any\n // state from their arguments (assuming that their supplied callbacks\n // don't) and skip this clone. Currently 'changed' hangs on to state\n // though.\n self._cache.applyChange[callbackName].apply(null, EJSON.clone(args));\n\n // If we haven't finished the initial adds, then we should only be getting\n // adds.\n if (!self._ready() &&\n (callbackName !== 'added' && callbackName !== 'addedBefore')) {\n throw new Error(\"Got \" + callbackName + \" during initial adds\");\n }\n\n // Now multiplex the callbacks out to all observe handles. It's OK if\n // these calls yield; since we're inside a task, no other use of our queue\n // can continue until these are done. (But we do have to be careful to not\n // use a handle that got removed, because removeHandle does not use the\n // queue; thus, we iterate over an array of keys that we control.)\n _.each(_.keys(self._handles), function (handleId) {\n var handle = self._handles && self._handles[handleId];\n if (!handle)\n return;\n var callback = handle['_' + callbackName];\n // clone arguments so that callbacks can mutate their arguments\n callback && callback.apply(null, EJSON.clone(args));\n });\n });\n },\n\n // Sends initial adds to a handle. It should only be called from within a task\n // (the task that is processing the addHandleAndSendInitialAdds call). It\n // synchronously invokes the handle's added or addedBefore; there's no need to\n // flush the queue afterwards to ensure that the callbacks get out.\n _sendAdds: function (handle) {\n var self = this;\n if (self._queue.safeToRunTask())\n throw Error(\"_sendAdds may only be called from within a task!\");\n var add = self._ordered ? handle._addedBefore : handle._added;\n if (!add)\n return;\n // note: docs may be an _IdMap or an OrderedDict\n self._cache.docs.forEach(function (doc, id) {\n if (!_.has(self._handles, handle._id))\n throw Error(\"handle got removed before sending initial adds!\");\n var fields = EJSON.clone(doc);\n delete fields._id;\n if (self._ordered)\n add(id, fields, null); // we're going in order, so add at end\n else\n add(id, fields);\n });\n }\n});\n\n\nvar nextObserveHandleId = 1;\nObserveHandle = function (multiplexer, callbacks) {\n var self = this;\n // The end user is only supposed to call stop(). The other fields are\n // accessible to the multiplexer, though.\n self._multiplexer = multiplexer;\n _.each(multiplexer.callbackNames(), function (name) {\n if (callbacks[name]) {\n self['_' + name] = callbacks[name];\n } else if (name === \"addedBefore\" && callbacks.added) {\n // Special case: if you specify \"added\" and \"movedBefore\", you get an\n // ordered observe where for some reason you don't get ordering data on\n // the adds. I dunno, we wrote tests for it, there must have been a\n // reason.\n self._addedBefore = function (id, fields, before) {\n callbacks.added(id, fields);\n };\n }\n });\n self._stopped = false;\n self._id = nextObserveHandleId++;\n};\nObserveHandle.prototype.stop = function () {\n var self = this;\n if (self._stopped)\n return;\n self._stopped = true;\n self._multiplexer.removeHandle(self._id);\n};\n","var Fiber = Npm.require('fibers');\n\nexport class DocFetcher {\n constructor(mongoConnection) {\n this._mongoConnection = mongoConnection;\n // Map from op -> [callback]\n this._callbacksForOp = new Map;\n }\n\n // Fetches document \"id\" from collectionName, returning it or null if not\n // found.\n //\n // If you make multiple calls to fetch() with the same op reference,\n // DocFetcher may assume that they all return the same document. (It does\n // not check to see if collectionName/id match.)\n //\n // You may assume that callback is never called synchronously (and in fact\n // OplogObserveDriver does so).\n fetch(collectionName, id, op, callback) {\n const self = this;\n\n check(collectionName, String);\n check(op, Object);\n\n // If there's already an in-progress fetch for this cache key, yield until\n // it's done and return whatever it returns.\n if (self._callbacksForOp.has(op)) {\n self._callbacksForOp.get(op).push(callback);\n return;\n }\n\n const callbacks = [callback];\n self._callbacksForOp.set(op, callbacks);\n\n Fiber(function () {\n try {\n var doc = self._mongoConnection.findOne(\n collectionName, {_id: id}) || null;\n // Return doc to all relevant callbacks. Note that this array can\n // continue to grow during callback excecution.\n while (callbacks.length > 0) {\n // Clone the document so that the various calls to fetch don't return\n // objects that are intertwingled with each other. Clone before\n // popping the future, so that if clone throws, the error gets passed\n // to the next callback.\n callbacks.pop()(null, EJSON.clone(doc));\n }\n } catch (e) {\n while (callbacks.length > 0) {\n callbacks.pop()(e);\n }\n } finally {\n // XXX consider keeping the doc around for a period of time before\n // removing from the cache\n self._callbacksForOp.delete(op);\n }\n }).run();\n }\n}\n","var POLLING_THROTTLE_MS = +process.env.METEOR_POLLING_THROTTLE_MS || 50;\nvar POLLING_INTERVAL_MS = +process.env.METEOR_POLLING_INTERVAL_MS || 10 * 1000;\n\nPollingObserveDriver = function (options) {\n var self = this;\n\n self._cursorDescription = options.cursorDescription;\n self._mongoHandle = options.mongoHandle;\n self._ordered = options.ordered;\n self._multiplexer = options.multiplexer;\n self._stopCallbacks = [];\n self._stopped = false;\n\n self._synchronousCursor = self._mongoHandle._createSynchronousCursor(\n self._cursorDescription);\n\n // previous results snapshot. on each poll cycle, diffs against\n // results drives the callbacks.\n self._results = null;\n\n // The number of _pollMongo calls that have been added to self._taskQueue but\n // have not started running. Used to make sure we never schedule more than one\n // _pollMongo (other than possibly the one that is currently running). It's\n // also used by _suspendPolling to pretend there's a poll scheduled. Usually,\n // it's either 0 (for \"no polls scheduled other than maybe one currently\n // running\") or 1 (for \"a poll scheduled that isn't running yet\"), but it can\n // also be 2 if incremented by _suspendPolling.\n self._pollsScheduledButNotStarted = 0;\n self._pendingWrites = []; // people to notify when polling completes\n\n // Make sure to create a separately throttled function for each\n // PollingObserveDriver object.\n self._ensurePollIsScheduled = _.throttle(\n self._unthrottledEnsurePollIsScheduled,\n self._cursorDescription.options.pollingThrottleMs || POLLING_THROTTLE_MS /* ms */);\n\n // XXX figure out if we still need a queue\n self._taskQueue = new Meteor._SynchronousQueue();\n\n var listenersHandle = listenAll(\n self._cursorDescription, function (notification) {\n // When someone does a transaction that might affect us, schedule a poll\n // of the database. If that transaction happens inside of a write fence,\n // block the fence until we've polled and notified observers.\n var fence = DDPServer._CurrentWriteFence.get();\n if (fence)\n self._pendingWrites.push(fence.beginWrite());\n // Ensure a poll is scheduled... but if we already know that one is,\n // don't hit the throttled _ensurePollIsScheduled function (which might\n // lead to us calling it unnecessarily in ms).\n if (self._pollsScheduledButNotStarted === 0)\n self._ensurePollIsScheduled();\n }\n );\n self._stopCallbacks.push(function () { listenersHandle.stop(); });\n\n // every once and a while, poll even if we don't think we're dirty, for\n // eventual consistency with database writes from outside the Meteor\n // universe.\n //\n // For testing, there's an undocumented callback argument to observeChanges\n // which disables time-based polling and gets called at the beginning of each\n // poll.\n if (options._testOnlyPollCallback) {\n self._testOnlyPollCallback = options._testOnlyPollCallback;\n } else {\n var pollingInterval =\n self._cursorDescription.options.pollingIntervalMs ||\n self._cursorDescription.options._pollingInterval || // COMPAT with 1.2\n POLLING_INTERVAL_MS;\n var intervalHandle = Meteor.setInterval(\n _.bind(self._ensurePollIsScheduled, self), pollingInterval);\n self._stopCallbacks.push(function () {\n Meteor.clearInterval(intervalHandle);\n });\n }\n\n // Make sure we actually poll soon!\n self._unthrottledEnsurePollIsScheduled();\n\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"mongo-livedata\", \"observe-drivers-polling\", 1);\n};\n\n_.extend(PollingObserveDriver.prototype, {\n // This is always called through _.throttle (except once at startup).\n _unthrottledEnsurePollIsScheduled: function () {\n var self = this;\n if (self._pollsScheduledButNotStarted > 0)\n return;\n ++self._pollsScheduledButNotStarted;\n self._taskQueue.queueTask(function () {\n self._pollMongo();\n });\n },\n\n // test-only interface for controlling polling.\n //\n // _suspendPolling blocks until any currently running and scheduled polls are\n // done, and prevents any further polls from being scheduled. (new\n // ObserveHandles can be added and receive their initial added callbacks,\n // though.)\n //\n // _resumePolling immediately polls, and allows further polls to occur.\n _suspendPolling: function() {\n var self = this;\n // Pretend that there's another poll scheduled (which will prevent\n // _ensurePollIsScheduled from queueing any more polls).\n ++self._pollsScheduledButNotStarted;\n // Now block until all currently running or scheduled polls are done.\n self._taskQueue.runTask(function() {});\n\n // Confirm that there is only one \"poll\" (the fake one we're pretending to\n // have) scheduled.\n if (self._pollsScheduledButNotStarted !== 1)\n throw new Error(\"_pollsScheduledButNotStarted is \" +\n self._pollsScheduledButNotStarted);\n },\n _resumePolling: function() {\n var self = this;\n // We should be in the same state as in the end of _suspendPolling.\n if (self._pollsScheduledButNotStarted !== 1)\n throw new Error(\"_pollsScheduledButNotStarted is \" +\n self._pollsScheduledButNotStarted);\n // Run a poll synchronously (which will counteract the\n // ++_pollsScheduledButNotStarted from _suspendPolling).\n self._taskQueue.runTask(function () {\n self._pollMongo();\n });\n },\n\n _pollMongo: function () {\n var self = this;\n --self._pollsScheduledButNotStarted;\n\n if (self._stopped)\n return;\n\n var first = false;\n var newResults;\n var oldResults = self._results;\n if (!oldResults) {\n first = true;\n // XXX maybe use OrderedDict instead?\n oldResults = self._ordered ? [] : new LocalCollection._IdMap;\n }\n\n self._testOnlyPollCallback && self._testOnlyPollCallback();\n\n // Save the list of pending writes which this round will commit.\n var writesForCycle = self._pendingWrites;\n self._pendingWrites = [];\n\n // Get the new query results. (This yields.)\n try {\n newResults = self._synchronousCursor.getRawObjects(self._ordered);\n } catch (e) {\n if (first && typeof(e.code) === 'number') {\n // This is an error document sent to us by mongod, not a connection\n // error generated by the client. And we've never seen this query work\n // successfully. Probably it's a bad selector or something, so we should\n // NOT retry. Instead, we should halt the observe (which ends up calling\n // `stop` on us).\n self._multiplexer.queryError(\n new Error(\n \"Exception while polling query \" +\n JSON.stringify(self._cursorDescription) + \": \" + e.message));\n return;\n }\n\n // getRawObjects can throw if we're having trouble talking to the\n // database. That's fine --- we will repoll later anyway. But we should\n // make sure not to lose track of this cycle's writes.\n // (It also can throw if there's just something invalid about this query;\n // unfortunately the ObserveDriver API doesn't provide a good way to\n // \"cancel\" the observe from the inside in this case.\n Array.prototype.push.apply(self._pendingWrites, writesForCycle);\n Meteor._debug(\"Exception while polling query \" +\n JSON.stringify(self._cursorDescription), e);\n return;\n }\n\n // Run diffs.\n if (!self._stopped) {\n LocalCollection._diffQueryChanges(\n self._ordered, oldResults, newResults, self._multiplexer);\n }\n\n // Signals the multiplexer to allow all observeChanges calls that share this\n // multiplexer to return. (This happens asynchronously, via the\n // multiplexer's queue.)\n if (first)\n self._multiplexer.ready();\n\n // Replace self._results atomically. (This assignment is what makes `first`\n // stay through on the next cycle, so we've waited until after we've\n // committed to ready-ing the multiplexer.)\n self._results = newResults;\n\n // Once the ObserveMultiplexer has processed everything we've done in this\n // round, mark all the writes which existed before this call as\n // commmitted. (If new writes have shown up in the meantime, there'll\n // already be another _pollMongo task scheduled.)\n self._multiplexer.onFlush(function () {\n _.each(writesForCycle, function (w) {\n w.committed();\n });\n });\n },\n\n stop: function () {\n var self = this;\n self._stopped = true;\n _.each(self._stopCallbacks, function (c) { c(); });\n // Release any write fences that are waiting on us.\n _.each(self._pendingWrites, function (w) {\n w.committed();\n });\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"mongo-livedata\", \"observe-drivers-polling\", -1);\n }\n});\n","var Future = Npm.require('fibers/future');\n\nvar PHASE = {\n QUERYING: \"QUERYING\",\n FETCHING: \"FETCHING\",\n STEADY: \"STEADY\"\n};\n\n// Exception thrown by _needToPollQuery which unrolls the stack up to the\n// enclosing call to finishIfNeedToPollQuery.\nvar SwitchedToQuery = function () {};\nvar finishIfNeedToPollQuery = function (f) {\n return function () {\n try {\n f.apply(this, arguments);\n } catch (e) {\n if (!(e instanceof SwitchedToQuery))\n throw e;\n }\n };\n};\n\nvar currentId = 0;\n\n// OplogObserveDriver is an alternative to PollingObserveDriver which follows\n// the Mongo operation log instead of just re-polling the query. It obeys the\n// same simple interface: constructing it starts sending observeChanges\n// callbacks (and a ready() invocation) to the ObserveMultiplexer, and you stop\n// it by calling the stop() method.\nOplogObserveDriver = function (options) {\n var self = this;\n self._usesOplog = true; // tests look at this\n\n self._id = currentId;\n currentId++;\n\n self._cursorDescription = options.cursorDescription;\n self._mongoHandle = options.mongoHandle;\n self._multiplexer = options.multiplexer;\n\n if (options.ordered) {\n throw Error(\"OplogObserveDriver only supports unordered observeChanges\");\n }\n\n var sorter = options.sorter;\n // We don't support $near and other geo-queries so it's OK to initialize the\n // comparator only once in the constructor.\n var comparator = sorter && sorter.getComparator();\n\n if (options.cursorDescription.options.limit) {\n // There are several properties ordered driver implements:\n // - _limit is a positive number\n // - _comparator is a function-comparator by which the query is ordered\n // - _unpublishedBuffer is non-null Min/Max Heap,\n // the empty buffer in STEADY phase implies that the\n // everything that matches the queries selector fits\n // into published set.\n // - _published - Min Heap (also implements IdMap methods)\n\n var heapOptions = { IdMap: LocalCollection._IdMap };\n self._limit = self._cursorDescription.options.limit;\n self._comparator = comparator;\n self._sorter = sorter;\n self._unpublishedBuffer = new MinMaxHeap(comparator, heapOptions);\n // We need something that can find Max value in addition to IdMap interface\n self._published = new MaxHeap(comparator, heapOptions);\n } else {\n self._limit = 0;\n self._comparator = null;\n self._sorter = null;\n self._unpublishedBuffer = null;\n self._published = new LocalCollection._IdMap;\n }\n\n // Indicates if it is safe to insert a new document at the end of the buffer\n // for this query. i.e. it is known that there are no documents matching the\n // selector those are not in published or buffer.\n self._safeAppendToBuffer = false;\n\n self._stopped = false;\n self._stopHandles = [];\n\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"mongo-livedata\", \"observe-drivers-oplog\", 1);\n\n self._registerPhaseChange(PHASE.QUERYING);\n\n self._matcher = options.matcher;\n var projection = self._cursorDescription.options.fields || {};\n self._projectionFn = LocalCollection._compileProjection(projection);\n // Projection function, result of combining important fields for selector and\n // existing fields projection\n self._sharedProjection = self._matcher.combineIntoProjection(projection);\n if (sorter)\n self._sharedProjection = sorter.combineIntoProjection(self._sharedProjection);\n self._sharedProjectionFn = LocalCollection._compileProjection(\n self._sharedProjection);\n\n self._needToFetch = new LocalCollection._IdMap;\n self._currentlyFetching = null;\n self._fetchGeneration = 0;\n\n self._requeryWhenDoneThisQuery = false;\n self._writesToCommitWhenWeReachSteady = [];\n\n // If the oplog handle tells us that it skipped some entries (because it got\n // behind, say), re-poll.\n self._stopHandles.push(self._mongoHandle._oplogHandle.onSkippedEntries(\n finishIfNeedToPollQuery(function () {\n self._needToPollQuery();\n })\n ));\n\n forEachTrigger(self._cursorDescription, function (trigger) {\n self._stopHandles.push(self._mongoHandle._oplogHandle.onOplogEntry(\n trigger, function (notification) {\n Meteor._noYieldsAllowed(finishIfNeedToPollQuery(function () {\n var op = notification.op;\n if (notification.dropCollection || notification.dropDatabase) {\n // Note: this call is not allowed to block on anything (especially\n // on waiting for oplog entries to catch up) because that will block\n // onOplogEntry!\n self._needToPollQuery();\n } else {\n // All other operators should be handled depending on phase\n if (self._phase === PHASE.QUERYING) {\n self._handleOplogEntryQuerying(op);\n } else {\n self._handleOplogEntrySteadyOrFetching(op);\n }\n }\n }));\n }\n ));\n });\n\n // XXX ordering w.r.t. everything else?\n self._stopHandles.push(listenAll(\n self._cursorDescription, function (notification) {\n // If we're not in a pre-fire write fence, we don't have to do anything.\n var fence = DDPServer._CurrentWriteFence.get();\n if (!fence || fence.fired)\n return;\n\n if (fence._oplogObserveDrivers) {\n fence._oplogObserveDrivers[self._id] = self;\n return;\n }\n\n fence._oplogObserveDrivers = {};\n fence._oplogObserveDrivers[self._id] = self;\n\n fence.onBeforeFire(function () {\n var drivers = fence._oplogObserveDrivers;\n delete fence._oplogObserveDrivers;\n\n // This fence cannot fire until we've caught up to \"this point\" in the\n // oplog, and all observers made it back to the steady state.\n self._mongoHandle._oplogHandle.waitUntilCaughtUp();\n\n _.each(drivers, function (driver) {\n if (driver._stopped)\n return;\n\n var write = fence.beginWrite();\n if (driver._phase === PHASE.STEADY) {\n // Make sure that all of the callbacks have made it through the\n // multiplexer and been delivered to ObserveHandles before committing\n // writes.\n driver._multiplexer.onFlush(function () {\n write.committed();\n });\n } else {\n driver._writesToCommitWhenWeReachSteady.push(write);\n }\n });\n });\n }\n ));\n\n // When Mongo fails over, we need to repoll the query, in case we processed an\n // oplog entry that got rolled back.\n self._stopHandles.push(self._mongoHandle._onFailover(finishIfNeedToPollQuery(\n function () {\n self._needToPollQuery();\n })));\n\n // Give _observeChanges a chance to add the new ObserveHandle to our\n // multiplexer, so that the added calls get streamed.\n Meteor.defer(finishIfNeedToPollQuery(function () {\n self._runInitialQuery();\n }));\n};\n\n_.extend(OplogObserveDriver.prototype, {\n _addPublished: function (id, doc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var fields = _.clone(doc);\n delete fields._id;\n self._published.set(id, self._sharedProjectionFn(doc));\n self._multiplexer.added(id, self._projectionFn(fields));\n\n // After adding this document, the published set might be overflowed\n // (exceeding capacity specified by limit). If so, push the maximum\n // element to the buffer, we might want to save it in memory to reduce the\n // amount of Mongo lookups in the future.\n if (self._limit && self._published.size() > self._limit) {\n // XXX in theory the size of published is no more than limit+1\n if (self._published.size() !== self._limit + 1) {\n throw new Error(\"After adding to published, \" +\n (self._published.size() - self._limit) +\n \" documents are overflowing the set\");\n }\n\n var overflowingDocId = self._published.maxElementId();\n var overflowingDoc = self._published.get(overflowingDocId);\n\n if (EJSON.equals(overflowingDocId, id)) {\n throw new Error(\"The document just added is overflowing the published set\");\n }\n\n self._published.remove(overflowingDocId);\n self._multiplexer.removed(overflowingDocId);\n self._addBuffered(overflowingDocId, overflowingDoc);\n }\n });\n },\n _removePublished: function (id) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._published.remove(id);\n self._multiplexer.removed(id);\n if (! self._limit || self._published.size() === self._limit)\n return;\n\n if (self._published.size() > self._limit)\n throw Error(\"self._published got too big\");\n\n // OK, we are publishing less than the limit. Maybe we should look in the\n // buffer to find the next element past what we were publishing before.\n\n if (!self._unpublishedBuffer.empty()) {\n // There's something in the buffer; move the first thing in it to\n // _published.\n var newDocId = self._unpublishedBuffer.minElementId();\n var newDoc = self._unpublishedBuffer.get(newDocId);\n self._removeBuffered(newDocId);\n self._addPublished(newDocId, newDoc);\n return;\n }\n\n // There's nothing in the buffer. This could mean one of a few things.\n\n // (a) We could be in the middle of re-running the query (specifically, we\n // could be in _publishNewResults). In that case, _unpublishedBuffer is\n // empty because we clear it at the beginning of _publishNewResults. In\n // this case, our caller already knows the entire answer to the query and\n // we don't need to do anything fancy here. Just return.\n if (self._phase === PHASE.QUERYING)\n return;\n\n // (b) We're pretty confident that the union of _published and\n // _unpublishedBuffer contain all documents that match selector. Because\n // _unpublishedBuffer is empty, that means we're confident that _published\n // contains all documents that match selector. So we have nothing to do.\n if (self._safeAppendToBuffer)\n return;\n\n // (c) Maybe there are other documents out there that should be in our\n // buffer. But in that case, when we emptied _unpublishedBuffer in\n // _removeBuffered, we should have called _needToPollQuery, which will\n // either put something in _unpublishedBuffer or set _safeAppendToBuffer\n // (or both), and it will put us in QUERYING for that whole time. So in\n // fact, we shouldn't be able to get here.\n\n throw new Error(\"Buffer inexplicably empty\");\n });\n },\n _changePublished: function (id, oldDoc, newDoc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._published.set(id, self._sharedProjectionFn(newDoc));\n var projectedNew = self._projectionFn(newDoc);\n var projectedOld = self._projectionFn(oldDoc);\n var changed = DiffSequence.makeChangedFields(\n projectedNew, projectedOld);\n if (!_.isEmpty(changed))\n self._multiplexer.changed(id, changed);\n });\n },\n _addBuffered: function (id, doc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._unpublishedBuffer.set(id, self._sharedProjectionFn(doc));\n\n // If something is overflowing the buffer, we just remove it from cache\n if (self._unpublishedBuffer.size() > self._limit) {\n var maxBufferedId = self._unpublishedBuffer.maxElementId();\n\n self._unpublishedBuffer.remove(maxBufferedId);\n\n // Since something matching is removed from cache (both published set and\n // buffer), set flag to false\n self._safeAppendToBuffer = false;\n }\n });\n },\n // Is called either to remove the doc completely from matching set or to move\n // it to the published set later.\n _removeBuffered: function (id) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._unpublishedBuffer.remove(id);\n // To keep the contract \"buffer is never empty in STEADY phase unless the\n // everything matching fits into published\" true, we poll everything as\n // soon as we see the buffer becoming empty.\n if (! self._unpublishedBuffer.size() && ! self._safeAppendToBuffer)\n self._needToPollQuery();\n });\n },\n // Called when a document has joined the \"Matching\" results set.\n // Takes responsibility of keeping _unpublishedBuffer in sync with _published\n // and the effect of limit enforced.\n _addMatching: function (doc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var id = doc._id;\n if (self._published.has(id))\n throw Error(\"tried to add something already published \" + id);\n if (self._limit && self._unpublishedBuffer.has(id))\n throw Error(\"tried to add something already existed in buffer \" + id);\n\n var limit = self._limit;\n var comparator = self._comparator;\n var maxPublished = (limit && self._published.size() > 0) ?\n self._published.get(self._published.maxElementId()) : null;\n var maxBuffered = (limit && self._unpublishedBuffer.size() > 0)\n ? self._unpublishedBuffer.get(self._unpublishedBuffer.maxElementId())\n : null;\n // The query is unlimited or didn't publish enough documents yet or the\n // new document would fit into published set pushing the maximum element\n // out, then we need to publish the doc.\n var toPublish = ! limit || self._published.size() < limit ||\n comparator(doc, maxPublished) < 0;\n\n // Otherwise we might need to buffer it (only in case of limited query).\n // Buffering is allowed if the buffer is not filled up yet and all\n // matching docs are either in the published set or in the buffer.\n var canAppendToBuffer = !toPublish && self._safeAppendToBuffer &&\n self._unpublishedBuffer.size() < limit;\n\n // Or if it is small enough to be safely inserted to the middle or the\n // beginning of the buffer.\n var canInsertIntoBuffer = !toPublish && maxBuffered &&\n comparator(doc, maxBuffered) <= 0;\n\n var toBuffer = canAppendToBuffer || canInsertIntoBuffer;\n\n if (toPublish) {\n self._addPublished(id, doc);\n } else if (toBuffer) {\n self._addBuffered(id, doc);\n } else {\n // dropping it and not saving to the cache\n self._safeAppendToBuffer = false;\n }\n });\n },\n // Called when a document leaves the \"Matching\" results set.\n // Takes responsibility of keeping _unpublishedBuffer in sync with _published\n // and the effect of limit enforced.\n _removeMatching: function (id) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n if (! self._published.has(id) && ! self._limit)\n throw Error(\"tried to remove something matching but not cached \" + id);\n\n if (self._published.has(id)) {\n self._removePublished(id);\n } else if (self._unpublishedBuffer.has(id)) {\n self._removeBuffered(id);\n }\n });\n },\n _handleDoc: function (id, newDoc) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var matchesNow = newDoc && self._matcher.documentMatches(newDoc).result;\n\n var publishedBefore = self._published.has(id);\n var bufferedBefore = self._limit && self._unpublishedBuffer.has(id);\n var cachedBefore = publishedBefore || bufferedBefore;\n\n if (matchesNow && !cachedBefore) {\n self._addMatching(newDoc);\n } else if (cachedBefore && !matchesNow) {\n self._removeMatching(id);\n } else if (cachedBefore && matchesNow) {\n var oldDoc = self._published.get(id);\n var comparator = self._comparator;\n var minBuffered = self._limit && self._unpublishedBuffer.size() &&\n self._unpublishedBuffer.get(self._unpublishedBuffer.minElementId());\n var maxBuffered;\n\n if (publishedBefore) {\n // Unlimited case where the document stays in published once it\n // matches or the case when we don't have enough matching docs to\n // publish or the changed but matching doc will stay in published\n // anyways.\n //\n // XXX: We rely on the emptiness of buffer. Be sure to maintain the\n // fact that buffer can't be empty if there are matching documents not\n // published. Notably, we don't want to schedule repoll and continue\n // relying on this property.\n var staysInPublished = ! self._limit ||\n self._unpublishedBuffer.size() === 0 ||\n comparator(newDoc, minBuffered) <= 0;\n\n if (staysInPublished) {\n self._changePublished(id, oldDoc, newDoc);\n } else {\n // after the change doc doesn't stay in the published, remove it\n self._removePublished(id);\n // but it can move into buffered now, check it\n maxBuffered = self._unpublishedBuffer.get(\n self._unpublishedBuffer.maxElementId());\n\n var toBuffer = self._safeAppendToBuffer ||\n (maxBuffered && comparator(newDoc, maxBuffered) <= 0);\n\n if (toBuffer) {\n self._addBuffered(id, newDoc);\n } else {\n // Throw away from both published set and buffer\n self._safeAppendToBuffer = false;\n }\n }\n } else if (bufferedBefore) {\n oldDoc = self._unpublishedBuffer.get(id);\n // remove the old version manually instead of using _removeBuffered so\n // we don't trigger the querying immediately. if we end this block\n // with the buffer empty, we will need to trigger the query poll\n // manually too.\n self._unpublishedBuffer.remove(id);\n\n var maxPublished = self._published.get(\n self._published.maxElementId());\n maxBuffered = self._unpublishedBuffer.size() &&\n self._unpublishedBuffer.get(\n self._unpublishedBuffer.maxElementId());\n\n // the buffered doc was updated, it could move to published\n var toPublish = comparator(newDoc, maxPublished) < 0;\n\n // or stays in buffer even after the change\n var staysInBuffer = (! toPublish && self._safeAppendToBuffer) ||\n (!toPublish && maxBuffered &&\n comparator(newDoc, maxBuffered) <= 0);\n\n if (toPublish) {\n self._addPublished(id, newDoc);\n } else if (staysInBuffer) {\n // stays in buffer but changes\n self._unpublishedBuffer.set(id, newDoc);\n } else {\n // Throw away from both published set and buffer\n self._safeAppendToBuffer = false;\n // Normally this check would have been done in _removeBuffered but\n // we didn't use it, so we need to do it ourself now.\n if (! self._unpublishedBuffer.size()) {\n self._needToPollQuery();\n }\n }\n } else {\n throw new Error(\"cachedBefore implies either of publishedBefore or bufferedBefore is true.\");\n }\n }\n });\n },\n _fetchModifiedDocuments: function () {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._registerPhaseChange(PHASE.FETCHING);\n // Defer, because nothing called from the oplog entry handler may yield,\n // but fetch() yields.\n Meteor.defer(finishIfNeedToPollQuery(function () {\n while (!self._stopped && !self._needToFetch.empty()) {\n if (self._phase === PHASE.QUERYING) {\n // While fetching, we decided to go into QUERYING mode, and then we\n // saw another oplog entry, so _needToFetch is not empty. But we\n // shouldn't fetch these documents until AFTER the query is done.\n break;\n }\n\n // Being in steady phase here would be surprising.\n if (self._phase !== PHASE.FETCHING)\n throw new Error(\"phase in fetchModifiedDocuments: \" + self._phase);\n\n self._currentlyFetching = self._needToFetch;\n var thisGeneration = ++self._fetchGeneration;\n self._needToFetch = new LocalCollection._IdMap;\n var waiting = 0;\n var fut = new Future;\n // This loop is safe, because _currentlyFetching will not be updated\n // during this loop (in fact, it is never mutated).\n self._currentlyFetching.forEach(function (op, id) {\n waiting++;\n self._mongoHandle._docFetcher.fetch(\n self._cursorDescription.collectionName, id, op,\n finishIfNeedToPollQuery(function (err, doc) {\n try {\n if (err) {\n Meteor._debug(\"Got exception while fetching documents\",\n err);\n // If we get an error from the fetcher (eg, trouble\n // connecting to Mongo), let's just abandon the fetch phase\n // altogether and fall back to polling. It's not like we're\n // getting live updates anyway.\n if (self._phase !== PHASE.QUERYING) {\n self._needToPollQuery();\n }\n } else if (!self._stopped && self._phase === PHASE.FETCHING\n && self._fetchGeneration === thisGeneration) {\n // We re-check the generation in case we've had an explicit\n // _pollQuery call (eg, in another fiber) which should\n // effectively cancel this round of fetches. (_pollQuery\n // increments the generation.)\n self._handleDoc(id, doc);\n }\n } finally {\n waiting--;\n // Because fetch() never calls its callback synchronously,\n // this is safe (ie, we won't call fut.return() before the\n // forEach is done).\n if (waiting === 0)\n fut.return();\n }\n }));\n });\n fut.wait();\n // Exit now if we've had a _pollQuery call (here or in another fiber).\n if (self._phase === PHASE.QUERYING)\n return;\n self._currentlyFetching = null;\n }\n // We're done fetching, so we can be steady, unless we've had a\n // _pollQuery call (here or in another fiber).\n if (self._phase !== PHASE.QUERYING)\n self._beSteady();\n }));\n });\n },\n _beSteady: function () {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._registerPhaseChange(PHASE.STEADY);\n var writes = self._writesToCommitWhenWeReachSteady;\n self._writesToCommitWhenWeReachSteady = [];\n self._multiplexer.onFlush(function () {\n _.each(writes, function (w) {\n w.committed();\n });\n });\n });\n },\n _handleOplogEntryQuerying: function (op) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._needToFetch.set(idForOp(op), op);\n });\n },\n _handleOplogEntrySteadyOrFetching: function (op) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var id = idForOp(op);\n // If we're already fetching this one, or about to, we can't optimize;\n // make sure that we fetch it again if necessary.\n if (self._phase === PHASE.FETCHING &&\n ((self._currentlyFetching && self._currentlyFetching.has(id)) ||\n self._needToFetch.has(id))) {\n self._needToFetch.set(id, op);\n return;\n }\n\n if (op.op === 'd') {\n if (self._published.has(id) ||\n (self._limit && self._unpublishedBuffer.has(id)))\n self._removeMatching(id);\n } else if (op.op === 'i') {\n if (self._published.has(id))\n throw new Error(\"insert found for already-existing ID in published\");\n if (self._unpublishedBuffer && self._unpublishedBuffer.has(id))\n throw new Error(\"insert found for already-existing ID in buffer\");\n\n // XXX what if selector yields? for now it can't but later it could\n // have $where\n if (self._matcher.documentMatches(op.o).result)\n self._addMatching(op.o);\n } else if (op.op === 'u') {\n // Is this a modifier ($set/$unset, which may require us to poll the\n // database to figure out if the whole document matches the selector) or\n // a replacement (in which case we can just directly re-evaluate the\n // selector)?\n var isReplace = !_.has(op.o, '$set') && !_.has(op.o, '$unset');\n // If this modifier modifies something inside an EJSON custom type (ie,\n // anything with EJSON$), then we can't try to use\n // LocalCollection._modify, since that just mutates the EJSON encoding,\n // not the actual object.\n var canDirectlyModifyDoc =\n !isReplace && modifierCanBeDirectlyApplied(op.o);\n\n var publishedBefore = self._published.has(id);\n var bufferedBefore = self._limit && self._unpublishedBuffer.has(id);\n\n if (isReplace) {\n self._handleDoc(id, _.extend({_id: id}, op.o));\n } else if ((publishedBefore || bufferedBefore) &&\n canDirectlyModifyDoc) {\n // Oh great, we actually know what the document is, so we can apply\n // this directly.\n var newDoc = self._published.has(id)\n ? self._published.get(id) : self._unpublishedBuffer.get(id);\n newDoc = EJSON.clone(newDoc);\n\n newDoc._id = id;\n try {\n LocalCollection._modify(newDoc, op.o);\n } catch (e) {\n if (e.name !== \"MinimongoError\")\n throw e;\n // We didn't understand the modifier. Re-fetch.\n self._needToFetch.set(id, op);\n if (self._phase === PHASE.STEADY) {\n self._fetchModifiedDocuments();\n }\n return;\n }\n self._handleDoc(id, self._sharedProjectionFn(newDoc));\n } else if (!canDirectlyModifyDoc ||\n self._matcher.canBecomeTrueByModifier(op.o) ||\n (self._sorter && self._sorter.affectedByModifier(op.o))) {\n self._needToFetch.set(id, op);\n if (self._phase === PHASE.STEADY)\n self._fetchModifiedDocuments();\n }\n } else {\n throw Error(\"XXX SURPRISING OPERATION: \" + op);\n }\n });\n },\n // Yields!\n _runInitialQuery: function () {\n var self = this;\n if (self._stopped)\n throw new Error(\"oplog stopped surprisingly early\");\n\n self._runQuery({initial: true}); // yields\n\n if (self._stopped)\n return; // can happen on queryError\n\n // Allow observeChanges calls to return. (After this, it's possible for\n // stop() to be called.)\n self._multiplexer.ready();\n\n self._doneQuerying(); // yields\n },\n\n // In various circumstances, we may just want to stop processing the oplog and\n // re-run the initial query, just as if we were a PollingObserveDriver.\n //\n // This function may not block, because it is called from an oplog entry\n // handler.\n //\n // XXX We should call this when we detect that we've been in FETCHING for \"too\n // long\".\n //\n // XXX We should call this when we detect Mongo failover (since that might\n // mean that some of the oplog entries we have processed have been rolled\n // back). The Node Mongo driver is in the middle of a bunch of huge\n // refactorings, including the way that it notifies you when primary\n // changes. Will put off implementing this until driver 1.4 is out.\n _pollQuery: function () {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n if (self._stopped)\n return;\n\n // Yay, we get to forget about all the things we thought we had to fetch.\n self._needToFetch = new LocalCollection._IdMap;\n self._currentlyFetching = null;\n ++self._fetchGeneration; // ignore any in-flight fetches\n self._registerPhaseChange(PHASE.QUERYING);\n\n // Defer so that we don't yield. We don't need finishIfNeedToPollQuery\n // here because SwitchedToQuery is not thrown in QUERYING mode.\n Meteor.defer(function () {\n self._runQuery();\n self._doneQuerying();\n });\n });\n },\n\n // Yields!\n _runQuery: function (options) {\n var self = this;\n options = options || {};\n var newResults, newBuffer;\n\n // This while loop is just to retry failures.\n while (true) {\n // If we've been stopped, we don't have to run anything any more.\n if (self._stopped)\n return;\n\n newResults = new LocalCollection._IdMap;\n newBuffer = new LocalCollection._IdMap;\n\n // Query 2x documents as the half excluded from the original query will go\n // into unpublished buffer to reduce additional Mongo lookups in cases\n // when documents are removed from the published set and need a\n // replacement.\n // XXX needs more thought on non-zero skip\n // XXX 2 is a \"magic number\" meaning there is an extra chunk of docs for\n // buffer if such is needed.\n var cursor = self._cursorForQuery({ limit: self._limit * 2 });\n try {\n cursor.forEach(function (doc, i) { // yields\n if (!self._limit || i < self._limit) {\n newResults.set(doc._id, doc);\n } else {\n newBuffer.set(doc._id, doc);\n }\n });\n break;\n } catch (e) {\n if (options.initial && typeof(e.code) === 'number') {\n // This is an error document sent to us by mongod, not a connection\n // error generated by the client. And we've never seen this query work\n // successfully. Probably it's a bad selector or something, so we\n // should NOT retry. Instead, we should halt the observe (which ends\n // up calling `stop` on us).\n self._multiplexer.queryError(e);\n return;\n }\n\n // During failover (eg) if we get an exception we should log and retry\n // instead of crashing.\n Meteor._debug(\"Got exception while polling query\", e);\n Meteor._sleepForMs(100);\n }\n }\n\n if (self._stopped)\n return;\n\n self._publishNewResults(newResults, newBuffer);\n },\n\n // Transitions to QUERYING and runs another query, or (if already in QUERYING)\n // ensures that we will query again later.\n //\n // This function may not block, because it is called from an oplog entry\n // handler. However, if we were not already in the QUERYING phase, it throws\n // an exception that is caught by the closest surrounding\n // finishIfNeedToPollQuery call; this ensures that we don't continue running\n // close that was designed for another phase inside PHASE.QUERYING.\n //\n // (It's also necessary whenever logic in this file yields to check that other\n // phases haven't put us into QUERYING mode, though; eg,\n // _fetchModifiedDocuments does this.)\n _needToPollQuery: function () {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n if (self._stopped)\n return;\n\n // If we're not already in the middle of a query, we can query now\n // (possibly pausing FETCHING).\n if (self._phase !== PHASE.QUERYING) {\n self._pollQuery();\n throw new SwitchedToQuery;\n }\n\n // We're currently in QUERYING. Set a flag to ensure that we run another\n // query when we're done.\n self._requeryWhenDoneThisQuery = true;\n });\n },\n\n // Yields!\n _doneQuerying: function () {\n var self = this;\n\n if (self._stopped)\n return;\n self._mongoHandle._oplogHandle.waitUntilCaughtUp(); // yields\n if (self._stopped)\n return;\n if (self._phase !== PHASE.QUERYING)\n throw Error(\"Phase unexpectedly \" + self._phase);\n\n Meteor._noYieldsAllowed(function () {\n if (self._requeryWhenDoneThisQuery) {\n self._requeryWhenDoneThisQuery = false;\n self._pollQuery();\n } else if (self._needToFetch.empty()) {\n self._beSteady();\n } else {\n self._fetchModifiedDocuments();\n }\n });\n },\n\n _cursorForQuery: function (optionsOverwrite) {\n var self = this;\n return Meteor._noYieldsAllowed(function () {\n // The query we run is almost the same as the cursor we are observing,\n // with a few changes. We need to read all the fields that are relevant to\n // the selector, not just the fields we are going to publish (that's the\n // \"shared\" projection). And we don't want to apply any transform in the\n // cursor, because observeChanges shouldn't use the transform.\n var options = _.clone(self._cursorDescription.options);\n\n // Allow the caller to modify the options. Useful to specify different\n // skip and limit values.\n _.extend(options, optionsOverwrite);\n\n options.fields = self._sharedProjection;\n delete options.transform;\n // We are NOT deep cloning fields or selector here, which should be OK.\n var description = new CursorDescription(\n self._cursorDescription.collectionName,\n self._cursorDescription.selector,\n options);\n return new Cursor(self._mongoHandle, description);\n });\n },\n\n\n // Replace self._published with newResults (both are IdMaps), invoking observe\n // callbacks on the multiplexer.\n // Replace self._unpublishedBuffer with newBuffer.\n //\n // XXX This is very similar to LocalCollection._diffQueryUnorderedChanges. We\n // should really: (a) Unify IdMap and OrderedDict into Unordered/OrderedDict\n // (b) Rewrite diff.js to use these classes instead of arrays and objects.\n _publishNewResults: function (newResults, newBuffer) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n\n // If the query is limited and there is a buffer, shut down so it doesn't\n // stay in a way.\n if (self._limit) {\n self._unpublishedBuffer.clear();\n }\n\n // First remove anything that's gone. Be careful not to modify\n // self._published while iterating over it.\n var idsToRemove = [];\n self._published.forEach(function (doc, id) {\n if (!newResults.has(id))\n idsToRemove.push(id);\n });\n _.each(idsToRemove, function (id) {\n self._removePublished(id);\n });\n\n // Now do adds and changes.\n // If self has a buffer and limit, the new fetched result will be\n // limited correctly as the query has sort specifier.\n newResults.forEach(function (doc, id) {\n self._handleDoc(id, doc);\n });\n\n // Sanity-check that everything we tried to put into _published ended up\n // there.\n // XXX if this is slow, remove it later\n if (self._published.size() !== newResults.size()) {\n console.error('The Mongo server and the Meteor query disagree on how ' +\n 'many documents match your query. Cursor description: ',\n self._cursorDescription);\n throw Error(\n \"The Mongo server and the Meteor query disagree on how \" +\n \"many documents match your query. Maybe it is hitting a Mongo \" +\n \"edge case? The query is: \" +\n EJSON.stringify(self._cursorDescription.selector));\n }\n self._published.forEach(function (doc, id) {\n if (!newResults.has(id))\n throw Error(\"_published has a doc that newResults doesn't; \" + id);\n });\n\n // Finally, replace the buffer\n newBuffer.forEach(function (doc, id) {\n self._addBuffered(id, doc);\n });\n\n self._safeAppendToBuffer = newBuffer.size() < self._limit;\n });\n },\n\n // This stop function is invoked from the onStop of the ObserveMultiplexer, so\n // it shouldn't actually be possible to call it until the multiplexer is\n // ready.\n //\n // It's important to check self._stopped after every call in this file that\n // can yield!\n stop: function () {\n var self = this;\n if (self._stopped)\n return;\n self._stopped = true;\n _.each(self._stopHandles, function (handle) {\n handle.stop();\n });\n\n // Note: we *don't* use multiplexer.onFlush here because this stop\n // callback is actually invoked by the multiplexer itself when it has\n // determined that there are no handles left. So nothing is actually going\n // to get flushed (and it's probably not valid to call methods on the\n // dying multiplexer).\n _.each(self._writesToCommitWhenWeReachSteady, function (w) {\n w.committed(); // maybe yields?\n });\n self._writesToCommitWhenWeReachSteady = null;\n\n // Proactively drop references to potentially big things.\n self._published = null;\n self._unpublishedBuffer = null;\n self._needToFetch = null;\n self._currentlyFetching = null;\n self._oplogEntryHandle = null;\n self._listenersHandle = null;\n\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"mongo-livedata\", \"observe-drivers-oplog\", -1);\n },\n\n _registerPhaseChange: function (phase) {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n var now = new Date;\n\n if (self._phase) {\n var timeDiff = now - self._phaseStartTime;\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"mongo-livedata\", \"time-spent-in-\" + self._phase + \"-phase\", timeDiff);\n }\n\n self._phase = phase;\n self._phaseStartTime = now;\n });\n }\n});\n\n// Does our oplog tailing code support this cursor? For now, we are being very\n// conservative and allowing only simple queries with simple options.\n// (This is a \"static method\".)\nOplogObserveDriver.cursorSupported = function (cursorDescription, matcher) {\n // First, check the options.\n var options = cursorDescription.options;\n\n // Did the user say no explicitly?\n // underscored version of the option is COMPAT with 1.2\n if (options.disableOplog || options._disableOplog)\n return false;\n\n // skip is not supported: to support it we would need to keep track of all\n // \"skipped\" documents or at least their ids.\n // limit w/o a sort specifier is not supported: current implementation needs a\n // deterministic way to order documents.\n if (options.skip || (options.limit && !options.sort)) return false;\n\n // If a fields projection option is given check if it is supported by\n // minimongo (some operators are not supported).\n if (options.fields) {\n try {\n LocalCollection._checkSupportedProjection(options.fields);\n } catch (e) {\n if (e.name === \"MinimongoError\") {\n return false;\n } else {\n throw e;\n }\n }\n }\n\n // We don't allow the following selectors:\n // - $where (not confident that we provide the same JS environment\n // as Mongo, and can yield!)\n // - $near (has \"interesting\" properties in MongoDB, like the possibility\n // of returning an ID multiple times, though even polling maybe\n // have a bug there)\n // XXX: once we support it, we would need to think more on how we\n // initialize the comparators when we create the driver.\n return !matcher.hasWhere() && !matcher.hasGeoQuery();\n};\n\nvar modifierCanBeDirectlyApplied = function (modifier) {\n return _.all(modifier, function (fields, operation) {\n return _.all(fields, function (value, field) {\n return !/EJSON\\$/.test(field);\n });\n });\n};\n\nMongoInternals.OplogObserveDriver = OplogObserveDriver;\n","// singleton\nexport const LocalCollectionDriver = new (class LocalCollectionDriver {\n constructor() {\n this.noConnCollections = Object.create(null);\n }\n\n open(name, conn) {\n if (! name) {\n return new LocalCollection;\n }\n\n if (! conn) {\n return ensureCollection(name, this.noConnCollections);\n }\n\n if (! conn._mongo_livedata_collections) {\n conn._mongo_livedata_collections = Object.create(null);\n }\n\n // XXX is there a way to keep track of a connection's collections without\n // dangling it off the connection object?\n return ensureCollection(name, conn._mongo_livedata_collections);\n }\n});\n\nfunction ensureCollection(name, collections) {\n return (name in collections)\n ? collections[name]\n : collections[name] = new LocalCollection(name);\n}\n","MongoInternals.RemoteCollectionDriver = function (\n mongo_url, options) {\n var self = this;\n self.mongo = new MongoConnection(mongo_url, options);\n};\n\n_.extend(MongoInternals.RemoteCollectionDriver.prototype, {\n open: function (name) {\n var self = this;\n var ret = {};\n _.each(\n ['find', 'findOne', 'insert', 'update', 'upsert',\n 'remove', '_ensureIndex', '_dropIndex', '_createCappedCollection',\n 'dropCollection', 'rawCollection'],\n function (m) {\n ret[m] = _.bind(self.mongo[m], self.mongo, name);\n });\n return ret;\n }\n});\n\n\n// Create the singleton RemoteCollectionDriver only on demand, so we\n// only require Mongo configuration if it's actually used (eg, not if\n// you're only trying to receive data from a remote DDP server.)\nMongoInternals.defaultRemoteCollectionDriver = _.once(function () {\n var connectionOptions = {};\n\n var mongoUrl = process.env.MONGO_URL;\n\n if (process.env.MONGO_OPLOG_URL) {\n connectionOptions.oplogUrl = process.env.MONGO_OPLOG_URL;\n }\n\n if (! mongoUrl)\n throw new Error(\"MONGO_URL must be set in environment\");\n\n return new MongoInternals.RemoteCollectionDriver(mongoUrl, connectionOptions);\n});\n","// options.connection, if given, is a LivedataClient or LivedataServer\n// XXX presently there is no way to destroy/clean up a Collection\n\n/**\n * @summary Namespace for MongoDB-related items\n * @namespace\n */\nMongo = {};\n\n/**\n * @summary Constructor for a Collection\n * @locus Anywhere\n * @instancename collection\n * @class\n * @param {String} name The name of the collection. If null, creates an unmanaged (unsynchronized) local collection.\n * @param {Object} [options]\n * @param {Object} options.connection The server connection that will manage this collection. Uses the default connection if not specified. Pass the return value of calling [`DDP.connect`](#ddp_connect) to specify a different server. Pass `null` to specify no connection. Unmanaged (`name` is null) collections cannot specify a connection.\n * @param {String} options.idGeneration The method of generating the `_id` fields of new documents in this collection. Possible values:\n\n - **`'STRING'`**: random strings\n - **`'MONGO'`**: random [`Mongo.ObjectID`](#mongo_object_id) values\n\nThe default id generation technique is `'STRING'`.\n * @param {Function} options.transform An optional transformation function. Documents will be passed through this function before being returned from `fetch` or `findOne`, and before being passed to callbacks of `observe`, `map`, `forEach`, `allow`, and `deny`. Transforms are *not* applied for the callbacks of `observeChanges` or to cursors returned from publish functions.\n * @param {Boolean} options.defineMutationMethods Set to `false` to skip setting up the mutation methods that enable insert/update/remove from client code. Default `true`.\n */\nMongo.Collection = function Collection(name, options) {\n if (!name && (name !== null)) {\n Meteor._debug(\"Warning: creating anonymous collection. It will not be \" +\n \"saved or synchronized over the network. (Pass null for \" +\n \"the collection name to turn off this warning.)\");\n name = null;\n }\n\n if (name !== null && typeof name !== \"string\") {\n throw new Error(\n \"First argument to new Mongo.Collection must be a string or null\");\n }\n\n if (options && options.methods) {\n // Backwards compatibility hack with original signature (which passed\n // \"connection\" directly instead of in options. (Connections must have a \"methods\"\n // method.)\n // XXX remove before 1.0\n options = {connection: options};\n }\n // Backwards compatibility: \"connection\" used to be called \"manager\".\n if (options && options.manager && !options.connection) {\n options.connection = options.manager;\n }\n\n options = {\n connection: undefined,\n idGeneration: 'STRING',\n transform: null,\n _driver: undefined,\n _preventAutopublish: false,\n ...options,\n };\n\n switch (options.idGeneration) {\n case 'MONGO':\n this._makeNewID = function () {\n var src = name ? DDP.randomStream('/collection/' + name) : Random.insecure;\n return new Mongo.ObjectID(src.hexString(24));\n };\n break;\n case 'STRING':\n default:\n this._makeNewID = function () {\n var src = name ? DDP.randomStream('/collection/' + name) : Random.insecure;\n return src.id();\n };\n break;\n }\n\n this._transform = LocalCollection.wrapTransform(options.transform);\n\n if (! name || options.connection === null)\n // note: nameless collections never have a connection\n this._connection = null;\n else if (options.connection)\n this._connection = options.connection;\n else if (Meteor.isClient)\n this._connection = Meteor.connection;\n else\n this._connection = Meteor.server;\n\n if (!options._driver) {\n // XXX This check assumes that webapp is loaded so that Meteor.server !==\n // null. We should fully support the case of \"want to use a Mongo-backed\n // collection from Node code without webapp\", but we don't yet.\n // #MeteorServerNull\n if (name && this._connection === Meteor.server &&\n typeof MongoInternals !== \"undefined\" &&\n MongoInternals.defaultRemoteCollectionDriver) {\n options._driver = MongoInternals.defaultRemoteCollectionDriver();\n } else {\n const { LocalCollectionDriver } =\n require(\"./local_collection_driver.js\");\n options._driver = LocalCollectionDriver;\n }\n }\n\n this._collection = options._driver.open(name, this._connection);\n this._name = name;\n this._driver = options._driver;\n\n this._maybeSetUpReplication(name, options);\n\n // XXX don't define these until allow or deny is actually used for this\n // collection. Could be hard if the security rules are only defined on the\n // server.\n if (options.defineMutationMethods !== false) {\n try {\n this._defineMutationMethods({\n useExisting: options._suppressSameNameError === true\n });\n } catch (error) {\n // Throw a more understandable error on the server for same collection name\n if (error.message === `A method named '/${name}/insert' is already defined`)\n throw new Error(`There is already a collection named \"${name}\"`);\n throw error;\n }\n }\n\n // autopublish\n if (Package.autopublish &&\n ! options._preventAutopublish &&\n this._connection &&\n this._connection.publish) {\n this._connection.publish(null, () => this.find(), {\n is_auto: true,\n });\n }\n};\n\nObject.assign(Mongo.Collection.prototype, {\n _maybeSetUpReplication(name, {\n _suppressSameNameError = false\n }) {\n const self = this;\n if (! (self._connection &&\n self._connection.registerStore)) {\n return;\n }\n\n // OK, we're going to be a slave, replicating some remote\n // database, except possibly with some temporary divergence while\n // we have unacknowledged RPC's.\n const ok = self._connection.registerStore(name, {\n // Called at the beginning of a batch of updates. batchSize is the number\n // of update calls to expect.\n //\n // XXX This interface is pretty janky. reset probably ought to go back to\n // being its own function, and callers shouldn't have to calculate\n // batchSize. The optimization of not calling pause/remove should be\n // delayed until later: the first call to update() should buffer its\n // message, and then we can either directly apply it at endUpdate time if\n // it was the only update, or do pauseObservers/apply/apply at the next\n // update() if there's another one.\n beginUpdate(batchSize, reset) {\n // pause observers so users don't see flicker when updating several\n // objects at once (including the post-reconnect reset-and-reapply\n // stage), and so that a re-sorting of a query can take advantage of the\n // full _diffQuery moved calculation instead of applying change one at a\n // time.\n if (batchSize > 1 || reset)\n self._collection.pauseObservers();\n\n if (reset)\n self._collection.remove({});\n },\n\n // Apply an update.\n // XXX better specify this interface (not in terms of a wire message)?\n update(msg) {\n var mongoId = MongoID.idParse(msg.id);\n var doc = self._collection.findOne(mongoId);\n\n // Is this a \"replace the whole doc\" message coming from the quiescence\n // of method writes to an object? (Note that 'undefined' is a valid\n // value meaning \"remove it\".)\n if (msg.msg === 'replace') {\n var replace = msg.replace;\n if (!replace) {\n if (doc)\n self._collection.remove(mongoId);\n } else if (!doc) {\n self._collection.insert(replace);\n } else {\n // XXX check that replace has no $ ops\n self._collection.update(mongoId, replace);\n }\n return;\n } else if (msg.msg === 'added') {\n if (doc) {\n throw new Error(\"Expected not to find a document already present for an add\");\n }\n self._collection.insert({ _id: mongoId, ...msg.fields });\n } else if (msg.msg === 'removed') {\n if (!doc)\n throw new Error(\"Expected to find a document already present for removed\");\n self._collection.remove(mongoId);\n } else if (msg.msg === 'changed') {\n if (!doc)\n throw new Error(\"Expected to find a document to change\");\n const keys = Object.keys(msg.fields);\n if (keys.length > 0) {\n var modifier = {};\n keys.forEach(key => {\n const value = msg.fields[key];\n if (EJSON.equals(doc[key], value)) {\n return;\n }\n if (typeof value === \"undefined\") {\n if (!modifier.$unset) {\n modifier.$unset = {};\n }\n modifier.$unset[key] = 1;\n } else {\n if (!modifier.$set) {\n modifier.$set = {};\n }\n modifier.$set[key] = value;\n }\n });\n if (Object.keys(modifier).length > 0) {\n self._collection.update(mongoId, modifier);\n }\n }\n } else {\n throw new Error(\"I don't know how to deal with this message\");\n }\n },\n\n // Called at the end of a batch of updates.\n endUpdate() {\n self._collection.resumeObservers();\n },\n\n // Called around method stub invocations to capture the original versions\n // of modified documents.\n saveOriginals() {\n self._collection.saveOriginals();\n },\n retrieveOriginals() {\n return self._collection.retrieveOriginals();\n },\n\n // Used to preserve current versions of documents across a store reset.\n getDoc(id) {\n return self.findOne(id);\n },\n\n // To be able to get back to the collection from the store.\n _getCollection() {\n return self;\n }\n });\n\n if (! ok) {\n const message = `There is already a collection named \"${name}\"`;\n if (_suppressSameNameError === true) {\n // XXX In theory we do not have to throw when `ok` is falsy. The\n // store is already defined for this collection name, but this\n // will simply be another reference to it and everything should\n // work. However, we have historically thrown an error here, so\n // for now we will skip the error only when _suppressSameNameError\n // is `true`, allowing people to opt in and give this some real\n // world testing.\n console.warn ? console.warn(message) : console.log(message);\n } else {\n throw new Error(message);\n }\n }\n },\n\n ///\n /// Main collection API\n ///\n\n _getFindSelector(args) {\n if (args.length == 0)\n return {};\n else\n return args[0];\n },\n\n _getFindOptions(args) {\n var self = this;\n if (args.length < 2) {\n return { transform: self._transform };\n } else {\n check(args[1], Match.Optional(Match.ObjectIncluding({\n fields: Match.Optional(Match.OneOf(Object, undefined)),\n sort: Match.Optional(Match.OneOf(Object, Array, Function, undefined)),\n limit: Match.Optional(Match.OneOf(Number, undefined)),\n skip: Match.Optional(Match.OneOf(Number, undefined))\n })));\n\n return {\n transform: self._transform,\n ...args[1],\n };\n }\n },\n\n /**\n * @summary Find the documents in a collection that match the selector.\n * @locus Anywhere\n * @method find\n * @memberof Mongo.Collection\n * @instance\n * @param {MongoSelector} [selector] A query describing the documents to find\n * @param {Object} [options]\n * @param {MongoSortSpecifier} options.sort Sort order (default: natural order)\n * @param {Number} options.skip Number of results to skip at the beginning\n * @param {Number} options.limit Maximum number of results to return\n * @param {MongoFieldSpecifier} options.fields Dictionary of fields to return or exclude.\n * @param {Boolean} options.reactive (Client only) Default `true`; pass `false` to disable reactivity\n * @param {Function} options.transform Overrides `transform` on the [`Collection`](#collections) for this cursor. Pass `null` to disable transformation.\n * @param {Boolean} options.disableOplog (Server only) Pass true to disable oplog-tailing on this query. This affects the way server processes calls to `observe` on this query. Disabling the oplog can be useful when working with data that updates in large batches.\n * @param {Number} options.pollingIntervalMs (Server only) When oplog is disabled (through the use of `disableOplog` or when otherwise not available), the frequency (in milliseconds) of how often to poll this query when observing on the server. Defaults to 10000ms (10 seconds).\n * @param {Number} options.pollingThrottleMs (Server only) When oplog is disabled (through the use of `disableOplog` or when otherwise not available), the minimum time (in milliseconds) to allow between re-polling when observing on the server. Increasing this will save CPU and mongo load at the expense of slower updates to users. Decreasing this is not recommended. Defaults to 50ms.\n * @param {Number} options.maxTimeMs (Server only) If set, instructs MongoDB to set a time limit for this cursor's operations. If the operation reaches the specified time limit (in milliseconds) without the having been completed, an exception will be thrown. Useful to prevent an (accidental or malicious) unoptimized query from causing a full collection scan that would disrupt other database users, at the expense of needing to handle the resulting error.\n * @param {String|Object} options.hint (Server only) Overrides MongoDB's default index selection and query optimization process. Specify an index to force its use, either by its name or index specification. You can also specify `{ $natural : 1 }` to force a forwards collection scan, or `{ $natural : -1 }` for a reverse collection scan. Setting this is only recommended for advanced users.\n * @returns {Mongo.Cursor}\n */\n find(...args) {\n // Collection.find() (return all docs) behaves differently\n // from Collection.find(undefined) (return 0 docs). so be\n // careful about the length of arguments.\n return this._collection.find(\n this._getFindSelector(args),\n this._getFindOptions(args)\n );\n },\n\n /**\n * @summary Finds the first document that matches the selector, as ordered by sort and skip options. Returns `undefined` if no matching document is found.\n * @locus Anywhere\n * @method findOne\n * @memberof Mongo.Collection\n * @instance\n * @param {MongoSelector} [selector] A query describing the documents to find\n * @param {Object} [options]\n * @param {MongoSortSpecifier} options.sort Sort order (default: natural order)\n * @param {Number} options.skip Number of results to skip at the beginning\n * @param {MongoFieldSpecifier} options.fields Dictionary of fields to return or exclude.\n * @param {Boolean} options.reactive (Client only) Default true; pass false to disable reactivity\n * @param {Function} options.transform Overrides `transform` on the [`Collection`](#collections) for this cursor. Pass `null` to disable transformation.\n * @returns {Object}\n */\n findOne(...args) {\n return this._collection.findOne(\n this._getFindSelector(args),\n this._getFindOptions(args)\n );\n }\n});\n\nObject.assign(Mongo.Collection, {\n _publishCursor(cursor, sub, collection) {\n var observeHandle = cursor.observeChanges({\n added: function (id, fields) {\n sub.added(collection, id, fields);\n },\n changed: function (id, fields) {\n sub.changed(collection, id, fields);\n },\n removed: function (id) {\n sub.removed(collection, id);\n }\n });\n\n // We don't call sub.ready() here: it gets called in livedata_server, after\n // possibly calling _publishCursor on multiple returned cursors.\n\n // register stop callback (expects lambda w/ no args).\n sub.onStop(function () {\n observeHandle.stop();\n });\n\n // return the observeHandle in case it needs to be stopped early\n return observeHandle;\n },\n\n // protect against dangerous selectors. falsey and {_id: falsey} are both\n // likely programmer error, and not what you want, particularly for destructive\n // operations. If a falsey _id is sent in, a new string _id will be\n // generated and returned; if a fallbackId is provided, it will be returned\n // instead.\n _rewriteSelector(selector, { fallbackId } = {}) {\n // shorthand -- scalars match _id\n if (LocalCollection._selectorIsId(selector))\n selector = {_id: selector};\n\n if (Array.isArray(selector)) {\n // This is consistent with the Mongo console itself; if we don't do this\n // check passing an empty array ends up selecting all items\n throw new Error(\"Mongo selector can't be an array.\");\n }\n\n if (!selector || (('_id' in selector) && !selector._id)) {\n // can't match anything\n return { _id: fallbackId || Random.id() };\n }\n\n return selector;\n }\n});\n\nObject.assign(Mongo.Collection.prototype, {\n // 'insert' immediately returns the inserted document's new _id.\n // The others return values immediately if you are in a stub, an in-memory\n // unmanaged collection, or a mongo-backed collection and you don't pass a\n // callback. 'update' and 'remove' return the number of affected\n // documents. 'upsert' returns an object with keys 'numberAffected' and, if an\n // insert happened, 'insertedId'.\n //\n // Otherwise, the semantics are exactly like other methods: they take\n // a callback as an optional last argument; if no callback is\n // provided, they block until the operation is complete, and throw an\n // exception if it fails; if a callback is provided, then they don't\n // necessarily block, and they call the callback when they finish with error and\n // result arguments. (The insert method provides the document ID as its result;\n // update and remove provide the number of affected docs as the result; upsert\n // provides an object with numberAffected and maybe insertedId.)\n //\n // On the client, blocking is impossible, so if a callback\n // isn't provided, they just return immediately and any error\n // information is lost.\n //\n // There's one more tweak. On the client, if you don't provide a\n // callback, then if there is an error, a message will be logged with\n // Meteor._debug.\n //\n // The intent (though this is actually determined by the underlying\n // drivers) is that the operations should be done synchronously, not\n // generating their result until the database has acknowledged\n // them. In the future maybe we should provide a flag to turn this\n // off.\n\n /**\n * @summary Insert a document in the collection. Returns its unique _id.\n * @locus Anywhere\n * @method insert\n * @memberof Mongo.Collection\n * @instance\n * @param {Object} doc The document to insert. May not yet have an _id attribute, in which case Meteor will generate one for you.\n * @param {Function} [callback] Optional. If present, called with an error object as the first argument and, if no error, the _id as the second.\n */\n insert(doc, callback) {\n // Make sure we were passed a document to insert\n if (!doc) {\n throw new Error(\"insert requires an argument\");\n }\n\n // Make a shallow clone of the document, preserving its prototype.\n doc = Object.create(\n Object.getPrototypeOf(doc),\n Object.getOwnPropertyDescriptors(doc)\n );\n\n if ('_id' in doc) {\n if (! doc._id ||\n ! (typeof doc._id === 'string' ||\n doc._id instanceof Mongo.ObjectID)) {\n throw new Error(\n \"Meteor requires document _id fields to be non-empty strings or ObjectIDs\");\n }\n } else {\n let generateId = true;\n\n // Don't generate the id if we're the client and the 'outermost' call\n // This optimization saves us passing both the randomSeed and the id\n // Passing both is redundant.\n if (this._isRemoteCollection()) {\n const enclosing = DDP._CurrentMethodInvocation.get();\n if (!enclosing) {\n generateId = false;\n }\n }\n\n if (generateId) {\n doc._id = this._makeNewID();\n }\n }\n\n // On inserts, always return the id that we generated; on all other\n // operations, just return the result from the collection.\n var chooseReturnValueFromCollectionResult = function (result) {\n if (doc._id) {\n return doc._id;\n }\n\n // XXX what is this for??\n // It's some iteraction between the callback to _callMutatorMethod and\n // the return value conversion\n doc._id = result;\n\n return result;\n };\n\n const wrappedCallback = wrapCallback(\n callback, chooseReturnValueFromCollectionResult);\n\n if (this._isRemoteCollection()) {\n const result = this._callMutatorMethod(\"insert\", [doc], wrappedCallback);\n return chooseReturnValueFromCollectionResult(result);\n }\n\n // it's my collection. descend into the collection object\n // and propagate any exception.\n try {\n // If the user provided a callback and the collection implements this\n // operation asynchronously, then queryRet will be undefined, and the\n // result will be returned through the callback instead.\n const result = this._collection.insert(doc, wrappedCallback);\n return chooseReturnValueFromCollectionResult(result);\n } catch (e) {\n if (callback) {\n callback(e);\n return null;\n }\n throw e;\n }\n },\n\n /**\n * @summary Modify one or more documents in the collection. Returns the number of matched documents.\n * @locus Anywhere\n * @method update\n * @memberof Mongo.Collection\n * @instance\n * @param {MongoSelector} selector Specifies which documents to modify\n * @param {MongoModifier} modifier Specifies how to modify the documents\n * @param {Object} [options]\n * @param {Boolean} options.multi True to modify all matching documents; false to only modify one of the matching documents (the default).\n * @param {Boolean} options.upsert True to insert a document if no matching documents are found.\n * @param {Function} [callback] Optional. If present, called with an error object as the first argument and, if no error, the number of affected documents as the second.\n */\n update(selector, modifier, ...optionsAndCallback) {\n const callback = popCallbackFromArgs(optionsAndCallback);\n\n // We've already popped off the callback, so we are left with an array\n // of one or zero items\n const options = { ...(optionsAndCallback[0] || null) };\n let insertedId;\n if (options && options.upsert) {\n // set `insertedId` if absent. `insertedId` is a Meteor extension.\n if (options.insertedId) {\n if (!(typeof options.insertedId === 'string' || options.insertedId instanceof Mongo.ObjectID))\n throw new Error(\"insertedId must be string or ObjectID\");\n insertedId = options.insertedId;\n } else if (!selector || !selector._id) {\n insertedId = this._makeNewID();\n options.generatedId = true;\n options.insertedId = insertedId;\n }\n }\n\n selector =\n Mongo.Collection._rewriteSelector(selector, { fallbackId: insertedId });\n\n const wrappedCallback = wrapCallback(callback);\n\n if (this._isRemoteCollection()) {\n const args = [\n selector,\n modifier,\n options\n ];\n\n return this._callMutatorMethod(\"update\", args, wrappedCallback);\n }\n\n // it's my collection. descend into the collection object\n // and propagate any exception.\n try {\n // If the user provided a callback and the collection implements this\n // operation asynchronously, then queryRet will be undefined, and the\n // result will be returned through the callback instead.\n return this._collection.update(\n selector, modifier, options, wrappedCallback);\n } catch (e) {\n if (callback) {\n callback(e);\n return null;\n }\n throw e;\n }\n },\n\n /**\n * @summary Remove documents from the collection\n * @locus Anywhere\n * @method remove\n * @memberof Mongo.Collection\n * @instance\n * @param {MongoSelector} selector Specifies which documents to remove\n * @param {Function} [callback] Optional. If present, called with an error object as its argument.\n */\n remove(selector, callback) {\n selector = Mongo.Collection._rewriteSelector(selector);\n\n const wrappedCallback = wrapCallback(callback);\n\n if (this._isRemoteCollection()) {\n return this._callMutatorMethod(\"remove\", [selector], wrappedCallback);\n }\n\n // it's my collection. descend into the collection object\n // and propagate any exception.\n try {\n // If the user provided a callback and the collection implements this\n // operation asynchronously, then queryRet will be undefined, and the\n // result will be returned through the callback instead.\n return this._collection.remove(selector, wrappedCallback);\n } catch (e) {\n if (callback) {\n callback(e);\n return null;\n }\n throw e;\n }\n },\n\n // Determine if this collection is simply a minimongo representation of a real\n // database on another server\n _isRemoteCollection() {\n // XXX see #MeteorServerNull\n return this._connection && this._connection !== Meteor.server;\n },\n\n /**\n * @summary Modify one or more documents in the collection, or insert one if no matching documents were found. Returns an object with keys `numberAffected` (the number of documents modified) and `insertedId` (the unique _id of the document that was inserted, if any).\n * @locus Anywhere\n * @method upsert\n * @memberof Mongo.Collection\n * @instance\n * @param {MongoSelector} selector Specifies which documents to modify\n * @param {MongoModifier} modifier Specifies how to modify the documents\n * @param {Object} [options]\n * @param {Boolean} options.multi True to modify all matching documents; false to only modify one of the matching documents (the default).\n * @param {Function} [callback] Optional. If present, called with an error object as the first argument and, if no error, the number of affected documents as the second.\n */\n upsert(selector, modifier, options, callback) {\n if (! callback && typeof options === \"function\") {\n callback = options;\n options = {};\n }\n\n return this.update(selector, modifier, {\n ...options,\n _returnObject: true,\n upsert: true,\n }, callback);\n },\n\n // We'll actually design an index API later. For now, we just pass through to\n // Mongo's, but make it synchronous.\n _ensureIndex(index, options) {\n var self = this;\n if (!self._collection._ensureIndex)\n throw new Error(\"Can only call _ensureIndex on server collections\");\n self._collection._ensureIndex(index, options);\n },\n\n _dropIndex(index) {\n var self = this;\n if (!self._collection._dropIndex)\n throw new Error(\"Can only call _dropIndex on server collections\");\n self._collection._dropIndex(index);\n },\n\n _dropCollection() {\n var self = this;\n if (!self._collection.dropCollection)\n throw new Error(\"Can only call _dropCollection on server collections\");\n self._collection.dropCollection();\n },\n\n _createCappedCollection(byteSize, maxDocuments) {\n var self = this;\n if (!self._collection._createCappedCollection)\n throw new Error(\"Can only call _createCappedCollection on server collections\");\n self._collection._createCappedCollection(byteSize, maxDocuments);\n },\n\n /**\n * @summary Returns the [`Collection`](http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html) object corresponding to this collection from the [npm `mongodb` driver module](https://www.npmjs.com/package/mongodb) which is wrapped by `Mongo.Collection`.\n * @locus Server\n * @memberof Mongo.Collection\n * @instance\n */\n rawCollection() {\n var self = this;\n if (! self._collection.rawCollection) {\n throw new Error(\"Can only call rawCollection on server collections\");\n }\n return self._collection.rawCollection();\n },\n\n /**\n * @summary Returns the [`Db`](http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html) object corresponding to this collection's database connection from the [npm `mongodb` driver module](https://www.npmjs.com/package/mongodb) which is wrapped by `Mongo.Collection`.\n * @locus Server\n * @memberof Mongo.Collection\n * @instance\n */\n rawDatabase() {\n var self = this;\n if (! (self._driver.mongo && self._driver.mongo.db)) {\n throw new Error(\"Can only call rawDatabase on server collections\");\n }\n return self._driver.mongo.db;\n }\n});\n\n// Convert the callback to not return a result if there is an error\nfunction wrapCallback(callback, convertResult) {\n return callback && function (error, result) {\n if (error) {\n callback(error);\n } else if (typeof convertResult === \"function\") {\n callback(error, convertResult(result));\n } else {\n callback(error, result);\n }\n };\n}\n\n/**\n * @summary Create a Mongo-style `ObjectID`. If you don't specify a `hexString`, the `ObjectID` will generated randomly (not using MongoDB's ID construction rules).\n * @locus Anywhere\n * @class\n * @param {String} [hexString] Optional. The 24-character hexadecimal contents of the ObjectID to create\n */\nMongo.ObjectID = MongoID.ObjectID;\n\n/**\n * @summary To create a cursor, use find. To access the documents in a cursor, use forEach, map, or fetch.\n * @class\n * @instanceName cursor\n */\nMongo.Cursor = LocalCollection.Cursor;\n\n/**\n * @deprecated in 0.9.1\n */\nMongo.Collection.Cursor = Mongo.Cursor;\n\n/**\n * @deprecated in 0.9.1\n */\nMongo.Collection.ObjectID = Mongo.ObjectID;\n\n/**\n * @deprecated in 0.9.1\n */\nMeteor.Collection = Mongo.Collection;\n\n// Allow deny stuff is now in the allow-deny package\nObject.assign(\n Meteor.Collection.prototype,\n AllowDeny.CollectionPrototype\n);\n\nfunction popCallbackFromArgs(args) {\n // Pull off any callback (or perhaps a 'callback' variable that was passed\n // in undefined, like how 'upsert' does it).\n if (args.length &&\n (args[args.length - 1] === undefined ||\n args[args.length - 1] instanceof Function)) {\n return args.pop();\n }\n}\n","/**\n * @summary Allows for user specified connection options\n * @example http://mongodb.github.io/node-mongodb-native/3.0/reference/connecting/connection-settings/\n * @locus Server\n * @param {Object} options User specified Mongo connection options\n */\nMongo.setConnectionOptions = function setConnectionOptions (options) {\n check(options, Object);\n Mongo._connectionOptions = options;\n};"]}