mongodb-livedata-server 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +63 -0
  2. package/dist/livedata_server.js +9 -0
  3. package/dist/meteor/binary-heap/max_heap.js +186 -0
  4. package/dist/meteor/binary-heap/min_heap.js +17 -0
  5. package/dist/meteor/binary-heap/min_max_heap.js +48 -0
  6. package/dist/meteor/callback-hook/hook.js +78 -0
  7. package/dist/meteor/ddp/crossbar.js +136 -0
  8. package/dist/meteor/ddp/heartbeat.js +77 -0
  9. package/dist/meteor/ddp/livedata_server.js +403 -0
  10. package/dist/meteor/ddp/method-invocation.js +72 -0
  11. package/dist/meteor/ddp/random-stream.js +100 -0
  12. package/dist/meteor/ddp/session-collection-view.js +106 -0
  13. package/dist/meteor/ddp/session-document-view.js +82 -0
  14. package/dist/meteor/ddp/session.js +570 -0
  15. package/dist/meteor/ddp/stream_server.js +181 -0
  16. package/dist/meteor/ddp/subscription.js +347 -0
  17. package/dist/meteor/ddp/utils.js +104 -0
  18. package/dist/meteor/ddp/writefence.js +111 -0
  19. package/dist/meteor/diff-sequence/diff.js +257 -0
  20. package/dist/meteor/ejson/ejson.js +569 -0
  21. package/dist/meteor/ejson/stringify.js +119 -0
  22. package/dist/meteor/ejson/utils.js +42 -0
  23. package/dist/meteor/id-map/id_map.js +92 -0
  24. package/dist/meteor/mongo/caching_change_observer.js +94 -0
  25. package/dist/meteor/mongo/doc_fetcher.js +53 -0
  26. package/dist/meteor/mongo/geojson_utils.js +41 -0
  27. package/dist/meteor/mongo/live_connection.js +264 -0
  28. package/dist/meteor/mongo/live_cursor.js +57 -0
  29. package/dist/meteor/mongo/minimongo_common.js +2002 -0
  30. package/dist/meteor/mongo/minimongo_matcher.js +217 -0
  31. package/dist/meteor/mongo/minimongo_sorter.js +268 -0
  32. package/dist/meteor/mongo/observe_driver_utils.js +73 -0
  33. package/dist/meteor/mongo/observe_multiplexer.js +228 -0
  34. package/dist/meteor/mongo/oplog-observe-driver.js +919 -0
  35. package/dist/meteor/mongo/oplog_tailing.js +352 -0
  36. package/dist/meteor/mongo/oplog_v2_converter.js +126 -0
  37. package/dist/meteor/mongo/polling_observe_driver.js +195 -0
  38. package/dist/meteor/mongo/synchronous-cursor.js +261 -0
  39. package/dist/meteor/mongo/synchronous-queue.js +110 -0
  40. package/dist/meteor/ordered-dict/ordered_dict.js +198 -0
  41. package/dist/meteor/random/AbstractRandomGenerator.js +92 -0
  42. package/dist/meteor/random/AleaRandomGenerator.js +90 -0
  43. package/dist/meteor/random/NodeRandomGenerator.js +42 -0
  44. package/dist/meteor/random/createAleaGenerator.js +32 -0
  45. package/dist/meteor/random/createRandom.js +22 -0
  46. package/dist/meteor/random/main.js +12 -0
  47. package/livedata_server.ts +3 -0
  48. package/meteor/LICENSE +28 -0
  49. package/meteor/binary-heap/max_heap.ts +225 -0
  50. package/meteor/binary-heap/min_heap.ts +15 -0
  51. package/meteor/binary-heap/min_max_heap.ts +53 -0
  52. package/meteor/callback-hook/hook.ts +85 -0
  53. package/meteor/ddp/crossbar.ts +148 -0
  54. package/meteor/ddp/heartbeat.ts +97 -0
  55. package/meteor/ddp/livedata_server.ts +473 -0
  56. package/meteor/ddp/method-invocation.ts +86 -0
  57. package/meteor/ddp/random-stream.ts +102 -0
  58. package/meteor/ddp/session-collection-view.ts +119 -0
  59. package/meteor/ddp/session-document-view.ts +92 -0
  60. package/meteor/ddp/session.ts +708 -0
  61. package/meteor/ddp/stream_server.ts +204 -0
  62. package/meteor/ddp/subscription.ts +392 -0
  63. package/meteor/ddp/utils.ts +119 -0
  64. package/meteor/ddp/writefence.ts +130 -0
  65. package/meteor/diff-sequence/diff.ts +295 -0
  66. package/meteor/ejson/ejson.ts +601 -0
  67. package/meteor/ejson/stringify.ts +122 -0
  68. package/meteor/ejson/utils.ts +38 -0
  69. package/meteor/id-map/id_map.ts +84 -0
  70. package/meteor/mongo/caching_change_observer.ts +120 -0
  71. package/meteor/mongo/doc_fetcher.ts +52 -0
  72. package/meteor/mongo/geojson_utils.ts +42 -0
  73. package/meteor/mongo/live_connection.ts +302 -0
  74. package/meteor/mongo/live_cursor.ts +79 -0
  75. package/meteor/mongo/minimongo_common.ts +2440 -0
  76. package/meteor/mongo/minimongo_matcher.ts +275 -0
  77. package/meteor/mongo/minimongo_sorter.ts +331 -0
  78. package/meteor/mongo/observe_driver_utils.ts +79 -0
  79. package/meteor/mongo/observe_multiplexer.ts +256 -0
  80. package/meteor/mongo/oplog-observe-driver.ts +1049 -0
  81. package/meteor/mongo/oplog_tailing.ts +414 -0
  82. package/meteor/mongo/oplog_v2_converter.ts +124 -0
  83. package/meteor/mongo/polling_observe_driver.ts +247 -0
  84. package/meteor/mongo/synchronous-cursor.ts +293 -0
  85. package/meteor/mongo/synchronous-queue.ts +119 -0
  86. package/meteor/ordered-dict/ordered_dict.ts +229 -0
  87. package/meteor/random/AbstractRandomGenerator.ts +99 -0
  88. package/meteor/random/AleaRandomGenerator.ts +96 -0
  89. package/meteor/random/NodeRandomGenerator.ts +37 -0
  90. package/meteor/random/createAleaGenerator.ts +31 -0
  91. package/meteor/random/createRandom.ts +19 -0
  92. package/meteor/random/main.ts +8 -0
  93. package/package.json +30 -0
  94. package/tsconfig.json +10 -0
