{"version":3,"sources":["meteor://💻app/packages/ddp-server/stream_server.js","meteor://💻app/packages/ddp-server/livedata_server.js","meteor://💻app/packages/ddp-server/writefence.js","meteor://💻app/packages/ddp-server/crossbar.js","meteor://💻app/packages/ddp-server/server_convenience.js"],"names":["websocketExtensions","_","once","extensions","websocketCompressionConfig","process","env","SERVER_WEBSOCKET_COMPRESSION","JSON","parse","push","Npm","require","configure","pathPrefix","__meteor_runtime_config__","ROOT_URL_PATH_PREFIX","StreamServer","self","registration_callbacks","open_sockets","prefix","RoutePolicy","declare","sockjs","serverOptions","log","heartbeat_delay","disconnect_delay","jsessionid","USE_JSESSIONID","DISABLE_WEBSOCKETS","websocket","faye_server_options","server","createServer","WebApp","httpServer","removeListener","_timeoutAdjustmentRequestCallback","installHandlers","addListener","_redirectWebsocketEndpoint","on","socket","setWebsocketTimeout","timeout","protocol","_session","recv","connection","setTimeout","send","data","write","without","TEST_METADATA","stringify","testMessageOnConnect","each","callback","Object","assign","prototype","register","all_sockets","values","forEach","event","oldHttpServerListeners","listeners","slice","removeAllListeners","newListener","request","args","arguments","url","parsedUrl","pathname","format","oldListener","apply","_objectSpread","module","link","default","v","DDPServer","Fiber","publicationStrategies","SERVER_MERGE","useCollectionView","doAccountingForCollection","NO_MERGE_NO_HISTORY","NO_MERGE","SessionDocumentView","existsIn","Set","dataByKey","Map","_SessionDocumentView","extend","getFields","ret","precedenceList","key","value","clearField","subscriptionHandle","changeCollector","get","removedValue","undefined","i","length","precedence","splice","delete","EJSON","equals","changeField","isAdd","clone","has","set","elt","find","SessionCollectionView","collectionName","sessionCallbacks","documents","callbacks","_SessionCollectionView","isEmpty","size","diff","previous","DiffSequence","diffMaps","both","bind","diffDocument","rightOnly","id","nowDV","added","leftOnly","prevDV","removed","fields","diffObjects","prev","now","changed","docView","add","changedResult","Error","err","Session","version","options","Random","initialized","inQueue","Meteor","_DoubleEndedQueue","blocked","workerRunning","cachedUnblock","_namedSubs","_universalSubs","userId","collectionViews","_isSending","_dontStartNewUniversalSubs","_pendingReady","_closeCallbacks","_socketUrl","_respondToPings","respondToPings","connectionHandle","close","onClose","fn","cb","bindEnvironment","defer","clientAddress","_clientAddress","httpHeaders","headers","msg","session","startUniversalSubs","run","heartbeatInterval","heartbeat","DDPCommon","Heartbeat","heartbeatTimeout","onTimeout","sendPing","start","Package","Facts","incrementServerFact","sendReady","subscriptionIds","subs","subscriptionId","_canSend","getPublicationStrategy","sendAdded","collection","sendChanged","sendRemoved","getSendCallbacks","getCollectionView","view","handlers","universal_publish_handlers","handler","_startSubscription","stop","_meteorSession","_deactivateAllSubscriptions","_removeSession","_printSentDDP","_debug","stringifyDDP","sendError","reason","offendingMessage","processMessage","msg_in","messageReceived","processNext","shift","unblock","onMessageHook","protocol_handlers","call","sub","name","params","Array","publish_handlers","error","DDPRateLimiter","rateLimiterInput","type","connectionId","_increment","rateLimitResult","_check","allowed","getErrorMessage","timeToReset","unsub","_stopSubscription","method","randomSeed","fence","_WriteFence","onAllCommitted","retire","methods","method_handlers","arm","setUserId","_setUserId","invocation","MethodInvocation","isSimulation","promise","Promise","resolve","reject","_CurrentWriteFence","withValue","DDP","_CurrentMethodInvocation","maybeAuditArgumentChecks","finish","payload","then","result","exception","wrapInternalException","_eachSub","f","_diffCollectionViews","beforeCVs","leftValue","rightValue","doc","_deactivate","oldNamedSubs","newSub","_recreate","_runHandler","_noYieldsAllowed","subId","Subscription","unblockHander","subName","maybeSub","_name","_removeAllDocuments","response","httpForwardedCount","parseInt","remoteAddress","forwardedFor","isString","trim","split","_handler","_subscriptionId","_params","_subscriptionHandle","_deactivated","_stopCallbacks","_documents","_ready","_idFilter","idStringify","MongoID","idParse","resultOrThenable","_CurrentPublicationInvocation","e","_isDeactivated","isThenable","_publishHandlerResult","res","isCursor","c","_publishCursor","ready","isArray","all","collectionNames","_getCollectionName","cur","_callStopCallbacks","collectionDocs","strId","onStop","ids","Server","defaultPublicationStrategy","onConnectionHook","Hook","debugPrintExceptions","_publicationStrategies","sessions","stream_server","raw_msg","_printReceivedDDP","parseDDP","_handleConnect","onConnection","setPublicationStrategy","publicationName","strategy","includes","onMessage","support","contains","SUPPORTED_DDP_VERSIONS","calculateVersion","publish","isObject","autopublish","is_auto","warned_about_autopublish","func","pop","callAsync","applyAsync","await","currentMethodInvocation","currentPublicationInvocation","makeRpcSeed","_urlForSession","sessionId","clientSupportedVersions","serverSupportedVersions","correctVersion","_calculateVersion","context","isClientSafe","originalMessage","message","details","_expectedByTest","stack","sanitizedError","description","Match","_failIfArgumentsAreNotAllChecked","Future","armed","fired","retired","outstanding_writes","before_fire_callbacks","completion_callbacks","EnvironmentVariable","beginWrite","committed","_maybeFire","onBeforeFire","armAndWait","future","wait","invokeCallback","_Crossbar","nextId","listenersByCollection","listenersByCollectionCount","factPackage","factName","_collectionForMessage","listen","trigger","record","fire","notification","listenersForCollection","callbackIds","l","_matches","ObjectID","triggerValue","_InvalidationCrossbar","DDP_DEFAULT_CONNECTION_URL","refresh"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAIA,mBAAmB,GAAGC,CAAC,CAACC,IAAF,CAAO,YAAY;AAC3C,MAAIC,UAAU,GAAG,EAAjB;AAEA,MAAIC,0BAA0B,GAAGC,OAAO,CAACC,GAAR,CAAYC,4BAAZ,GACzBC,IAAI,CAACC,KAAL,CAAWJ,OAAO,CAACC,GAAR,CAAYC,4BAAvB,CADyB,GAC8B,EAD/D;;AAEA,MAAIH,0BAAJ,EAAgC;AAC9BD,cAAU,CAACO,IAAX,CAAgBC,GAAG,CAACC,OAAJ,CAAY,oBAAZ,EAAkCC,SAAlC,CACdT,0BADc,CAAhB;AAGD;;AAED,SAAOD,UAAP;AACD,CAZyB,CAA1B;;AAcA,IAAIW,UAAU,GAAGC,yBAAyB,CAACC,oBAA1B,IAAmD,EAApE;;AAEAC,YAAY,GAAG,YAAY;AACzB,MAAIC,IAAI,G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,GAAxB,EAA6B;AACjD,aAAO,CAACzG,CAAC,CAAC2H,GAAF,CAAMmT,YAAN,EAAoBrU,GAApB,CAAD,IACLa,KAAK,CAACC,MAAN,CAAa6T,YAAb,EAA2BN,YAAY,CAACrU,GAAD,CAAvC,CADF;AAED,KAHM,CAAP;AAID;AA1IqC,CAAxC,E,CA6IA;AACA;AACA;AACA;AACA;;;AACAlB,SAAS,CAAC8V,qBAAV,GAAkC,IAAI9V,SAAS,CAAC4U,SAAd,CAAwB;AACxDK,UAAQ,EAAE;AAD8C,CAAxB,CAAlC,C;;;;;;;;;;;ACpKA,IAAIpa,OAAO,CAACC,GAAR,CAAYib,0BAAhB,EAA4C;AAC1Cxa,2BAAyB,CAACwa,0BAA1B,GACElb,OAAO,CAACC,GAAR,CAAYib,0BADd;AAED;;AAEDjR,MAAM,CAACpI,MAAP,GAAgB,IAAI8T,MAAJ,EAAhB;;AAEA1L,MAAM,CAACkR,OAAP,GAAiB,UAAUT,YAAV,EAAwB;AACvCvV,WAAS,CAAC8V,qBAAV,CAAgCR,IAAhC,CAAqCC,YAArC;AACD,CAFD,C,CAIA;AACA;;;AACA9a,CAAC,CAAC0D,IAAF,CAAO,CAAC,SAAD,EAAY,SAAZ,EAAuB,MAAvB,EAA+B,OAA/B,EAAwC,cAAxC,EAAwD,WAAxD,CAAP,EACO,UAAU0L,IAAV,EAAgB;AACd/E,QAAM,CAAC+E,IAAD,CAAN,GAAepP,CAAC,CAAC4I,IAAF,CAAOyB,MAAM,CAACpI,MAAP,CAAcmN,IAAd,CAAP,EAA4B/E,MAAM,CAACpI,MAAnC,CAAf;AACD,CAHR,E","file":"/packages/ddp-server.js","sourcesContent":["// By default, we use the permessage-deflate extension with default\n// configuration. If $SERVER_WEBSOCKET_COMPRESSION is set, then it must be valid\n// JSON. If it represents a falsey value, then we do not use permessage-deflate\n// at all; otherwise, the JSON value is used as an argument to deflate's\n// configure method; see\n// https://github.com/faye/permessage-deflate-node/blob/master/README.md\n//\n// (We do this in an _.once instead of at startup, because we don't want to\n// crash the tool during isopacket load if your JSON doesn't parse. This is only\n// a problem because the tool has to load the DDP server code just in order to\n// be a DDP client; see https://github.com/meteor/meteor/issues/3452 .)\nvar websocketExtensions = _.once(function () {\n var extensions = [];\n\n var websocketCompressionConfig = process.env.SERVER_WEBSOCKET_COMPRESSION\n ? JSON.parse(process.env.SERVER_WEBSOCKET_COMPRESSION) : {};\n if (websocketCompressionConfig) {\n extensions.push(Npm.require('permessage-deflate').configure(\n websocketCompressionConfig\n ));\n }\n\n return extensions;\n});\n\nvar pathPrefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || \"\";\n\nStreamServer = function () {\n var self = this;\n self.registration_callbacks = [];\n self.open_sockets = [];\n\n // Because we are installing directly onto WebApp.httpServer instead of using\n // WebApp.app, we have to process the path prefix ourselves.\n self.prefix = pathPrefix + '/sockjs';\n RoutePolicy.declare(self.prefix + '/', 'network');\n\n // set up sockjs\n var sockjs = Npm.require('sockjs');\n var serverOptions = {\n prefix: self.prefix,\n log: function() {},\n // this is the default, but we code it explicitly because we depend\n // on it in stream_client:HEARTBEAT_TIMEOUT\n heartbeat_delay: 45000,\n // The default disconnect_delay is 5 seconds, but if the server ends up CPU\n // bound for that much time, SockJS might not notice that the user has\n // reconnected because the timer (of disconnect_delay ms) can fire before\n // SockJS processes the new connection. Eventually we'll fix this by not\n // combining CPU-heavy processing with SockJS termination (eg a proxy which\n // converts to Unix sockets) but for now, raise the delay.\n disconnect_delay: 60 * 1000,\n // Set the USE_JSESSIONID environment variable to enable setting the\n // JSESSIONID cookie. This is useful for setting up proxies with\n // session affinity.\n jsessionid: !!process.env.USE_JSESSIONID\n };\n\n // If you know your server environment (eg, proxies) will prevent websockets\n // from ever working, set $DISABLE_WEBSOCKETS and SockJS clients (ie,\n // browsers) will not waste time attempting to use them.\n // (Your server will still have a /websocket endpoint.)\n if (process.env.DISABLE_WEBSOCKETS) {\n serverOptions.websocket = false;\n } else {\n serverOptions.faye_server_options = {\n extensions: websocketExtensions()\n };\n }\n\n self.server = sockjs.createServer(serverOptions);\n\n // Install the sockjs handlers, but we want to keep around our own particular\n // request handler that adjusts idle timeouts while we have an outstanding\n // request. This compensates for the fact that sockjs removes all listeners\n // for \"request\" to add its own.\n WebApp.httpServer.removeListener(\n 'request', WebApp._timeoutAdjustmentRequestCallback);\n self.server.installHandlers(WebApp.httpServer);\n WebApp.httpServer.addListener(\n 'request', WebApp._timeoutAdjustmentRequestCallback);\n\n // Support the /websocket endpoint\n self._redirectWebsocketEndpoint();\n\n self.server.on('connection', function (socket) {\n // sockjs sometimes passes us null instead of a socket object\n // so we need to guard against that. see:\n // https://github.com/sockjs/sockjs-node/issues/121\n // https://github.com/meteor/meteor/issues/10468\n if (!socket) return;\n\n // We want to make sure that if a client connects to us and does the initial\n // Websocket handshake but never gets to the DDP handshake, that we\n // eventually kill the socket. Once the DDP handshake happens, DDP\n // heartbeating will work. And before the Websocket handshake, the timeouts\n // we set at the server level in webapp_server.js will work. But\n // faye-websocket calls setTimeout(0) on any socket it takes over, so there\n // is an \"in between\" state where this doesn't happen. We work around this\n // by explicitly setting the socket timeout to a relatively large time here,\n // and setting it back to zero when we set up the heartbeat in\n // livedata_server.js.\n socket.setWebsocketTimeout = function (timeout) {\n if ((socket.protocol === 'websocket' ||\n socket.protocol === 'websocket-raw')\n && socket._session.recv) {\n socket._session.recv.connection.setTimeout(timeout);\n }\n };\n socket.setWebsocketTimeout(45 * 1000);\n\n socket.send = function (data) {\n socket.write(data);\n };\n socket.on('close', function () {\n self.open_sockets = _.without(self.open_sockets, socket);\n });\n self.open_sockets.push(socket);\n\n // only to send a message after connection on tests, useful for\n // socket-stream-client/server-tests.js\n if (process.env.TEST_METADATA && process.env.TEST_METADATA !== \"{}\") {\n socket.send(JSON.stringify({ testMessageOnConnect: true }));\n }\n\n // call all our callbacks when we get a new socket. they will do the\n // work of setting up handlers and such for specific messages.\n _.each(self.registration_callbacks, function (callback) {\n callback(socket);\n });\n });\n\n};\n\nObject.assign(StreamServer.prototype, {\n // call my callback when a new socket connects.\n // also call it for all current connections.\n register: function (callback) {\n var self = this;\n self.registration_callbacks.push(callback);\n _.each(self.all_sockets(), function (socket) {\n callback(socket);\n });\n },\n\n // get a list of all sockets\n all_sockets: function () {\n var self = this;\n return _.values(self.open_sockets);\n },\n\n // Redirect /websocket to /sockjs/websocket in order to not expose\n // sockjs to clients that want to use raw websockets\n _redirectWebsocketEndpoint: function() {\n var self = this;\n // Unfortunately we can't use a connect middleware here since\n // sockjs installs itself prior to all existing listeners\n // (meaning prior to any connect middlewares) so we need to take\n // an approach similar to overshadowListeners in\n // https://github.com/sockjs/sockjs-node/blob/cf820c55af6a9953e16558555a31decea554f70e/src/utils.coffee\n ['request', 'upgrade'].forEach((event) => {\n var httpServer = WebApp.httpServer;\n var oldHttpServerListeners = httpServer.listeners(event).slice(0);\n httpServer.removeAllListeners(event);\n\n // request and upgrade have different arguments passed but\n // we only care about the first one which is always request\n var newListener = function(request /*, moreArguments */) {\n // Store arguments for use within the closure below\n var args = arguments;\n\n // TODO replace with url package\n var url = Npm.require('url');\n\n // Rewrite /websocket and /websocket/ urls to /sockjs/websocket while\n // preserving query string.\n var parsedUrl = url.parse(request.url);\n if (parsedUrl.pathname === pathPrefix + '/websocket' ||\n parsedUrl.pathname === pathPrefix + '/websocket/') {\n parsedUrl.pathname = self.prefix + '/websocket';\n request.url = url.format(parsedUrl);\n }\n _.each(oldHttpServerListeners, function(oldListener) {\n oldListener.apply(httpServer, args);\n });\n };\n httpServer.addListener(event, newListener);\n });\n }\n});\n","DDPServer = {};\n\nvar Fiber = Npm.require('fibers');\n\n// Publication strategies define how we handle data from published cursors at the collection level\n// This allows someone to:\n// - Choose a trade-off between client-server bandwidth and server memory usage\n// - Implement special (non-mongo) collections like volatile message queues\nconst publicationStrategies = {\n // SERVER_MERGE is the default strategy.\n // When using this strategy, the server maintains a copy of all data a connection is subscribed to.\n // This allows us to only send deltas over multiple publications.\n SERVER_MERGE: {\n useCollectionView: true,\n doAccountingForCollection: true,\n },\n // The NO_MERGE_NO_HISTORY strategy results in the server sending all publication data\n // directly to the client. It does not remember what it has previously sent\n // to it will not trigger removed messages when a subscription is stopped.\n // This should only be chosen for special use cases like send-and-forget queues.\n NO_MERGE_NO_HISTORY: {\n useCollectionView: false,\n doAccountingForCollection: false,\n },\n // NO_MERGE is similar to NO_MERGE_NO_HISTORY but the server will remember the IDs it has\n // sent to the client so it can remove them when a subscription is stopped.\n // This strategy can be used when a collection is only used in a single publication.\n NO_MERGE: {\n useCollectionView: false,\n doAccountingForCollection: true,\n }\n};\n\nDDPServer.publicationStrategies = publicationStrategies;\n\n// This file contains classes:\n// * Session - The server's connection to a single DDP client\n// * Subscription - A single subscription for a single client\n// * Server - An entire server that may talk to > 1 client. A DDP endpoint.\n//\n// Session and Subscription are file scope. For now, until we freeze\n// the interface, Server is package scope (in the future it should be\n// exported).\n\n// Represents a single document in a SessionCollectionView\nvar SessionDocumentView = function () {\n var self = this;\n self.existsIn = new Set(); // set of subscriptionHandle\n self.dataByKey = new Map(); // key-> [ {subscriptionHandle, value} by precedence]\n};\n\nDDPServer._SessionDocumentView = SessionDocumentView;\n\n\n_.extend(SessionDocumentView.prototype, {\n\n getFields: function () {\n var self = this;\n var ret = {};\n self.dataByKey.forEach(function (precedenceList, key) {\n ret[key] = precedenceList[0].value;\n });\n return ret;\n },\n\n clearField: function (subscriptionHandle, key, changeCollector) {\n var self = this;\n // Publish API ignores _id if present in fields\n if (key === \"_id\")\n return;\n var precedenceList = self.dataByKey.get(key);\n\n // It's okay to clear fields that didn't exist. No need to throw\n // an error.\n if (!precedenceList)\n return;\n\n var removedValue = undefined;\n for (var i = 0; i < precedenceList.length; i++) {\n var precedence = precedenceList[i];\n if (precedence.subscriptionHandle === subscriptionHandle) {\n // The view's value can only change if this subscription is the one that\n // used to have precedence.\n if (i === 0)\n removedValue = precedence.value;\n precedenceList.splice(i, 1);\n break;\n }\n }\n if (precedenceList.length === 0) {\n self.dataByKey.delete(key);\n changeCollector[key] = undefined;\n } else if (removedValue !== undefined &&\n !EJSON.equals(removedValue, precedenceList[0].value)) {\n changeCollector[key] = precedenceList[0].value;\n }\n },\n\n changeField: function (subscriptionHandle, key, value,\n changeCollector, isAdd) {\n var self = this;\n // Publish API ignores _id if present in fields\n if (key === \"_id\")\n return;\n\n // Don't share state with the data passed in by the user.\n value = EJSON.clone(value);\n\n if (!self.dataByKey.has(key)) {\n self.dataByKey.set(key, [{subscriptionHandle: subscriptionHandle,\n value: value}]);\n changeCollector[key] = value;\n return;\n }\n var precedenceList = self.dataByKey.get(key);\n var elt;\n if (!isAdd) {\n elt = precedenceList.find(function (precedence) {\n return precedence.subscriptionHandle === subscriptionHandle;\n });\n }\n\n if (elt) {\n if (elt === precedenceList[0] && !EJSON.equals(value, elt.value)) {\n // this subscription is changing the value of this field.\n changeCollector[key] = value;\n }\n elt.value = value;\n } else {\n // this subscription is newly caring about this field\n precedenceList.push({subscriptionHandle: subscriptionHandle, value: value});\n }\n\n }\n});\n\n/**\n * Represents a client's view of a single collection\n * @param {String} collectionName Name of the collection it represents\n * @param {Object.} sessionCallbacks The callbacks for added, changed, removed\n * @class SessionCollectionView\n */\nvar SessionCollectionView = function (collectionName, sessionCallbacks) {\n var self = this;\n self.collectionName = collectionName;\n self.documents = new Map();\n self.callbacks = sessionCallbacks;\n};\n\nDDPServer._SessionCollectionView = SessionCollectionView;\n\n\nObject.assign(SessionCollectionView.prototype, {\n\n isEmpty: function () {\n var self = this;\n return self.documents.size === 0;\n },\n\n diff: function (previous) {\n var self = this;\n DiffSequence.diffMaps(previous.documents, self.documents, {\n both: _.bind(self.diffDocument, self),\n\n rightOnly: function (id, nowDV) {\n self.callbacks.added(self.collectionName, id, nowDV.getFields());\n },\n\n leftOnly: function (id, prevDV) {\n self.callbacks.removed(self.collectionName, id);\n }\n });\n },\n\n diffDocument: function (id, prevDV, nowDV) {\n var self = this;\n var fields = {};\n DiffSequence.diffObjects(prevDV.getFields(), nowDV.getFields(), {\n both: function (key, prev, now) {\n if (!EJSON.equals(prev, now))\n fields[key] = now;\n },\n rightOnly: function (key, now) {\n fields[key] = now;\n },\n leftOnly: function(key, prev) {\n fields[key] = undefined;\n }\n });\n self.callbacks.changed(self.collectionName, id, fields);\n },\n\n added: function (subscriptionHandle, id, fields) {\n var self = this;\n var docView = self.documents.get(id);\n var added = false;\n if (!docView) {\n added = true;\n docView = new SessionDocumentView();\n self.documents.set(id, docView);\n }\n docView.existsIn.add(subscriptionHandle);\n var changeCollector = {};\n _.each(fields, function (value, key) {\n docView.changeField(\n subscriptionHandle, key, value, changeCollector, true);\n });\n if (added)\n self.callbacks.added(self.collectionName, id, changeCollector);\n else\n self.callbacks.changed(self.collectionName, id, changeCollector);\n },\n\n changed: function (subscriptionHandle, id, changed) {\n var self = this;\n var changedResult = {};\n var docView = self.documents.get(id);\n if (!docView)\n throw new Error(\"Could not find element with id \" + id + \" to change\");\n _.each(changed, function (value, key) {\n if (value === undefined)\n docView.clearField(subscriptionHandle, key, changedResult);\n else\n docView.changeField(subscriptionHandle, key, value, changedResult);\n });\n self.callbacks.changed(self.collectionName, id, changedResult);\n },\n\n removed: function (subscriptionHandle, id) {\n var self = this;\n var docView = self.documents.get(id);\n if (!docView) {\n var err = new Error(\"Removed nonexistent document \" + id);\n throw err;\n }\n docView.existsIn.delete(subscriptionHandle);\n if (docView.existsIn.size === 0) {\n // it is gone from everyone\n self.callbacks.removed(self.collectionName, id);\n self.documents.delete(id);\n } else {\n var changed = {};\n // remove this subscription from every precedence list\n // and record the changes\n docView.dataByKey.forEach(function (precedenceList, key) {\n docView.clearField(subscriptionHandle, key, changed);\n });\n\n self.callbacks.changed(self.collectionName, id, changed);\n }\n }\n});\n\n/******************************************************************************/\n/* Session */\n/******************************************************************************/\n\nvar Session = function (server, version, socket, options) {\n var self = this;\n self.id = Random.id();\n\n self.server = server;\n self.version = version;\n\n self.initialized = false;\n self.socket = socket;\n\n // Set to null when the session is destroyed. Multiple places below\n // use this to determine if the session is alive or not.\n self.inQueue = new Meteor._DoubleEndedQueue();\n\n self.blocked = false;\n self.workerRunning = false;\n\n self.cachedUnblock = null;\n\n // Sub objects for active subscriptions\n self._namedSubs = new Map();\n self._universalSubs = [];\n\n self.userId = null;\n\n self.collectionViews = new Map();\n\n // Set this to false to not send messages when collectionViews are\n // modified. This is done when rerunning subs in _setUserId and those messages\n // are calculated via a diff instead.\n self._isSending = true;\n\n // If this is true, don't start a newly-created universal publisher on this\n // session. The session will take care of starting it when appropriate.\n self._dontStartNewUniversalSubs = false;\n\n // When we are rerunning subscriptions, any ready messages\n // we want to buffer up for when we are done rerunning subscriptions\n self._pendingReady = [];\n\n // List of callbacks to call when this connection is closed.\n self._closeCallbacks = [];\n\n\n // XXX HACK: If a sockjs connection, save off the URL. This is\n // temporary and will go away in the near future.\n self._socketUrl = socket.url;\n\n // Allow tests to disable responding to pings.\n self._respondToPings = options.respondToPings;\n\n // This object is the public interface to the session. In the public\n // API, it is called the `connection` object. Internally we call it\n // a `connectionHandle` to avoid ambiguity.\n self.connectionHandle = {\n id: self.id,\n close: function () {\n self.close();\n },\n onClose: function (fn) {\n var cb = Meteor.bindEnvironment(fn, \"connection onClose callback\");\n if (self.inQueue) {\n self._closeCallbacks.push(cb);\n } else {\n // if we're already closed, call the callback.\n Meteor.defer(cb);\n }\n },\n clientAddress: self._clientAddress(),\n httpHeaders: self.socket.headers\n };\n\n self.send({ msg: 'connected', session: self.id });\n\n // On initial connect, spin up all the universal publishers.\n Fiber(function () {\n self.startUniversalSubs();\n }).run();\n\n if (version !== 'pre1' && options.heartbeatInterval !== 0) {\n // We no longer need the low level timeout because we have heartbeats.\n socket.setWebsocketTimeout(0);\n\n self.heartbeat = new DDPCommon.Heartbeat({\n heartbeatInterval: options.heartbeatInterval,\n heartbeatTimeout: options.heartbeatTimeout,\n onTimeout: function () {\n self.close();\n },\n sendPing: function () {\n self.send({msg: 'ping'});\n }\n });\n self.heartbeat.start();\n }\n\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"livedata\", \"sessions\", 1);\n};\n\nObject.assign(Session.prototype, {\n\n sendReady: function (subscriptionIds) {\n var self = this;\n if (self._isSending)\n self.send({msg: \"ready\", subs: subscriptionIds});\n else {\n _.each(subscriptionIds, function (subscriptionId) {\n self._pendingReady.push(subscriptionId);\n });\n }\n },\n\n _canSend(collectionName) {\n return this._isSending || !this.server.getPublicationStrategy(collectionName).useCollectionView;\n },\n\n\n sendAdded(collectionName, id, fields) {\n if (this._canSend(collectionName))\n this.send({msg: \"added\", collection: collectionName, id, fields});\n },\n\n sendChanged(collectionName, id, fields) {\n if (_.isEmpty(fields))\n return;\n\n if (this._canSend(collectionName)) {\n this.send({\n msg: \"changed\",\n collection: collectionName,\n id,\n fields\n });\n }\n },\n\n sendRemoved(collectionName, id) {\n if (this._canSend(collectionName))\n this.send({msg: \"removed\", collection: collectionName, id});\n },\n\n getSendCallbacks: function () {\n var self = this;\n return {\n added: _.bind(self.sendAdded, self),\n changed: _.bind(self.sendChanged, self),\n removed: _.bind(self.sendRemoved, self)\n };\n },\n\n getCollectionView: function (collectionName) {\n var self = this;\n var ret = self.collectionViews.get(collectionName);\n if (!ret) {\n ret = new SessionCollectionView(collectionName,\n self.getSendCallbacks());\n self.collectionViews.set(collectionName, ret);\n }\n return ret;\n },\n\n added(subscriptionHandle, collectionName, id, fields) {\n if (this.server.getPublicationStrategy(collectionName).useCollectionView) {\n const view = this.getCollectionView(collectionName);\n view.added(subscriptionHandle, id, fields);\n } else {\n this.sendAdded(collectionName, id, fields);\n }\n },\n\n removed(subscriptionHandle, collectionName, id) {\n if (this.server.getPublicationStrategy(collectionName).useCollectionView) {\n const view = this.getCollectionView(collectionName);\n view.removed(subscriptionHandle, id);\n if (view.isEmpty()) {\n this.collectionViews.delete(collectionName);\n }\n } else {\n this.sendRemoved(collectionName, id);\n }\n },\n\n changed(subscriptionHandle, collectionName, id, fields) {\n if (this.server.getPublicationStrategy(collectionName).useCollectionView) {\n const view = this.getCollectionView(collectionName);\n view.changed(subscriptionHandle, id, fields);\n } else {\n this.sendChanged(collectionName, id, fields);\n }\n },\n\n startUniversalSubs: function () {\n var self = this;\n // Make a shallow copy of the set of universal handlers and start them. If\n // additional universal publishers start while we're running them (due to\n // yielding), they will run separately as part of Server.publish.\n var handlers = _.clone(self.server.universal_publish_handlers);\n _.each(handlers, function (handler) {\n self._startSubscription(handler);\n });\n },\n\n // Destroy this session and unregister it at the server.\n close: function () {\n var self = this;\n\n // Destroy this session, even if it's not registered at the\n // server. Stop all processing and tear everything down. If a socket\n // was attached, close it.\n\n // Already destroyed.\n if (! self.inQueue)\n return;\n\n // Drop the merge box data immediately.\n self.inQueue = null;\n self.collectionViews = new Map();\n\n if (self.heartbeat) {\n self.heartbeat.stop();\n self.heartbeat = null;\n }\n\n if (self.socket) {\n self.socket.close();\n self.socket._meteorSession = null;\n }\n\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"livedata\", \"sessions\", -1);\n\n Meteor.defer(function () {\n // Stop callbacks can yield, so we defer this on close.\n // sub._isDeactivated() detects that we set inQueue to null and\n // treats it as semi-deactivated (it will ignore incoming callbacks, etc).\n self._deactivateAllSubscriptions();\n\n // Defer calling the close callbacks, so that the caller closing\n // the session isn't waiting for all the callbacks to complete.\n _.each(self._closeCallbacks, function (callback) {\n callback();\n });\n });\n\n // Unregister the session.\n self.server._removeSession(self);\n },\n\n // Send a message (doing nothing if no socket is connected right now).\n // It should be a JSON object (it will be stringified).\n send: function (msg) {\n var self = this;\n if (self.socket) {\n if (Meteor._printSentDDP)\n Meteor._debug(\"Sent DDP\", DDPCommon.stringifyDDP(msg));\n self.socket.send(DDPCommon.stringifyDDP(msg));\n }\n },\n\n // Send a connection error.\n sendError: function (reason, offendingMessage) {\n var self = this;\n var msg = {msg: 'error', reason: reason};\n if (offendingMessage)\n msg.offendingMessage = offendingMessage;\n self.send(msg);\n },\n\n // Process 'msg' as an incoming message. As a guard against\n // race conditions during reconnection, ignore the message if\n // 'socket' is not the currently connected socket.\n //\n // We run the messages from the client one at a time, in the order\n // given by the client. The message handler is passed an idempotent\n // function 'unblock' which it may call to allow other messages to\n // begin running in parallel in another fiber (for example, a method\n // that wants to yield). Otherwise, it is automatically unblocked\n // when it returns.\n //\n // Actually, we don't have to 'totally order' the messages in this\n // way, but it's the easiest thing that's correct. (unsub needs to\n // be ordered against sub, methods need to be ordered against each\n // other).\n processMessage: function (msg_in) {\n var self = this;\n if (!self.inQueue) // we have been destroyed.\n return;\n\n // Respond to ping and pong messages immediately without queuing.\n // If the negotiated DDP version is \"pre1\" which didn't support\n // pings, preserve the \"pre1\" behavior of responding with a \"bad\n // request\" for the unknown messages.\n //\n // Fibers are needed because heartbeats use Meteor.setTimeout, which\n // needs a Fiber. We could actually use regular setTimeout and avoid\n // these new fibers, but it is easier to just make everything use\n // Meteor.setTimeout and not think too hard.\n //\n // Any message counts as receiving a pong, as it demonstrates that\n // the client is still alive.\n if (self.heartbeat) {\n Fiber(function () {\n self.heartbeat.messageReceived();\n }).run();\n }\n\n if (self.version !== 'pre1' && msg_in.msg === 'ping') {\n if (self._respondToPings)\n self.send({msg: \"pong\", id: msg_in.id});\n return;\n }\n if (self.version !== 'pre1' && msg_in.msg === 'pong') {\n // Since everything is a pong, there is nothing to do\n return;\n }\n\n self.inQueue.push(msg_in);\n if (self.workerRunning)\n return;\n self.workerRunning = true;\n\n var processNext = function () {\n var msg = self.inQueue && self.inQueue.shift();\n if (!msg) {\n self.workerRunning = false;\n return;\n }\n\n Fiber(function () {\n var blocked = true;\n\n var unblock = function () {\n if (!blocked)\n return; // idempotent\n blocked = false;\n processNext();\n };\n\n self.server.onMessageHook.each(function (callback) {\n callback(msg, self);\n return true;\n });\n\n if (_.has(self.protocol_handlers, msg.msg))\n self.protocol_handlers[msg.msg].call(self, msg, unblock);\n else\n self.sendError('Bad request', msg);\n unblock(); // in case the handler didn't already do it\n }).run();\n };\n\n processNext();\n },\n\n protocol_handlers: {\n sub: function (msg, unblock) {\n var self = this;\n\n // cacheUnblock temporarly, so we can capture it later\n // we will use unblock in current eventLoop, so this is safe\n self.cachedUnblock = unblock;\n\n // reject malformed messages\n if (typeof (msg.id) !== \"string\" ||\n typeof (msg.name) !== \"string\" ||\n (('params' in msg) && !(msg.params instanceof Array))) {\n self.sendError(\"Malformed subscription\", msg);\n return;\n }\n\n if (!self.server.publish_handlers[msg.name]) {\n self.send({\n msg: 'nosub', id: msg.id,\n error: new Meteor.Error(404, `Subscription '${msg.name}' not found`)});\n return;\n }\n\n if (self._namedSubs.has(msg.id))\n // subs are idempotent, or rather, they are ignored if a sub\n // with that id already exists. this is important during\n // reconnect.\n return;\n\n // XXX It'd be much better if we had generic hooks where any package can\n // hook into subscription handling, but in the mean while we special case\n // ddp-rate-limiter package. This is also done for weak requirements to\n // add the ddp-rate-limiter package in case we don't have Accounts. A\n // user trying to use the ddp-rate-limiter must explicitly require it.\n if (Package['ddp-rate-limiter']) {\n var DDPRateLimiter = Package['ddp-rate-limiter'].DDPRateLimiter;\n var rateLimiterInput = {\n userId: self.userId,\n clientAddress: self.connectionHandle.clientAddress,\n type: \"subscription\",\n name: msg.name,\n connectionId: self.id\n };\n\n DDPRateLimiter._increment(rateLimiterInput);\n var rateLimitResult = DDPRateLimiter._check(rateLimiterInput);\n if (!rateLimitResult.allowed) {\n self.send({\n msg: 'nosub', id: msg.id,\n error: new Meteor.Error(\n 'too-many-requests',\n DDPRateLimiter.getErrorMessage(rateLimitResult),\n {timeToReset: rateLimitResult.timeToReset})\n });\n return;\n }\n }\n\n var handler = self.server.publish_handlers[msg.name];\n\n self._startSubscription(handler, msg.id, msg.params, msg.name);\n\n // cleaning cached unblock\n self.cachedUnblock = null;\n },\n\n unsub: function (msg) {\n var self = this;\n\n self._stopSubscription(msg.id);\n },\n\n method: function (msg, unblock) {\n var self = this;\n\n // Reject malformed messages.\n // For now, we silently ignore unknown attributes,\n // for forwards compatibility.\n if (typeof (msg.id) !== \"string\" ||\n typeof (msg.method) !== \"string\" ||\n (('params' in msg) && !(msg.params instanceof Array)) ||\n (('randomSeed' in msg) && (typeof msg.randomSeed !== \"string\"))) {\n self.sendError(\"Malformed method invocation\", msg);\n return;\n }\n\n var randomSeed = msg.randomSeed || null;\n\n // Set up to mark the method as satisfied once all observers\n // (and subscriptions) have reacted to any writes that were\n // done.\n var fence = new DDPServer._WriteFence;\n fence.onAllCommitted(function () {\n // Retire the fence so that future writes are allowed.\n // This means that callbacks like timers are free to use\n // the fence, and if they fire before it's armed (for\n // example, because the method waits for them) their\n // writes will be included in the fence.\n fence.retire();\n self.send({\n msg: 'updated', methods: [msg.id]});\n });\n\n // Find the handler\n var handler = self.server.method_handlers[msg.method];\n if (!handler) {\n self.send({\n msg: 'result', id: msg.id,\n error: new Meteor.Error(404, `Method '${msg.method}' not found`)});\n fence.arm();\n return;\n }\n\n var setUserId = function(userId) {\n self._setUserId(userId);\n };\n\n var invocation = new DDPCommon.MethodInvocation({\n isSimulation: false,\n userId: self.userId,\n setUserId: setUserId,\n unblock: unblock,\n connection: self.connectionHandle,\n randomSeed: randomSeed\n });\n\n const promise = new Promise((resolve, reject) => {\n // XXX It'd be better if we could hook into method handlers better but\n // for now, we need to check if the ddp-rate-limiter exists since we\n // have a weak requirement for the ddp-rate-limiter package to be added\n // to our application.\n if (Package['ddp-rate-limiter']) {\n var DDPRateLimiter = Package['ddp-rate-limiter'].DDPRateLimiter;\n var rateLimiterInput = {\n userId: self.userId,\n clientAddress: self.connectionHandle.clientAddress,\n type: \"method\",\n name: msg.method,\n connectionId: self.id\n };\n DDPRateLimiter._increment(rateLimiterInput);\n var rateLimitResult = DDPRateLimiter._check(rateLimiterInput)\n if (!rateLimitResult.allowed) {\n reject(new Meteor.Error(\n \"too-many-requests\",\n DDPRateLimiter.getErrorMessage(rateLimitResult),\n {timeToReset: rateLimitResult.timeToReset}\n ));\n return;\n }\n }\n\n resolve(DDPServer._CurrentWriteFence.withValue(\n fence,\n () => DDP._CurrentMethodInvocation.withValue(\n invocation,\n () => maybeAuditArgumentChecks(\n handler, invocation, msg.params,\n \"call to '\" + msg.method + \"'\"\n )\n )\n ));\n });\n\n function finish() {\n fence.arm();\n unblock();\n }\n\n const payload = {\n msg: \"result\",\n id: msg.id\n };\n\n promise.then((result) => {\n finish();\n if (result !== undefined) {\n payload.result = result;\n }\n self.send(payload);\n }, (exception) => {\n finish();\n payload.error = wrapInternalException(\n exception,\n `while invoking method '${msg.method}'`\n );\n self.send(payload);\n });\n }\n },\n\n _eachSub: function (f) {\n var self = this;\n self._namedSubs.forEach(f);\n self._universalSubs.forEach(f);\n },\n\n _diffCollectionViews: function (beforeCVs) {\n var self = this;\n DiffSequence.diffMaps(beforeCVs, self.collectionViews, {\n both: function (collectionName, leftValue, rightValue) {\n rightValue.diff(leftValue);\n },\n rightOnly: function (collectionName, rightValue) {\n rightValue.documents.forEach(function (docView, id) {\n self.sendAdded(collectionName, id, docView.getFields());\n });\n },\n leftOnly: function (collectionName, leftValue) {\n leftValue.documents.forEach(function (doc, id) {\n self.sendRemoved(collectionName, id);\n });\n }\n });\n },\n\n // Sets the current user id in all appropriate contexts and reruns\n // all subscriptions\n _setUserId: function(userId) {\n var self = this;\n\n if (userId !== null && typeof userId !== \"string\")\n throw new Error(\"setUserId must be called on string or null, not \" +\n typeof userId);\n\n // Prevent newly-created universal subscriptions from being added to our\n // session. They will be found below when we call startUniversalSubs.\n //\n // (We don't have to worry about named subscriptions, because we only add\n // them when we process a 'sub' message. We are currently processing a\n // 'method' message, and the method did not unblock, because it is illegal\n // to call setUserId after unblock. Thus we cannot be concurrently adding a\n // new named subscription).\n self._dontStartNewUniversalSubs = true;\n\n // Prevent current subs from updating our collectionViews and call their\n // stop callbacks. This may yield.\n self._eachSub(function (sub) {\n sub._deactivate();\n });\n\n // All subs should now be deactivated. Stop sending messages to the client,\n // save the state of the published collections, reset to an empty view, and\n // update the userId.\n self._isSending = false;\n var beforeCVs = self.collectionViews;\n self.collectionViews = new Map();\n self.userId = userId;\n\n // _setUserId is normally called from a Meteor method with\n // DDP._CurrentMethodInvocation set. But DDP._CurrentMethodInvocation is not\n // expected to be set inside a publish function, so we temporary unset it.\n // Inside a publish function DDP._CurrentPublicationInvocation is set.\n DDP._CurrentMethodInvocation.withValue(undefined, function () {\n // Save the old named subs, and reset to having no subscriptions.\n var oldNamedSubs = self._namedSubs;\n self._namedSubs = new Map();\n self._universalSubs = [];\n\n oldNamedSubs.forEach(function (sub, subscriptionId) {\n var newSub = sub._recreate();\n self._namedSubs.set(subscriptionId, newSub);\n // nb: if the handler throws or calls this.error(), it will in fact\n // immediately send its 'nosub'. This is OK, though.\n newSub._runHandler();\n });\n\n // Allow newly-created universal subs to be started on our connection in\n // parallel with the ones we're spinning up here, and spin up universal\n // subs.\n self._dontStartNewUniversalSubs = false;\n self.startUniversalSubs();\n });\n\n // Start sending messages again, beginning with the diff from the previous\n // state of the world to the current state. No yields are allowed during\n // this diff, so that other changes cannot interleave.\n Meteor._noYieldsAllowed(function () {\n self._isSending = true;\n self._diffCollectionViews(beforeCVs);\n if (!_.isEmpty(self._pendingReady)) {\n self.sendReady(self._pendingReady);\n self._pendingReady = [];\n }\n });\n },\n\n _startSubscription: function (handler, subId, params, name) {\n var self = this;\n\n var sub = new Subscription(\n self, handler, subId, params, name);\n\n let unblockHander = self.cachedUnblock;\n // _startSubscription may call from a lot places\n // so cachedUnblock might be null in somecases\n // assign the cachedUnblock\n sub.unblock = unblockHander || (() => {});\n\n if (subId)\n self._namedSubs.set(subId, sub);\n else\n self._universalSubs.push(sub);\n\n sub._runHandler();\n },\n\n // Tear down specified subscription\n _stopSubscription: function (subId, error) {\n var self = this;\n\n var subName = null;\n if (subId) {\n var maybeSub = self._namedSubs.get(subId);\n if (maybeSub) {\n subName = maybeSub._name;\n maybeSub._removeAllDocuments();\n maybeSub._deactivate();\n self._namedSubs.delete(subId);\n }\n }\n\n var response = {msg: 'nosub', id: subId};\n\n if (error) {\n response.error = wrapInternalException(\n error,\n subName ? (\"from sub \" + subName + \" id \" + subId)\n : (\"from sub id \" + subId));\n }\n\n self.send(response);\n },\n\n // Tear down all subscriptions. Note that this does NOT send removed or nosub\n // messages, since we assume the client is gone.\n _deactivateAllSubscriptions: function () {\n var self = this;\n\n self._namedSubs.forEach(function (sub, id) {\n sub._deactivate();\n });\n self._namedSubs = new Map();\n\n self._universalSubs.forEach(function (sub) {\n sub._deactivate();\n });\n self._universalSubs = [];\n },\n\n // Determine the remote client's IP address, based on the\n // HTTP_FORWARDED_COUNT environment variable representing how many\n // proxies the server is behind.\n _clientAddress: function () {\n var self = this;\n\n // For the reported client address for a connection to be correct,\n // the developer must set the HTTP_FORWARDED_COUNT environment\n // variable to an integer representing the number of hops they\n // expect in the `x-forwarded-for` header. E.g., set to \"1\" if the\n // server is behind one proxy.\n //\n // This could be computed once at startup instead of every time.\n var httpForwardedCount = parseInt(process.env['HTTP_FORWARDED_COUNT']) || 0;\n\n if (httpForwardedCount === 0)\n return self.socket.remoteAddress;\n\n var forwardedFor = self.socket.headers[\"x-forwarded-for\"];\n if (! _.isString(forwardedFor))\n return null;\n forwardedFor = forwardedFor.trim().split(/\\s*,\\s*/);\n\n // Typically the first value in the `x-forwarded-for` header is\n // the original IP address of the client connecting to the first\n // proxy. However, the end user can easily spoof the header, in\n // which case the first value(s) will be the fake IP address from\n // the user pretending to be a proxy reporting the original IP\n // address value. By counting HTTP_FORWARDED_COUNT back from the\n // end of the list, we ensure that we get the IP address being\n // reported by *our* first proxy.\n\n if (httpForwardedCount < 0 || httpForwardedCount > forwardedFor.length)\n return null;\n\n return forwardedFor[forwardedFor.length - httpForwardedCount];\n }\n});\n\n/******************************************************************************/\n/* Subscription */\n/******************************************************************************/\n\n// Ctor for a sub handle: the input to each publish function\n\n// Instance name is this because it's usually referred to as this inside a\n// publish\n/**\n * @summary The server's side of a subscription\n * @class Subscription\n * @instanceName this\n * @showInstanceName true\n */\nvar Subscription = function (\n session, handler, subscriptionId, params, name) {\n var self = this;\n self._session = session; // type is Session\n\n /**\n * @summary Access inside the publish function. The incoming [connection](#meteor_onconnection) for this subscription.\n * @locus Server\n * @name connection\n * @memberOf Subscription\n * @instance\n */\n self.connection = session.connectionHandle; // public API object\n\n self._handler = handler;\n\n // My subscription ID (generated by client, undefined for universal subs).\n self._subscriptionId = subscriptionId;\n // Undefined for universal subs\n self._name = name;\n\n self._params = params || [];\n\n // Only named subscriptions have IDs, but we need some sort of string\n // internally to keep track of all subscriptions inside\n // SessionDocumentViews. We use this subscriptionHandle for that.\n if (self._subscriptionId) {\n self._subscriptionHandle = 'N' + self._subscriptionId;\n } else {\n self._subscriptionHandle = 'U' + Random.id();\n }\n\n // Has _deactivate been called?\n self._deactivated = false;\n\n // Stop callbacks to g/c this sub. called w/ zero arguments.\n self._stopCallbacks = [];\n\n // The set of (collection, documentid) that this subscription has\n // an opinion about.\n self._documents = new Map();\n\n // Remember if we are ready.\n self._ready = false;\n\n // Part of the public API: the user of this sub.\n\n /**\n * @summary Access inside the publish function. The id of the logged-in user, or `null` if no user is logged in.\n * @locus Server\n * @memberOf Subscription\n * @name userId\n * @instance\n */\n self.userId = session.userId;\n\n // For now, the id filter is going to default to\n // the to/from DDP methods on MongoID, to\n // specifically deal with mongo/minimongo ObjectIds.\n\n // Later, you will be able to make this be \"raw\"\n // if you want to publish a collection that you know\n // just has strings for keys and no funny business, to\n // a DDP consumer that isn't minimongo.\n\n self._idFilter = {\n idStringify: MongoID.idStringify,\n idParse: MongoID.idParse\n };\n\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"livedata\", \"subscriptions\", 1);\n};\n\nObject.assign(Subscription.prototype, {\n _runHandler: function() {\n // XXX should we unblock() here? Either before running the publish\n // function, or before running _publishCursor.\n //\n // Right now, each publish function blocks all future publishes and\n // methods waiting on data from Mongo (or whatever else the function\n // blocks on). This probably slows page load in common cases.\n\n if (!this.unblock) {\n this.unblock = () => {};\n }\n\n const self = this;\n let resultOrThenable = null;\n try {\n resultOrThenable = DDP._CurrentPublicationInvocation.withValue(self, () =>\n maybeAuditArgumentChecks(\n self._handler,\n self,\n EJSON.clone(self._params),\n // It's OK that this would look weird for universal subscriptions,\n // because they have no arguments so there can never be an\n // audit-argument-checks failure.\n \"publisher '\" + self._name + \"'\"\n )\n );\n } catch (e) {\n self.error(e);\n return;\n }\n\n // Did the handler call this.error or this.stop?\n if (self._isDeactivated()) return;\n\n // Both conventional and async publish handler functions are supported.\n // If an object is returned with a then() function, it is either a promise\n // or thenable and will be resolved asynchronously.\n const isThenable =\n resultOrThenable && typeof resultOrThenable.then === 'function';\n if (isThenable) {\n Promise.resolve(resultOrThenable).then(\n (...args) => self._publishHandlerResult.bind(self)(...args),\n e => self.error(e)\n );\n } else {\n self._publishHandlerResult(resultOrThenable);\n }\n },\n\n _publishHandlerResult: function (res) {\n // SPECIAL CASE: Instead of writing their own callbacks that invoke\n // this.added/changed/ready/etc, the user can just return a collection\n // cursor or array of cursors from the publish function; we call their\n // _publishCursor method which starts observing the cursor and publishes the\n // results. Note that _publishCursor does NOT call ready().\n //\n // XXX This uses an undocumented interface which only the Mongo cursor\n // interface publishes. Should we make this interface public and encourage\n // users to implement it themselves? Arguably, it's unnecessary; users can\n // already write their own functions like\n // var publishMyReactiveThingy = function (name, handler) {\n // Meteor.publish(name, function () {\n // var reactiveThingy = handler();\n // reactiveThingy.publishMe();\n // });\n // };\n\n var self = this;\n var isCursor = function (c) {\n return c && c._publishCursor;\n };\n if (isCursor(res)) {\n try {\n res._publishCursor(self);\n } catch (e) {\n self.error(e);\n return;\n }\n // _publishCursor only returns after the initial added callbacks have run.\n // mark subscription as ready.\n self.ready();\n } else if (_.isArray(res)) {\n // Check all the elements are cursors\n if (! _.all(res, isCursor)) {\n self.error(new Error(\"Publish function returned an array of non-Cursors\"));\n return;\n }\n // Find duplicate collection names\n // XXX we should support overlapping cursors, but that would require the\n // merge box to allow overlap within a subscription\n var collectionNames = {};\n for (var i = 0; i < res.length; ++i) {\n var collectionName = res[i]._getCollectionName();\n if (_.has(collectionNames, collectionName)) {\n self.error(new Error(\n \"Publish function returned multiple cursors for collection \" +\n collectionName));\n return;\n }\n collectionNames[collectionName] = true;\n };\n\n try {\n _.each(res, function (cur) {\n cur._publishCursor(self);\n });\n } catch (e) {\n self.error(e);\n return;\n }\n self.ready();\n } else if (res) {\n // Truthy values other than cursors or arrays are probably a\n // user mistake (possible returning a Mongo document via, say,\n // `coll.findOne()`).\n self.error(new Error(\"Publish function can only return a Cursor or \"\n + \"an array of Cursors\"));\n }\n },\n\n // This calls all stop callbacks and prevents the handler from updating any\n // SessionCollectionViews further. It's used when the user unsubscribes or\n // disconnects, as well as during setUserId re-runs. It does *NOT* send\n // removed messages for the published objects; if that is necessary, call\n // _removeAllDocuments first.\n _deactivate: function() {\n var self = this;\n if (self._deactivated)\n return;\n self._deactivated = true;\n self._callStopCallbacks();\n Package['facts-base'] && Package['facts-base'].Facts.incrementServerFact(\n \"livedata\", \"subscriptions\", -1);\n },\n\n _callStopCallbacks: function () {\n var self = this;\n // Tell listeners, so they can clean up\n var callbacks = self._stopCallbacks;\n self._stopCallbacks = [];\n _.each(callbacks, function (callback) {\n callback();\n });\n },\n\n // Send remove messages for every document.\n _removeAllDocuments: function () {\n var self = this;\n Meteor._noYieldsAllowed(function () {\n self._documents.forEach(function (collectionDocs, collectionName) {\n collectionDocs.forEach(function (strId) {\n self.removed(collectionName, self._idFilter.idParse(strId));\n });\n });\n });\n },\n\n // Returns a new Subscription for the same session with the same\n // initial creation parameters. This isn't a clone: it doesn't have\n // the same _documents cache, stopped state or callbacks; may have a\n // different _subscriptionHandle, and gets its userId from the\n // session, not from this object.\n _recreate: function () {\n var self = this;\n return new Subscription(\n self._session, self._handler, self._subscriptionId, self._params,\n self._name);\n },\n\n /**\n * @summary Call inside the publish function. Stops this client's subscription, triggering a call on the client to the `onStop` callback passed to [`Meteor.subscribe`](#meteor_subscribe), if any. If `error` is not a [`Meteor.Error`](#meteor_error), it will be [sanitized](#meteor_error).\n * @locus Server\n * @param {Error} error The error to pass to the client.\n * @instance\n * @memberOf Subscription\n */\n error: function (error) {\n var self = this;\n if (self._isDeactivated())\n return;\n self._session._stopSubscription(self._subscriptionId, error);\n },\n\n // Note that while our DDP client will notice that you've called stop() on the\n // server (and clean up its _subscriptions table) we don't actually provide a\n // mechanism for an app to notice this (the subscribe onError callback only\n // triggers if there is an error).\n\n /**\n * @summary Call inside the publish function. Stops this client's subscription and invokes the client's `onStop` callback with no error.\n * @locus Server\n * @instance\n * @memberOf Subscription\n */\n stop: function () {\n var self = this;\n if (self._isDeactivated())\n return;\n self._session._stopSubscription(self._subscriptionId);\n },\n\n /**\n * @summary Call inside the publish function. Registers a callback function to run when the subscription is stopped.\n * @locus Server\n * @memberOf Subscription\n * @instance\n * @param {Function} func The callback function\n */\n onStop: function (callback) {\n var self = this;\n callback = Meteor.bindEnvironment(callback, 'onStop callback', self);\n if (self._isDeactivated())\n callback();\n else\n self._stopCallbacks.push(callback);\n },\n\n // This returns true if the sub has been deactivated, *OR* if the session was\n // destroyed but the deferred call to _deactivateAllSubscriptions hasn't\n // happened yet.\n _isDeactivated: function () {\n var self = this;\n return self._deactivated || self._session.inQueue === null;\n },\n\n /**\n * @summary Call inside the publish function. Informs the subscriber that a document has been added to the record set.\n * @locus Server\n * @memberOf Subscription\n * @instance\n * @param {String} collection The name of the collection that contains the new document.\n * @param {String} id The new document's ID.\n * @param {Object} fields The fields in the new document. If `_id` is present it is ignored.\n */\n added (collectionName, id, fields) {\n if (this._isDeactivated())\n return;\n id = this._idFilter.idStringify(id);\n\n if (this._session.server.getPublicationStrategy(collectionName).doAccountingForCollection) {\n let ids = this._documents.get(collectionName);\n if (ids == null) {\n ids = new Set();\n this._documents.set(collectionName, ids);\n }\n ids.add(id);\n }\n\n this._session.added(this._subscriptionHandle, collectionName, id, fields);\n },\n\n /**\n * @summary Call inside the publish function. Informs the subscriber that a document in the record set has been modified.\n * @locus Server\n * @memberOf Subscription\n * @instance\n * @param {String} collection The name of the collection that contains the changed document.\n * @param {String} id The changed document's ID.\n * @param {Object} fields The fields in the document that have changed, together with their new values. If a field is not present in `fields` it was left unchanged; if it is present in `fields` and has a value of `undefined` it was removed from the document. If `_id` is present it is ignored.\n */\n changed (collectionName, id, fields) {\n if (this._isDeactivated())\n return;\n id = this._idFilter.idStringify(id);\n this._session.changed(this._subscriptionHandle, collectionName, id, fields);\n },\n\n /**\n * @summary Call inside the publish function. Informs the subscriber that a document has been removed from the record set.\n * @locus Server\n * @memberOf Subscription\n * @instance\n * @param {String} collection The name of the collection that the document has been removed from.\n * @param {String} id The ID of the document that has been removed.\n */\n removed (collectionName, id) {\n if (this._isDeactivated())\n return;\n id = this._idFilter.idStringify(id);\n\n if (this._session.server.getPublicationStrategy(collectionName).doAccountingForCollection) {\n // We don't bother to delete sets of things in a collection if the\n // collection is empty. It could break _removeAllDocuments.\n this._documents.get(collectionName).delete(id);\n }\n\n this._session.removed(this._subscriptionHandle, collectionName, id);\n },\n\n /**\n * @summary Call inside the publish function. Informs the subscriber that an initial, complete snapshot of the record set has been sent. This will trigger a call on the client to the `onReady` callback passed to [`Meteor.subscribe`](#meteor_subscribe), if any.\n * @locus Server\n * @memberOf Subscription\n * @instance\n */\n ready: function () {\n var self = this;\n if (self._isDeactivated())\n return;\n if (!self._subscriptionId)\n return; // Unnecessary but ignored for universal sub\n if (!self._ready) {\n self._session.sendReady([self._subscriptionId]);\n self._ready = true;\n }\n }\n});\n\n/******************************************************************************/\n/* Server */\n/******************************************************************************/\n\nServer = function (options = {}) {\n var self = this;\n\n // The default heartbeat interval is 30 seconds on the server and 35\n // seconds on the client. Since the client doesn't need to send a\n // ping as long as it is receiving pings, this means that pings\n // normally go from the server to the client.\n //\n // Note: Troposphere depends on the ability to mutate\n // Meteor.server.options.heartbeatTimeout! This is a hack, but it's life.\n self.options = {\n heartbeatInterval: 15000,\n heartbeatTimeout: 15000,\n // For testing, allow responding to pings to be disabled.\n respondToPings: true,\n defaultPublicationStrategy: publicationStrategies.SERVER_MERGE,\n ...options,\n };\n\n // Map of callbacks to call when a new connection comes in to the\n // server and completes DDP version negotiation. Use an object instead\n // of an array so we can safely remove one from the list while\n // iterating over it.\n self.onConnectionHook = new Hook({\n debugPrintExceptions: \"onConnection callback\"\n });\n\n // Map of callbacks to call when a new message comes in.\n self.onMessageHook = new Hook({\n debugPrintExceptions: \"onMessage callback\"\n });\n\n self.publish_handlers = {};\n self.universal_publish_handlers = [];\n\n self.method_handlers = {};\n\n self._publicationStrategies = {};\n\n self.sessions = new Map(); // map from id to session\n\n self.stream_server = new StreamServer;\n\n self.stream_server.register(function (socket) {\n // socket implements the SockJSConnection interface\n socket._meteorSession = null;\n\n var sendError = function (reason, offendingMessage) {\n var msg = {msg: 'error', reason: reason};\n if (offendingMessage)\n msg.offendingMessage = offendingMessage;\n socket.send(DDPCommon.stringifyDDP(msg));\n };\n\n socket.on('data', function (raw_msg) {\n if (Meteor._printReceivedDDP) {\n Meteor._debug(\"Received DDP\", raw_msg);\n }\n try {\n try {\n var msg = DDPCommon.parseDDP(raw_msg);\n } catch (err) {\n sendError('Parse error');\n return;\n }\n if (msg === null || !msg.msg) {\n sendError('Bad request', msg);\n return;\n }\n\n if (msg.msg === 'connect') {\n if (socket._meteorSession) {\n sendError(\"Already connected\", msg);\n return;\n }\n Fiber(function () {\n self._handleConnect(socket, msg);\n }).run();\n return;\n }\n\n if (!socket._meteorSession) {\n sendError('Must connect first', msg);\n return;\n }\n socket._meteorSession.processMessage(msg);\n } catch (e) {\n // XXX print stack nicely\n Meteor._debug(\"Internal exception while processing message\", msg, e);\n }\n });\n\n socket.on('close', function () {\n if (socket._meteorSession) {\n Fiber(function () {\n socket._meteorSession.close();\n }).run();\n }\n });\n });\n};\n\nObject.assign(Server.prototype, {\n\n /**\n * @summary Register a callback to be called when a new DDP connection is made to the server.\n * @locus Server\n * @param {function} callback The function to call when a new DDP connection is established.\n * @memberOf Meteor\n * @importFromPackage meteor\n */\n onConnection: function (fn) {\n var self = this;\n return self.onConnectionHook.register(fn);\n },\n\n /**\n * @summary Set publication strategy for the given publication. Publications strategies are available from `DDPServer.publicationStrategies`. You call this method from `Meteor.server`, like `Meteor.server.setPublicationStrategy()`\n * @locus Server\n * @alias setPublicationStrategy\n * @param publicationName {String}\n * @param strategy {{useCollectionView: boolean, doAccountingForCollection: boolean}}\n * @memberOf Meteor.server\n * @importFromPackage meteor\n */\n setPublicationStrategy(publicationName, strategy) {\n if (!Object.values(publicationStrategies).includes(strategy)) {\n throw new Error(`Invalid merge strategy: ${strategy} \n for collection ${publicationName}`);\n }\n this._publicationStrategies[publicationName] = strategy;\n },\n\n /**\n * @summary Gets the publication strategy for the requested publication. You call this method from `Meteor.server`, like `Meteor.server.getPublicationStrategy()`\n * @locus Server\n * @alias getPublicationStrategy\n * @param publicationName {String}\n * @memberOf Meteor.server\n * @importFromPackage meteor\n * @return {{useCollectionView: boolean, doAccountingForCollection: boolean}}\n */\n getPublicationStrategy(publicationName) {\n return this._publicationStrategies[publicationName]\n || this.options.defaultPublicationStrategy;\n },\n\n /**\n * @summary Register a callback to be called when a new DDP message is received.\n * @locus Server\n * @param {function} callback The function to call when a new DDP message is received.\n * @memberOf Meteor\n * @importFromPackage meteor\n */\n onMessage: function (fn) {\n var self = this;\n return self.onMessageHook.register(fn);\n },\n\n _handleConnect: function (socket, msg) {\n var self = this;\n\n // The connect message must specify a version and an array of supported\n // versions, and it must claim to support what it is proposing.\n if (!(typeof (msg.version) === 'string' &&\n _.isArray(msg.support) &&\n _.all(msg.support, _.isString) &&\n _.contains(msg.support, msg.version))) {\n socket.send(DDPCommon.stringifyDDP({msg: 'failed',\n version: DDPCommon.SUPPORTED_DDP_VERSIONS[0]}));\n socket.close();\n return;\n }\n\n // In the future, handle session resumption: something like:\n // socket._meteorSession = self.sessions[msg.session]\n var version = calculateVersion(msg.support, DDPCommon.SUPPORTED_DDP_VERSIONS);\n\n if (msg.version !== version) {\n // The best version to use (according to the client's stated preferences)\n // is not the one the client is trying to use. Inform them about the best\n // version to use.\n socket.send(DDPCommon.stringifyDDP({msg: 'failed', version: version}));\n socket.close();\n return;\n }\n\n // Yay, version matches! Create a new session.\n // Note: Troposphere depends on the ability to mutate\n // Meteor.server.options.heartbeatTimeout! This is a hack, but it's life.\n socket._meteorSession = new Session(self, version, socket, self.options);\n self.sessions.set(socket._meteorSession.id, socket._meteorSession);\n self.onConnectionHook.each(function (callback) {\n if (socket._meteorSession)\n callback(socket._meteorSession.connectionHandle);\n return true;\n });\n },\n /**\n * Register a publish handler function.\n *\n * @param name {String} identifier for query\n * @param handler {Function} publish handler\n * @param options {Object}\n *\n * Server will call handler function on each new subscription,\n * either when receiving DDP sub message for a named subscription, or on\n * DDP connect for a universal subscription.\n *\n * If name is null, this will be a subscription that is\n * automatically established and permanently on for all connected\n * client, instead of a subscription that can be turned on and off\n * with subscribe().\n *\n * options to contain:\n * - (mostly internal) is_auto: true if generated automatically\n * from an autopublish hook. this is for cosmetic purposes only\n * (it lets us determine whether to print a warning suggesting\n * that you turn off autopublish).\n */\n\n /**\n * @summary Publish a record set.\n * @memberOf Meteor\n * @importFromPackage meteor\n * @locus Server\n * @param {String|Object} name If String, name of the record set. If Object, publications Dictionary of publish functions by name. If `null`, the set has no name, and the record set is automatically sent to all connected clients.\n * @param {Function} func Function called on the server each time a client subscribes. Inside the function, `this` is the publish handler object, described below. If the client passed arguments to `subscribe`, the function is called with the same arguments.\n */\n publish: function (name, handler, options) {\n var self = this;\n\n if (! _.isObject(name)) {\n options = options || {};\n\n if (name && name in self.publish_handlers) {\n Meteor._debug(\"Ignoring duplicate publish named '\" + name + \"'\");\n return;\n }\n\n if (Package.autopublish && !options.is_auto) {\n // They have autopublish on, yet they're trying to manually\n // pick stuff to publish. They probably should turn off\n // autopublish. (This check isn't perfect -- if you create a\n // publish before you turn on autopublish, it won't catch\n // it, but this will definitely handle the simple case where\n // you've added the autopublish package to your app, and are\n // calling publish from your app code).\n if (!self.warned_about_autopublish) {\n self.warned_about_autopublish = true;\n Meteor._debug(\n \"** You've set up some data subscriptions with Meteor.publish(), but\\n\" +\n \"** you still have autopublish turned on. Because autopublish is still\\n\" +\n \"** on, your Meteor.publish() calls won't have much effect. All data\\n\" +\n \"** will still be sent to all clients.\\n\" +\n \"**\\n\" +\n \"** Turn off autopublish by removing the autopublish package:\\n\" +\n \"**\\n\" +\n \"** $ meteor remove autopublish\\n\" +\n \"**\\n\" +\n \"** .. and make sure you have Meteor.publish() and Meteor.subscribe() calls\\n\" +\n \"** for each collection that you want clients to see.\\n\");\n }\n }\n\n if (name)\n self.publish_handlers[name] = handler;\n else {\n self.universal_publish_handlers.push(handler);\n // Spin up the new publisher on any existing session too. Run each\n // session's subscription in a new Fiber, so that there's no change for\n // self.sessions to change while we're running this loop.\n self.sessions.forEach(function (session) {\n if (!session._dontStartNewUniversalSubs) {\n Fiber(function() {\n session._startSubscription(handler);\n }).run();\n }\n });\n }\n }\n else{\n _.each(name, function(value, key) {\n self.publish(key, value, {});\n });\n }\n },\n\n _removeSession: function (session) {\n var self = this;\n self.sessions.delete(session.id);\n },\n\n /**\n * @summary Defines functions that can be invoked over the network by clients.\n * @locus Anywhere\n * @param {Object} methods Dictionary whose keys are method names and values are functions.\n * @memberOf Meteor\n * @importFromPackage meteor\n */\n methods: function (methods) {\n var self = this;\n _.each(methods, function (func, name) {\n if (typeof func !== 'function')\n throw new Error(\"Method '\" + name + \"' must be a function\");\n if (self.method_handlers[name])\n throw new Error(\"A method named '\" + name + \"' is already defined\");\n self.method_handlers[name] = func;\n });\n },\n\n call: function (name, ...args) {\n if (args.length && typeof args[args.length - 1] === \"function\") {\n // If it's a function, the last argument is the result callback, not\n // a parameter to the remote method.\n var callback = args.pop();\n }\n\n return this.apply(name, args, callback);\n },\n\n // A version of the call method that always returns a Promise.\n callAsync: function (name, ...args) {\n return this.applyAsync(name, args);\n },\n\n apply: function (name, args, options, callback) {\n // We were passed 3 arguments. They may be either (name, args, options)\n // or (name, args, callback)\n if (! callback && typeof options === 'function') {\n callback = options;\n options = {};\n } else {\n options = options || {};\n }\n\n const promise = this.applyAsync(name, args, options);\n\n // Return the result in whichever way the caller asked for it. Note that we\n // do NOT block on the write fence in an analogous way to how the client\n // blocks on the relevant data being visible, so you are NOT guaranteed that\n // cursor observe callbacks have fired when your callback is invoked. (We\n // can change this if there's a real use case).\n if (callback) {\n promise.then(\n result => callback(undefined, result),\n exception => callback(exception)\n );\n } else {\n return promise.await();\n }\n },\n\n // @param options {Optional Object}\n applyAsync: function (name, args, options) {\n // Run the handler\n var handler = this.method_handlers[name];\n if (! handler) {\n return Promise.reject(\n new Meteor.Error(404, `Method '${name}' not found`)\n );\n }\n\n // If this is a method call from within another method or publish function,\n // get the user state from the outer method or publish function, otherwise\n // don't allow setUserId to be called\n var userId = null;\n var setUserId = function() {\n throw new Error(\"Can't call setUserId on a server initiated method call\");\n };\n var connection = null;\n var currentMethodInvocation = DDP._CurrentMethodInvocation.get();\n var currentPublicationInvocation = DDP._CurrentPublicationInvocation.get();\n var randomSeed = null;\n if (currentMethodInvocation) {\n userId = currentMethodInvocation.userId;\n setUserId = function(userId) {\n currentMethodInvocation.setUserId(userId);\n };\n connection = currentMethodInvocation.connection;\n randomSeed = DDPCommon.makeRpcSeed(currentMethodInvocation, name);\n } else if (currentPublicationInvocation) {\n userId = currentPublicationInvocation.userId;\n setUserId = function(userId) {\n currentPublicationInvocation._session._setUserId(userId);\n };\n connection = currentPublicationInvocation.connection;\n }\n\n var invocation = new DDPCommon.MethodInvocation({\n isSimulation: false,\n userId,\n setUserId,\n connection,\n randomSeed\n });\n\n return new Promise(resolve => resolve(\n DDP._CurrentMethodInvocation.withValue(\n invocation,\n () => maybeAuditArgumentChecks(\n handler, invocation, EJSON.clone(args),\n \"internal call to '\" + name + \"'\"\n )\n )\n )).then(EJSON.clone);\n },\n\n _urlForSession: function (sessionId) {\n var self = this;\n var session = self.sessions.get(sessionId);\n if (session)\n return session._socketUrl;\n else\n return null;\n }\n});\n\nvar calculateVersion = function (clientSupportedVersions,\n serverSupportedVersions) {\n var correctVersion = _.find(clientSupportedVersions, function (version) {\n return _.contains(serverSupportedVersions, version);\n });\n if (!correctVersion) {\n correctVersion = serverSupportedVersions[0];\n }\n return correctVersion;\n};\n\nDDPServer._calculateVersion = calculateVersion;\n\n\n// \"blind\" exceptions other than those that were deliberately thrown to signal\n// errors to the client\nvar wrapInternalException = function (exception, context) {\n if (!exception) return exception;\n\n // To allow packages to throw errors intended for the client but not have to\n // depend on the Meteor.Error class, `isClientSafe` can be set to true on any\n // error before it is thrown.\n if (exception.isClientSafe) {\n if (!(exception instanceof Meteor.Error)) {\n const originalMessage = exception.message;\n exception = new Meteor.Error(exception.error, exception.reason, exception.details);\n exception.message = originalMessage;\n }\n return exception;\n }\n\n // Tests can set the '_expectedByTest' flag on an exception so it won't go to\n // the server log.\n if (!exception._expectedByTest) {\n Meteor._debug(\"Exception \" + context, exception.stack);\n if (exception.sanitizedError) {\n Meteor._debug(\"Sanitized and reported to the client as:\", exception.sanitizedError);\n Meteor._debug();\n }\n }\n\n // Did the error contain more details that could have been useful if caught in\n // server code (or if thrown from non-client-originated code), but also\n // provided a \"sanitized\" version with more context than 500 Internal server\n // error? Use that.\n if (exception.sanitizedError) {\n if (exception.sanitizedError.isClientSafe)\n return exception.sanitizedError;\n Meteor._debug(\"Exception \" + context + \" provides a sanitizedError that \" +\n \"does not have isClientSafe property set; ignoring\");\n }\n\n return new Meteor.Error(500, \"Internal server error\");\n};\n\n\n// Audit argument checks, if the audit-argument-checks package exists (it is a\n// weak dependency of this package).\nvar maybeAuditArgumentChecks = function (f, context, args, description) {\n args = args || [];\n if (Package['audit-argument-checks']) {\n return Match._failIfArgumentsAreNotAllChecked(\n f, context, args, description);\n }\n return f.apply(context, args);\n};\n","var Future = Npm.require('fibers/future');\n\n// A write fence collects a group of writes, and provides a callback\n// when all of the writes are fully committed and propagated (all\n// observers have been notified of the write and acknowledged it.)\n//\nDDPServer._WriteFence = function () {\n var self = this;\n\n self.armed = false;\n self.fired = false;\n self.retired = false;\n self.outstanding_writes = 0;\n self.before_fire_callbacks = [];\n self.completion_callbacks = [];\n};\n\n// The current write fence. When there is a current write fence, code\n// that writes to databases should register their writes with it using\n// beginWrite().\n//\nDDPServer._CurrentWriteFence = new Meteor.EnvironmentVariable;\n\n_.extend(DDPServer._WriteFence.prototype, {\n // Start tracking a write, and return an object to represent it. The\n // object has a single method, committed(). This method should be\n // called when the write is fully committed and propagated. You can\n // continue to add writes to the WriteFence up until it is triggered\n // (calls its callbacks because all writes have committed.)\n beginWrite: function () {\n var self = this;\n\n if (self.retired)\n return { committed: function () {} };\n\n if (self.fired)\n throw new Error(\"fence has already activated -- too late to add writes\");\n\n self.outstanding_writes++;\n var committed = false;\n return {\n committed: function () {\n if (committed)\n throw new Error(\"committed called twice on the same write\");\n committed = true;\n self.outstanding_writes--;\n self._maybeFire();\n }\n };\n },\n\n // Arm the fence. Once the fence is armed, and there are no more\n // uncommitted writes, it will activate.\n arm: function () {\n var self = this;\n if (self === DDPServer._CurrentWriteFence.get())\n throw Error(\"Can't arm the current fence\");\n self.armed = true;\n self._maybeFire();\n },\n\n // Register a function to be called once before firing the fence.\n // Callback function can add new writes to the fence, in which case\n // it won't fire until those writes are done as well.\n onBeforeFire: function (func) {\n var self = this;\n if (self.fired)\n throw new Error(\"fence has already activated -- too late to \" +\n \"add a callback\");\n self.before_fire_callbacks.push(func);\n },\n\n // Register a function to be called when the fence fires.\n onAllCommitted: function (func) {\n var self = this;\n if (self.fired)\n throw new Error(\"fence has already activated -- too late to \" +\n \"add a callback\");\n self.completion_callbacks.push(func);\n },\n\n // Convenience function. Arms the fence, then blocks until it fires.\n armAndWait: function () {\n var self = this;\n var future = new Future;\n self.onAllCommitted(function () {\n future['return']();\n });\n self.arm();\n future.wait();\n },\n\n _maybeFire: function () {\n var self = this;\n if (self.fired)\n throw new Error(\"write fence already activated?\");\n if (self.armed && !self.outstanding_writes) {\n function invokeCallback (func) {\n try {\n func(self);\n } catch (err) {\n Meteor._debug(\"exception in write fence callback\", err);\n }\n }\n\n self.outstanding_writes++;\n while (self.before_fire_callbacks.length > 0) {\n var callbacks = self.before_fire_callbacks;\n self.before_fire_callbacks = [];\n _.each(callbacks, invokeCallback);\n }\n self.outstanding_writes--;\n\n if (!self.outstanding_writes) {\n self.fired = true;\n var callbacks = self.completion_callbacks;\n self.completion_callbacks = [];\n _.each(callbacks, invokeCallback);\n }\n }\n },\n\n // Deactivate this fence so that adding more writes has no effect.\n // The fence must have already fired.\n retire: function () {\n var self = this;\n if (! self.fired)\n throw new Error(\"Can't retire a fence that hasn't fired.\");\n self.retired = true;\n }\n});\n","// A \"crossbar\" is a class that provides structured notification registration.\n// See _match for the definition of how a notification matches a trigger.\n// All notifications and triggers must have a string key named 'collection'.\n\nDDPServer._Crossbar = function (options) {\n var self = this;\n options = options || {};\n\n self.nextId = 1;\n // map from collection name (string) -> listener id -> object. each object has\n // keys 'trigger', 'callback'. As a hack, the empty string means \"no\n // collection\".\n self.listenersByCollection = {};\n self.listenersByCollectionCount = {};\n self.factPackage = options.factPackage || \"livedata\";\n self.factName = options.factName || null;\n};\n\n_.extend(DDPServer._Crossbar.prototype, {\n // msg is a trigger or a notification\n _collectionForMessage: function (msg) {\n var self = this;\n if (! _.has(msg, 'collection')) {\n return '';\n } else if (typeof(msg.collection) === 'string') {\n if (msg.collection === '')\n throw Error(\"Message has empty collection!\");\n return msg.collection;\n } else {\n throw Error(\"Message has non-string collection!\");\n }\n },\n\n // Listen for notification that match 'trigger'. A notification\n // matches if it has the key-value pairs in trigger as a\n // subset. When a notification matches, call 'callback', passing\n // the actual notification.\n //\n // Returns a listen handle, which is an object with a method\n // stop(). Call stop() to stop listening.\n //\n // XXX It should be legal to call fire() from inside a listen()\n // callback?\n listen: function (trigger, callback) {\n var self = this;\n var id = self.nextId++;\n\n var collection = self._collectionForMessage(trigger);\n var record = {trigger: EJSON.clone(trigger), callback: callback};\n if (! _.has(self.listenersByCollection, collection)) {\n self.listenersByCollection[collection] = {};\n self.listenersByCollectionCount[collection] = 0;\n }\n self.listenersByCollection[collection][id] = record;\n self.listenersByCollectionCount[collection]++;\n\n if (self.factName && Package['facts-base']) {\n Package['facts-base'].Facts.incrementServerFact(\n self.factPackage, self.factName, 1);\n }\n\n return {\n stop: function () {\n if (self.factName && Package['facts-base']) {\n Package['facts-base'].Facts.incrementServerFact(\n self.factPackage, self.factName, -1);\n }\n delete self.listenersByCollection[collection][id];\n self.listenersByCollectionCount[collection]--;\n if (self.listenersByCollectionCount[collection] === 0) {\n delete self.listenersByCollection[collection];\n delete self.listenersByCollectionCount[collection];\n }\n }\n };\n },\n\n // Fire the provided 'notification' (an object whose attribute\n // values are all JSON-compatibile) -- inform all matching listeners\n // (registered with listen()).\n //\n // If fire() is called inside a write fence, then each of the\n // listener callbacks will be called inside the write fence as well.\n //\n // The listeners may be invoked in parallel, rather than serially.\n fire: function (notification) {\n var self = this;\n\n var collection = self._collectionForMessage(notification);\n\n if (! _.has(self.listenersByCollection, collection)) {\n return;\n }\n\n var listenersForCollection = self.listenersByCollection[collection];\n var callbackIds = [];\n _.each(listenersForCollection, function (l, id) {\n if (self._matches(notification, l.trigger)) {\n callbackIds.push(id);\n }\n });\n\n // Listener callbacks can yield, so we need to first find all the ones that\n // match in a single iteration over self.listenersByCollection (which can't\n // be mutated during this iteration), and then invoke the matching\n // callbacks, checking before each call to ensure they haven't stopped.\n // Note that we don't have to check that\n // self.listenersByCollection[collection] still === listenersForCollection,\n // because the only way that stops being true is if listenersForCollection\n // first gets reduced down to the empty object (and then never gets\n // increased again).\n _.each(callbackIds, function (id) {\n if (_.has(listenersForCollection, id)) {\n listenersForCollection[id].callback(notification);\n }\n });\n },\n\n // A notification matches a trigger if all keys that exist in both are equal.\n //\n // Examples:\n // N:{collection: \"C\"} matches T:{collection: \"C\"}\n // (a non-targeted write to a collection matches a\n // non-targeted query)\n // N:{collection: \"C\", id: \"X\"} matches T:{collection: \"C\"}\n // (a targeted write to a collection matches a non-targeted query)\n // N:{collection: \"C\"} matches T:{collection: \"C\", id: \"X\"}\n // (a non-targeted write to a collection matches a\n // targeted query)\n // N:{collection: \"C\", id: \"X\"} matches T:{collection: \"C\", id: \"X\"}\n // (a targeted write to a collection matches a targeted query targeted\n // at the same document)\n // N:{collection: \"C\", id: \"X\"} does not match T:{collection: \"C\", id: \"Y\"}\n // (a targeted write to a collection does not match a targeted query\n // targeted at a different document)\n _matches: function (notification, trigger) {\n // Most notifications that use the crossbar have a string `collection` and\n // maybe an `id` that is a string or ObjectID. We're already dividing up\n // triggers by collection, but let's fast-track \"nope, different ID\" (and\n // avoid the overly generic EJSON.equals). This makes a noticeable\n // performance difference; see https://github.com/meteor/meteor/pull/3697\n if (typeof(notification.id) === 'string' &&\n typeof(trigger.id) === 'string' &&\n notification.id !== trigger.id) {\n return false;\n }\n if (notification.id instanceof MongoID.ObjectID &&\n trigger.id instanceof MongoID.ObjectID &&\n ! notification.id.equals(trigger.id)) {\n return false;\n }\n\n return _.all(trigger, function (triggerValue, key) {\n return !_.has(notification, key) ||\n EJSON.equals(triggerValue, notification[key]);\n });\n }\n});\n\n// The \"invalidation crossbar\" is a specific instance used by the DDP server to\n// implement write fence notifications. Listener callbacks on this crossbar\n// should call beginWrite on the current write fence before they return, if they\n// want to delay the write fence from firing (ie, the DDP method-data-updated\n// message from being sent).\nDDPServer._InvalidationCrossbar = new DDPServer._Crossbar({\n factName: \"invalidation-crossbar-listeners\"\n});\n","if (process.env.DDP_DEFAULT_CONNECTION_URL) {\n __meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL =\n process.env.DDP_DEFAULT_CONNECTION_URL;\n}\n\nMeteor.server = new Server;\n\nMeteor.refresh = function (notification) {\n DDPServer._InvalidationCrossbar.fire(notification);\n};\n\n// Proxy the public methods of Meteor.server so they can\n// be called directly on Meteor.\n_.each(['publish', 'methods', 'call', 'apply', 'onConnection', 'onMessage'],\n function (name) {\n Meteor[name] = _.bind(Meteor.server[name], Meteor.server);\n });\n"]}