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