@@ -0,0 +1,403 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ClientSafeError = exports.ddpError = exports.maybeAuditArgumentChecks = exports.wrapInternalException = exports._calculateVersion = exports.DDPServer = exports.DDP = void 0;
4
+ const method_invocation_1 = require("./method-invocation");
5
+ const stream_server_1 = require("./stream_server");
6
+ const session_1 = require("./session");
7
+ const utils_1 = require("./utils");
8
+ const random_stream_1 = require("./random-stream");
9
+ const ejson_1 = require("../ejson/ejson");
10
+ const hook_1 = require("../callback-hook/hook");
11
+ exports.DDP = {};
12
+ class DDPServer {
13
+ constructor(options = {}, httpServer) {
14
+ this.publish_handlers = {};
15
+ this.universal_publish_handlers = [];
16
+ this.method_handlers = {};
17
+ this._publicationStrategies = {};
18
+ this.sessions = new Map(); // map from id to session
19
+ var self = this;
20
+ // The default heartbeat interval is 30 seconds on the server and 35
21
+ // seconds on the client. Since the client doesn't need to send a
22
+ // ping as long as it is receiving pings, this means that pings
23
+ // normally go from the server to the client.
24
+ //
25
+ // Note: Troposphere depends on the ability to mutate
26
+ // Meteor.server.options.heartbeatTimeout! This is a hack, but it's life.
27
+ self.options = Object.assign({ heartbeatInterval: 15000, heartbeatTimeout: 15000,
28
+ // For testing, allow responding to pings to be disabled.
29
+ respondToPings: true, defaultPublicationStrategy: DDPServer.publicationStrategies.SERVER_MERGE }, options);
30
+ // Map of callbacks to call when a new connection comes in to the
31
+ // server and completes DDP version negotiation. Use an object instead
32
+ // of an array so we can safely remove one from the list while
33
+ // iterating over it.
34
+ self.onConnectionHook = new hook_1.Hook({
35
+ debugPrintExceptions: "onConnection callback"
36
+ });
37
+ // Map of callbacks to call when a new message comes in.
38
+ self.onMessageHook = new hook_1.Hook({
39
+ debugPrintExceptions: "onMessage callback"
40
+ });
41
+ self.stream_server = new stream_server_1.StreamServer(httpServer);
42
+ self.stream_server.register(function (socket) {
43
+ // socket implements the SockJSConnection interface
44
+ socket._meteorSession = null;
45
+ var sendError = function (reason, offendingMessage) {
46
+ var msg = { msg: 'error', reason, offendingMessage };
47
+ socket.send((0, utils_1.stringifyDDP)(msg));
48
+ };
49
+ socket.on('data', async function (raw_msg) {
50
+ try {
51
+ try {
52
+ var msg = (0, utils_1.parseDDP)(raw_msg);
53
+ }
54
+ catch (err) {
55
+ sendError('Parse error');
56
+ return;
57
+ }
58
+ if (msg === null || !msg.msg) {
59
+ sendError('Bad request', msg);
60
+ return;
61
+ }
62
+ if (msg.msg === 'connect') {
63
+ if (socket._meteorSession) {
64
+ sendError("Already connected", msg);
65
+ return;
66
+ }
67
+ self._handleConnect(socket, msg);
68
+ return;
69
+ }
70
+ if (!socket._meteorSession) {
71
+ sendError('Must connect first', msg);
72
+ return;
73
+ }
74
+ await socket._meteorSession.processMessage(msg);
75
+ }
76
+ catch (e) {
77
+ // XXX print stack nicely
78
+ console.log("Internal exception while processing message", msg, e);
79
+ }
80
+ });
81
+ socket.on('close', function () {
82
+ if (socket._meteorSession) {
83
+ socket._meteorSession.close();
84
+ }
85
+ });
86
+ });
87
+ }
88
+ /**
89
+ * @summary Register a callback to be called when a new DDP connection is made to the server.
90
+ * @locus Server
91
+ * @param {function} callback The function to call when a new DDP connection is established.
92
+ * @memberOf Meteor
93
+ * @importFromPackage meteor
94
+ */
95
+ onConnection(fn) {
96
+ var self = this;
97
+ return self.onConnectionHook.register(fn);
98
+ }
99
+ /**
100
+ * @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()`
101
+ * @locus Server
102
+ * @alias setPublicationStrategy
103
+ * @param publicationName {String}
104
+ * @param strategy {{useCollectionView: boolean, doAccountingForCollection: boolean}}
105
+ * @memberOf Meteor.server
106
+ * @importFromPackage meteor
107
+ */
108
+ setPublicationStrategy(publicationName, strategy) {
109
+ if (!Object.values(DDPServer.publicationStrategies).includes(strategy)) {
110
+ throw new Error(`Invalid merge strategy: ${strategy}
111
+ for collection ${publicationName}`);
112
+ }
113
+ this._publicationStrategies[publicationName] = strategy;
114
+ }
115
+ /**
116
+ * @summary Gets the publication strategy for the requested publication. You call this method from `Meteor.server`, like `Meteor.server.getPublicationStrategy()`
117
+ * @locus Server
118
+ * @alias getPublicationStrategy
119
+ * @param publicationName {String}
120
+ * @memberOf Meteor.server
121
+ * @importFromPackage meteor
122
+ * @return {{useCollectionView: boolean, doAccountingForCollection: boolean}}
123
+ */
124
+ getPublicationStrategy(publicationName) {
125
+ return this._publicationStrategies[publicationName]
126
+ || this.options.defaultPublicationStrategy;
127
+ }
128
+ /**
129
+ * @summary Register a callback to be called when a new DDP message is received.
130
+ * @locus Server
131
+ * @param {function} callback The function to call when a new DDP message is received.
132
+ * @memberOf Meteor
133
+ * @importFromPackage meteor
134
+ */
135
+ onMessage(fn) {
136
+ var self = this;
137
+ return self.onMessageHook.register(fn);
138
+ }
139
+ _handleConnect(socket, msg) {
140
+ var self = this;
141
+ // The connect message must specify a version and an array of supported
142
+ // versions, and it must claim to support what it is proposing.
143
+ if (!(typeof (msg.version) === 'string' &&
144
+ Array.isArray(msg.support) &&
145
+ msg.support.every(s => typeof s === "string") &&
146
+ msg.support.includes(msg.version))) {
147
+ socket.send((0, utils_1.stringifyDDP)({
148
+ msg: 'failed',
149
+ version: utils_1.SUPPORTED_DDP_VERSIONS[0]
150
+ }));
151
+ socket.close();
152
+ return;
153
+ }
154
+ // In the future, handle session resumption: something like:
155
+ // socket._meteorSession = self.sessions[msg.session]
156
+ var version = _calculateVersion(msg.support, utils_1.SUPPORTED_DDP_VERSIONS);
157
+ if (msg.version !== version) {
158
+ // The best version to use (according to the client's stated preferences)
159
+ // is not the one the client is trying to use. Inform them about the best
160
+ // version to use.
161
+ socket.send((0, utils_1.stringifyDDP)({ msg: 'failed', version: version }));
162
+ socket.close();
163
+ return;
164
+ }
165
+ // Yay, version matches! Create a new session.
166
+ // Note: Troposphere depends on the ability to mutate
167
+ // Meteor.server.options.heartbeatTimeout! This is a hack, but it's life.
168
+ socket._meteorSession = new session_1.DDPSession(self, version, socket, self.options);
169
+ self.sessions.set(socket._meteorSession.id, socket._meteorSession);
170
+ self.onConnectionHook.each(function (callback) {
171
+ if (socket._meteorSession)
172
+ callback(socket._meteorSession.connectionHandle);
173
+ return true;
174
+ });
175
+ }
176
+ /**
177
+ * Register a publish handler function.
178
+ *
179
+ * @param name {String} identifier for query
180
+ * @param handler {Function} publish handler
181
+ *
182
+ * Server will call handler function on each new subscription,
183
+ * either when receiving DDP sub message for a named subscription, or on
184
+ * DDP connect for a universal subscription.
185
+ *
186
+ * If name is null, this will be a subscription that is
187
+ * automatically established and permanently on for all connected
188
+ * client, instead of a subscription that can be turned on and off
189
+ * with subscribe().
190
+ *
191
+ */
192
+ /**
193
+ * @summary Publish a record set.
194
+ * @memberOf Meteor
195
+ * @importFromPackage meteor
196
+ * @locus Server
197
+ * @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.
198
+ * @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.
199
+ */
200
+ publish(name, handler) {
201
+ var self = this;
202
+ if (typeof name === "string") {
203
+ if (name in self.publish_handlers) {
204
+ console.log("Ignoring duplicate publish named '" + name + "'");
205
+ return;
206
+ }
207
+ self.publish_handlers[name] = handler;
208
+ }
209
+ else if (name == null) {
210
+ self.universal_publish_handlers.push(handler);
211
+ // Spin up the new publisher on any existing session too. Run each
212
+ // session's subscription in a new Fiber, so that there's no change for
213
+ // self.sessions to change while we're running this loop.
214
+ self.sessions.forEach(function (session) {
215
+ if (!session._dontStartNewUniversalSubs) {
216
+ session._startSubscription(handler);
217
+ }
218
+ });
219
+ }
220
+ else {
221
+ for (const [key, value] of Object.entries(name)) {
222
+ self.publish(key, value);
223
+ }
224
+ }
225
+ }
226
+ _removeSession(session) {
227
+ this.sessions.delete(session.id);
228
+ }
229
+ /**
230
+ * @summary Defines functions that can be invoked over the network by clients.
231
+ * @locus Anywhere
232
+ * @param {Object} methods Dictionary whose keys are method names and values are functions.
233
+ * @memberOf Meteor
234
+ * @importFromPackage meteor
235
+ */
236
+ methods(methods) {
237
+ var self = this;
238
+ for (const [name, func] of Object.entries(methods)) {
239
+ if (typeof func !== 'function')
240
+ throw new Error("Method '" + name + "' must be a function");
241
+ if (self.method_handlers[name])
242
+ throw new Error("A method named '" + name + "' is already defined");
243
+ self.method_handlers[name] = func;
244
+ }
245
+ }
246
+ // A version of the call method that always returns a Promise.
247
+ callAsync(name, ...args) {
248
+ return this.applyAsync(name, args);
249
+ }
250
+ // @param options {Optional Object}
251
+ applyAsync(name, args) {
252
+ // Run the handler
253
+ var handler = this.method_handlers[name];
254
+ if (!handler) {
255
+ return Promise.reject(ddpError(404, `Method '${name}' not found`));
256
+ }
257
+ // If this is a method call from within another method or publish function,
258
+ // get the user state from the outer method or publish function, otherwise
259
+ // don't allow setUserId to be called
260
+ var userId = null;
261
+ var setUserId = function () {
262
+ throw new Error("Can't call setUserId on a server initiated method call");
263
+ };
264
+ var connection = null;
265
+ var currentMethodInvocation = exports.DDP._CurrentMethodInvocation;
266
+ var currentPublicationInvocation = exports.DDP._CurrentPublicationInvocation;
267
+ var randomSeed = null;
268
+ if (currentMethodInvocation) {
269
+ userId = currentMethodInvocation.userId;
270
+ setUserId = function (userId) {
271
+ currentMethodInvocation.setUserId(userId);
272
+ };
273
+ connection = currentMethodInvocation.connection;
274
+ randomSeed = (0, random_stream_1.makeRpcSeed)(currentMethodInvocation, name);
275
+ }
276
+ else if (currentPublicationInvocation) {
277
+ userId = currentPublicationInvocation.userId;
278
+ setUserId = function (userId) {
279
+ currentPublicationInvocation._session._setUserId(userId);
280
+ };
281
+ connection = currentPublicationInvocation.connection;
282
+ }
283
+ var invocation = new method_invocation_1.MethodInvocation({
284
+ isSimulation: false,
285
+ userId,
286
+ setUserId,
287
+ connection,
288
+ randomSeed
289
+ });
290
+ return new Promise(resolve => {
291
+ const oldInvocation = exports.DDP._CurrentMethodInvocation;
292
+ try {
293
+ exports.DDP._CurrentMethodInvocation = invocation;
294
+ const result = maybeAuditArgumentChecks(handler, invocation, (0, ejson_1.clone)(args), "internal call to '" + name + "'");
295
+ resolve(result);
296
+ }
297
+ finally {
298
+ exports.DDP._CurrentMethodInvocation = oldInvocation;
299
+ }
300
+ }).then(ejson_1.clone);
301
+ }
302
+ _urlForSession(sessionId) {
303
+ var self = this;
304
+ var session = self.sessions.get(sessionId);
305
+ if (session)
306
+ return session._socketUrl;
307
+ else
308
+ return null;
309
+ }
310
+ }
311
+ exports.DDPServer = DDPServer;
312
+ // Publication strategies define how we handle data from published cursors at the collection level
313
+ // This allows someone to:
314
+ // - Choose a trade-off between client-server bandwidth and server memory usage
315
+ // - Implement special (non-mongo) collections like volatile message queues
316
+ DDPServer.publicationStrategies = {
317
+ // SERVER_MERGE is the default strategy.
318
+ // When using this strategy, the server maintains a copy of all data a connection is subscribed to.
319
+ // This allows us to only send deltas over multiple publications.
320
+ SERVER_MERGE: {
321
+ useCollectionView: true,
322
+ doAccountingForCollection: true,
323
+ },
324
+ // The NO_MERGE_NO_HISTORY strategy results in the server sending all publication data
325
+ // directly to the client. It does not remember what it has previously sent
326
+ // to it will not trigger removed messages when a subscription is stopped.
327
+ // This should only be chosen for special use cases like send-and-forget queues.
328
+ NO_MERGE_NO_HISTORY: {
329
+ useCollectionView: false,
330
+ doAccountingForCollection: false,
331
+ },
332
+ // NO_MERGE is similar to NO_MERGE_NO_HISTORY but the server will remember the IDs it has
333
+ // sent to the client so it can remove them when a subscription is stopped.
334
+ // This strategy can be used when a collection is only used in a single publication.
335
+ NO_MERGE: {
336
+ useCollectionView: false,
337
+ doAccountingForCollection: true,
338
+ }
339
+ };
340
+ function _calculateVersion(clientSupportedVersions, serverSupportedVersions) {
341
+ var correctVersion = clientSupportedVersions.find(version => serverSupportedVersions.includes(version));
342
+ if (!correctVersion) {
343
+ correctVersion = serverSupportedVersions[0];
344
+ }
345
+ return correctVersion;
346
+ }
347
+ exports._calculateVersion = _calculateVersion;
348
+ ;
349
+ // "blind" exceptions other than those that were deliberately thrown to signal
350
+ // errors to the client
351
+ function wrapInternalException(exception, context) {
352
+ if (!exception)
353
+ return exception;
354
+ // To allow packages to throw errors intended for the client but not have to
355
+ // depend on the Meteor.Error class, `isClientSafe` can be set to true on any
356
+ // error before it is thrown.
357
+ if (exception.isClientSafe) {
358
+ if (!(exception instanceof ClientSafeError)) {
359
+ const originalMessage = exception.message;
360
+ exception = ddpError(exception.error, exception.reason, exception.details);
361
+ exception.message = originalMessage;
362
+ }
363
+ return exception;
364
+ }
365
+ // Did the error contain more details that could have been useful if caught in
366
+ // server code (or if thrown from non-client-originated code), but also
367
+ // provided a "sanitized" version with more context than 500 Internal server
368
+ // error? Use that.
369
+ if (exception.sanitizedError) {
370
+ if (exception.sanitizedError.isClientSafe)
371
+ return exception.sanitizedError;
372
+ }
373
+ return ddpError(500, "Internal server error");
374
+ }
375
+ exports.wrapInternalException = wrapInternalException;
376
+ ;
377
+ // Audit argument checks, if the audit-argument-checks package exists (it is a
378
+ // weak dependency of this package).
379
+ function maybeAuditArgumentChecks(f, context, args, description) {
380
+ args = args || [];
381
+ /*if (Package['audit-argument-checks']) {
382
+ return Match._failIfArgumentsAreNotAllChecked(
383
+ f, context, args, description);
384
+ }*/
385
+ return f.apply(context, args);
386
+ }
387
+ exports.maybeAuditArgumentChecks = maybeAuditArgumentChecks;
388
+ ;
389
+ function ddpError(error, reason, details) {
390
+ return { isClientSafe: true, error, reason, message: (reason ? reason + " " : "") + "[" + error + "]", errorType: "Meteor.Error" };
391
+ }
392
+ exports.ddpError = ddpError;
393
+ class ClientSafeError extends Error {
394
+ constructor(error, reason, details) {
395
+ super((reason ? reason + " " : "") + "[" + error + "]");
396
+ this.error = error;
397
+ this.reason = reason;
398
+ this.details = details;
399
+ this.isClientSafe = true;
400
+ this.errorType = "Meteor.Error";
401
+ }
402
+ }
403
+ exports.ClientSafeError = ClientSafeError;
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MethodInvocation = void 0;
4
+ // Instance name is this because it is usually referred to as this inside a
5
+ // method definition
6
+ /**
7
+ * @summary The state for a single invocation of a method, referenced by this
8
+ * inside a method definition.
9
+ * @param {Object} options
10
+ * @instanceName this
11
+ * @showInstanceName true
12
+ */
13
+ class MethodInvocation {
14
+ constructor(options) {
15
+ // true if we're running not the actual method, but a stub (that is,
16
+ // if we're on a client (which may be a browser, or in the future a
17
+ // server connecting to another server) and presently running a
18
+ // simulation of a server-side method for latency compensation
19
+ // purposes). not currently true except in a client such as a browser,
20
+ // since there's usually no point in running stubs unless you have a
21
+ // zero-latency connection to the user.
22
+ /**
23
+ * @summary Access inside a method invocation. Boolean value, true if this invocation is a stub.
24
+ * @locus Anywhere
25
+ * @name isSimulation
26
+ * @memberOf DDPCommon.MethodInvocation
27
+ * @instance
28
+ * @type {Boolean}
29
+ */
30
+ this.isSimulation = options.isSimulation;
31
+ // used to know when the function apply was called by callAsync
32
+ this._isFromCallAsync = options.isFromCallAsync;
33
+ // current user id
34
+ /**
35
+ * @summary The id of the user that made this method call, or `null` if no user was logged in.
36
+ * @locus Anywhere
37
+ * @name userId
38
+ * @memberOf DDPCommon.MethodInvocation
39
+ * @instance
40
+ */
41
+ this.userId = options.userId;
42
+ // sets current user id in all appropriate server contexts and
43
+ // reruns subscriptions
44
+ this._setUserId = options.setUserId || function () { };
45
+ // On the server, the connection this method call came in on.
46
+ /**
47
+ * @summary Access inside a method invocation. The [connection](#meteor_onconnection) that this method was received on. `null` if the method is not associated with a connection, eg. a server initiated method call. Calls to methods made from a server method which was in turn initiated from the client share the same `connection`.
48
+ * @locus Server
49
+ * @name connection
50
+ * @memberOf DDPCommon.MethodInvocation
51
+ * @instance
52
+ */
53
+ this.connection = options.connection;
54
+ // The seed for randomStream value generation
55
+ this.randomSeed = options.randomSeed;
56
+ // This is set by RandomStream.get; and holds the random stream state
57
+ this.randomStream = null;
58
+ }
59
+ /**
60
+ * @summary Set the logged in user.
61
+ * @locus Server
62
+ * @memberOf DDPCommon.MethodInvocation
63
+ * @instance
64
+ * @param {String | null} userId The value that should be returned by `userId` on this connection.
65
+ */
66
+ setUserId(userId) {
67
+ this.userId = userId;
68
+ this._setUserId(userId);
69
+ }
70
+ }
71
+ exports.MethodInvocation = MethodInvocation;
72
+ ;
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ // RandomStream allows for generation of pseudo-random values, from a seed.
3
+ //
4
+ // We use this for consistent 'random' numbers across the client and server.
5
+ // We want to generate probably-unique IDs on the client, and we ideally want
6
+ // the server to generate the same IDs when it executes the method.
7
+ //
8
+ // For generated values to be the same, we must seed ourselves the same way,
9
+ // and we must keep track of the current state of our pseudo-random generators.
10
+ // We call this state the scope. By default, we use the current DDP method
11
+ // invocation as our scope. DDP now allows the client to specify a randomSeed.
12
+ // If a randomSeed is provided it will be used to seed our random sequences.
13
+ // In this way, client and server method calls will generate the same values.
14
+ //
15
+ // We expose multiple named streams; each stream is independent
16
+ // and is seeded differently (but predictably from the name).
17
+ // By using multiple streams, we support reordering of requests,
18
+ // as long as they occur on different streams.
19
+ //
20
+ // @param options {Optional Object}
21
+ // seed: Array or value - Seed value(s) for the generator.
22
+ // If an array, will be used as-is
23
+ // If a value, will be converted to a single-value array
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.makeRpcSeed = exports.RandomStream = void 0;
26
+ const main_1 = require("../random/main");
27
+ // If omitted, a random array will be used as the seed.
28
+ class RandomStream {
29
+ constructor(options) {
30
+ this.seed = [].concat(options.seed || randomToken());
31
+ this.sequences = Object.create(null);
32
+ }
33
+ // Get a random sequence with the specified name, creating it if does not exist.
34
+ // New sequences are seeded with the seed concatenated with the name.
35
+ // By passing a seed into Random.create, we use the Alea generator.
36
+ _sequence(name) {
37
+ var self = this;
38
+ var sequence = self.sequences[name] || null;
39
+ if (sequence === null) {
40
+ var sequenceSeed = self.seed.concat(name);
41
+ for (var i = 0; i < sequenceSeed.length; i++) {
42
+ if (typeof sequenceSeed[i] === "function") {
43
+ sequenceSeed[i] = sequenceSeed[i]();
44
+ }
45
+ }
46
+ self.sequences[name] = sequence = main_1.Random.createWithSeeds.apply(null, sequenceSeed);
47
+ }
48
+ return sequence;
49
+ }
50
+ // Returns the random stream with the specified name, in the specified
51
+ // scope. If a scope is passed, then we use that to seed a (not
52
+ // cryptographically secure) PRNG using the fast Alea algorithm. If
53
+ // scope is null (or otherwise falsey) then we use a generated seed.
54
+ //
55
+ // However, scope will normally be the current DDP method invocation,
56
+ // so we'll use the stream with the specified name, and we should get
57
+ // consistent values on the client and server sides of a method call.
58
+ static get(scope, name) {
59
+ if (!name) {
60
+ name = "default";
61
+ }
62
+ if (!scope) {
63
+ // There was no scope passed in; the sequence won't actually be
64
+ // reproducible. but make it fast (and not cryptographically
65
+ // secure) anyways, so that the behavior is similar to what you'd
66
+ // get by passing in a scope.
67
+ return main_1.Random.insecure;
68
+ }
69
+ var randomStream = scope.randomStream;
70
+ if (!randomStream) {
71
+ scope.randomStream = randomStream = new RandomStream({
72
+ seed: scope.randomSeed
73
+ });
74
+ }
75
+ return randomStream._sequence(name);
76
+ }
77
+ ;
78
+ }
79
+ exports.RandomStream = RandomStream;
80
+ ;
81
+ // Returns a random string of sufficient length for a random seed.
82
+ // This is a placeholder function; a similar function is planned
83
+ // for Random itself; when that is added we should remove this function,
84
+ // and call Random's randomToken instead.
85
+ function randomToken() {
86
+ return main_1.Random.hexString(20);
87
+ }
88
+ ;
89
+ // Creates a randomSeed for passing to a method call.
90
+ // Note that we take enclosing as an argument,
91
+ // though we expect it to be DDP._CurrentMethodInvocation.get()
92
+ // However, we often evaluate makeRpcSeed lazily, and thus the relevant
93
+ // invocation may not be the one currently in scope.
94
+ // If enclosing is null, we'll use Random and values won't be repeatable.
95
+ function makeRpcSeed(enclosing, methodName) {
96
+ var stream = RandomStream.get(enclosing, '/rpc/' + methodName);
97
+ return stream.hexString(20);
98
+ }
99
+ exports.makeRpcSeed = makeRpcSeed;
100
+ ;
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SessionCollectionView = void 0;
4
+ const diff_1 = require("../diff-sequence/diff");
5
+ const ejson_1 = require("../ejson/ejson");
6
+ const session_document_view_1 = require("./session-document-view");
7
+ /**
8
+ * Represents a client's view of a single collection
9
+ * @param {String} collectionName Name of the collection it represents
10
+ * @param {Object.<String, Function>} sessionCallbacks The callbacks for added, changed, removed
11
+ * @class SessionCollectionView
12
+ */
13
+ class SessionCollectionView {
14
+ constructor(collectionName, callbacks) {
15
+ this.collectionName = collectionName;
16
+ this.callbacks = callbacks;
17
+ this.documents = new Map();
18
+ }
19
+ isEmpty() {
20
+ return this.documents.size === 0;
21
+ }
22
+ diff(previous) {
23
+ diff_1.DiffSequence.diffMaps(previous.documents, this.documents, {
24
+ both: this.diffDocument.bind(this),
25
+ rightOnly: (id, nowDV) => {
26
+ this.callbacks.added(this.collectionName, id, nowDV.getFields());
27
+ },
28
+ leftOnly: (id, prevDV) => {
29
+ this.callbacks.removed(this.collectionName, id);
30
+ }
31
+ });
32
+ }
33
+ diffDocument(id, prevDV, nowDV) {
34
+ const fields = {};
35
+ diff_1.DiffSequence.diffObjects(prevDV.getFields(), nowDV.getFields(), {
36
+ both: (key, prev, now) => {
37
+ if (!(0, ejson_1.equals)(prev, now))
38
+ fields[key] = now;
39
+ },
40
+ rightOnly: (key, now) => {
41
+ fields[key] = now;
42
+ },
43
+ leftOnly: (key, prev) => {
44
+ fields[key] = undefined;
45
+ }
46
+ });
47
+ this.callbacks.changed(this.collectionName, id, fields);
48
+ }
49
+ added(subscriptionHandle, id, fields) {
50
+ var self = this;
51
+ var docView = self.documents.get(id);
52
+ var added = false;
53
+ if (!docView) {
54
+ added = true;
55
+ docView = new session_document_view_1.SessionDocumentView();
56
+ self.documents.set(id, docView);
57
+ }
58
+ docView.existsIn.add(subscriptionHandle);
59
+ var changeCollector = {};
60
+ for (const [key, value] of Object.entries(fields)) {
61
+ docView.changeField(subscriptionHandle, key, value, changeCollector, true);
62
+ }
63
+ if (added)
64
+ self.callbacks.added(self.collectionName, id, changeCollector);
65
+ else
66
+ self.callbacks.changed(self.collectionName, id, changeCollector);
67
+ }
68
+ changed(subscriptionHandle, id, changed) {
69
+ var self = this;
70
+ var changedResult = {};
71
+ var docView = self.documents.get(id);
72
+ if (!docView)
73
+ throw new Error("Could not find element with id " + id + " to change");
74
+ for (const [key, value] of Object.entries(changed)) {
75
+ if (value === undefined)
76
+ docView.clearField(subscriptionHandle, key, changedResult);
77
+ else
78
+ docView.changeField(subscriptionHandle, key, value, changedResult);
79
+ }
80
+ self.callbacks.changed(self.collectionName, id, changedResult);
81
+ }
82
+ removed(subscriptionHandle, id) {
83
+ var self = this;
84
+ var docView = self.documents.get(id);
85
+ if (!docView) {
86
+ var err = new Error("Removed nonexistent document " + id);
87
+ throw err;
88
+ }
89
+ docView.existsIn.delete(subscriptionHandle);
90
+ if (docView.existsIn.size === 0) {
91
+ // it is gone from everyone
92
+ self.callbacks.removed(self.collectionName, id);
93
+ self.documents.delete(id);
94
+ }
95
+ else {
96
+ var changed = {};
97
+ // remove this subscription from every precedence list
98
+ // and record the changes
99
+ docView.dataByKey.forEach((precedenceList, key) => {
100
+ docView.clearField(subscriptionHandle, key, changed);
101
+ });
102
+ self.callbacks.changed(self.collectionName, id, changed);
103
+ }
104
+ }
105
+ }
106
+ exports.SessionCollectionView = SessionCollectionView;