-
Notifications
You must be signed in to change notification settings - Fork 456
/
useragent.js
484 lines (425 loc) · 14.7 KB
/
useragent.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
var hat = require('hat');
var TransformStream = require('stream').Transform;
var async = require('async');
/**
* Provides access to the backend of `instance`.
*
* Create a user agent accessing a share instance
*
* userAgent = new UserAgent(instance)
*
* The user agent exposes the following API to communicate asynchronously with
* the share instances backend.
* - submit (submit)
* - fetch (fetch)
* - subscribe (subscribe)
* - getOps (get ops)
* - query (query)
* - queryFetch (query)
*
*
* Middleware
* ----------
* Each of the API methods also triggers an action (given in brackets) on the
* share instance. This enables middleware to modifiy the requests and results
* By default the request passed to the middleware contains the properties
* - action
* - agent
* - backend
* - collection
* - docName
* The `collection` and `docName` properties are only set if applicable. In
* addition each API method extends the request object with custom properties.
* These are documented with the methods.
*
*
* Filters
* -------
* The documents provided by the `fetch`, `query` and `queryFetch` methods are
* filtered with the share instance's `docFilters`.
*
* instance.filter(function(collection, docName, docData, next) {
* if (docName == "mario") {
* docData.greeting = "It'se me: Mario";
* next();
* } else {
* next("Document not found!");
* }
* });
* userAgent.fetch('people', 'mario', function(error, data) {
* data.greeting; // It'se me
* });
* userAgent.fetch('people', 'peaches', function(error, data) {
* error == "Document not found!";
* });
*
* In a filter `this` is the user agent.
*
* Similarily we can filter the operations that a client can see
*
* instance.filterOps(function(collection, docName, opData, next) {
* if (opData.op == 'cheat')
* next("Not on my watch!");
* else
* next();
* }
* });
*
*/
var UserAgent = function(instance, stream) {
this.instance = instance;
this.backend = instance.backend;
this.stream = stream;
this.sessionId = hat();
this.connectTime = new Date();
};
module.exports = UserAgent;
/**
* Helper to run the filters over some data. Returns an error string on error,
* or nothing on success. Data is modified in place.
*/
UserAgent.prototype._runFilters = function(filters, collection, docName, data, callback) {
var self = this;
async.eachSeries(filters, function(filter, next) {
filter.call(self, collection, docName, data, next);
}, function(error) {
callback(error, error ? null : data);
});
};
UserAgent.prototype.filterDoc = function(collection, docName, data, callback) {
return this._runFilters(this.instance.docFilters, collection, docName, data, callback);
};
UserAgent.prototype.filterOp = function(collection, docName, data, callback) {
return this._runFilters(this.instance.opFilters, collection, docName, data, callback);
};
// This is only used by bulkFetch, but its enough logic that I prefer to
// separate it out.
//
// data is a map from collection name -> doc name -> data.
UserAgent.prototype.filterDocs = function(data, callback) {
var work = 1;
var done = function() {
work--;
if (work === 0 && callback) callback(null, data);
}
for (var cName in data) {
for (var docName in data[cName]) {
work++;
this.filterDoc(cName, docName, data[cName][docName], function(err) {
if (err && callback) {
callback(err);
callback = null;
}
// Clean up call stack
process.nextTick(done);
});
}
}
done();
};
UserAgent.prototype.filterOps = function(collection, docName, ops, callback) {
if (!ops) return callback();
var agent = this;
var i = 0;
(function next(err) {
if (err) return callback(err);
var op = ops[i++];
if (op) {
// Clean up call stack. Would it be better to modulus the iterator and
// only introduce next tick every nth iteration?
process.nextTick(function() {
agent.filterOp(collection, docName, op, next);
});
} else {
callback(null, ops);
}
})();
};
/**
* Builds a request, passes it through the instance's extension stack for the
* action and calls callback with the request.
*/
UserAgent.prototype.trigger = function(action, collection, docName, request, callback) {
if (typeof request === 'function') {
callback = request;
request = {};
}
request.agent = this;
request.action = action;
if (collection) request.collection = collection;
if (docName) request.docName = docName;
request.backend = this.backend;
this.instance._trigger(request, callback);
};
/**
* Fetch current snapshot of a document
*
* Triggers the `fetch` action. The actual fetch is performed with collection
* and docName from the middleware request.
*/
UserAgent.prototype.fetch = function(collection, docName, callback) {
var agent = this;
agent.trigger('fetch', collection, docName, function(err, action) {
if (err) return callback(err);
collection = action.collection;
docName = action.docName;
agent.backend.fetch(collection, docName, function(err, data) {
if (err) return callback(err);
if (data) {
agent.filterDoc(collection, docName, data, callback);
} else {
callback(null, data);
}
});
});
};
var bulkFetchRequestsEmpty = function(requests) {
for (var cName in requests) {
if (requests[cName].length) return false;
}
return true;
};
// requests is a map from collection -> [docName]
UserAgent.prototype.bulkFetch = function(requests, callback) {
var agent = this;
if (bulkFetchRequestsEmpty(requests)) return callback(null, {});
if (this.instance._hasMiddleware('bulk fetch') || !this.instance._hasMiddleware('fetch')) {
agent.trigger('bulk fetch', null, null, {requests:requests}, function(err, action) {
if (err) return callback(err);
requests = action.requests;
agent.backend.bulkFetch(requests, function(err, data) {
if (err) return callback(err);
agent.filterDocs(data, callback);
});
});
} else {
// Could implement this using async...
throw Error('If you have fetch middleware you need to also make bulk fetch middleware');
}
};
/**
* Get all operations on this document with version in [start, end).
*
* Tiggers `get ops` action with requst
* { start: start, end: end }
*/
UserAgent.prototype.getOps = function(collection, docName, start, end, callback) {
var agent = this;
agent.trigger('get ops', collection, docName, {start:start, end:end}, function(err, action) {
if (err) return callback(err);
agent.backend.getOps(action.collection, action.docName, start, end, function(err, results) {
if (err) return callback(err);
agent.filterOps(collection, docName, results, callback);
});
});
};
function OpTransformStream(agent, collection, docName, stream) {
TransformStream.call(this, {objectMode: true});
this.agent = agent;
this.collection = collection;
this.docName = docName;
this.stream = stream;
}
OpTransformStream.prototype = Object.create(TransformStream.prototype);
OpTransformStream.prototype.destroy = function() {
this.stream.destroy();
};
OpTransformStream.prototype._transform = function(data, encoding, callback) {
var filterOpCallback = getFilterOpCallback(this, callback);
this.agent.filterOp(this.collection, this.docName, data, filterOpCallback);
};
function getFilterOpCallback(opTransformStream, callback) {
return function filterOpCallback(err, data) {
opTransformStream.push(err ? {error: err} : data);
callback();
};
}
/**
* Filter the data passed through the stream with `filterOp()`
*
* Returns a new stream that let's us only read these messages from stream wich
* where not filtered by `this.filterOp(collection, docName, message)`. If the
* filter chain calls an error we read a `{error: 'description'}` message from the
* stream.
*/
UserAgent.prototype.wrapOpStream = function(collection, docName, stream) {
var opTransformStream = new OpTransformStream(this, collection, docName, stream);
stream.pipe(opTransformStream);
return opTransformStream;
};
/**
* Apply `wrapOpStream()` to each stream
*
* `streams` is a map `collection -> docName -> stream`. It returns the same map
* with the streams wrapped.
*/
UserAgent.prototype.wrapOpStreams = function(streams) {
for (var cName in streams) {
for (var docName in streams[cName]) {
streams[cName][docName] = this.wrapOpStream(cName, docName, streams[cName][docName]);
}
}
return streams;
};
/**
* Get stream of operations for a document.
*
* On success it resturns a readable stream of operations for this document.
*
* Triggers the `subscribe` action with request
* { version: version }
*/
UserAgent.prototype.subscribe = function(collection, docName, version, callback) {
var agent = this;
agent.trigger('subscribe', collection, docName, {version:version}, function(err, action) {
if (err) return callback(err);
collection = action.collection;
docName = action.docName;
version = action.version;
agent.backend.subscribe(collection, docName, version, function(err, stream) {
callback(err, err ? null : agent.wrapOpStream(collection, docName, stream));
});
});
};
// requests is a map from cName -> docName -> version.
UserAgent.prototype.bulkSubscribe = function(requests, callback) {
var agent = this;
// Use a bulk subscribe to check everything in one go.
agent.trigger('bulk subscribe', null, null, {requests: requests}, function(err, action) {
if (err) return callback(err);
agent.backend.bulkSubscribe(action.requests, function(err, streams) {
callback(err, err ? null : agent.wrapOpStreams(streams));
});
});
};
// DEPRECATED - just call fetch() then subscribe() yourself.
UserAgent.prototype.fetchAndSubscribe = function(collection, docName, callback) {
var agent = this;
agent.trigger('fetch', collection, docName, function(err, action) {
if (err) return callback(err);
agent.trigger('subscribe', action.collection, action.docName, function(err, action) {
if (err) return callback(err);
collection = action.collection;
docName = action.docName;
agent.backend.fetchAndSubscribe(action.collection, action.docName, function(err, data, stream) {
if (err) return callback(err);
agent.filterDoc(collection, docName, data, function (err, data) {
if (err) return callback(err);
var wrappedStream = agent.wrapOpStream(collection, docName, stream);
callback(null, data, wrappedStream);
});
});
});
});
};
/**
* Submits an operation.
*
* On success it returns the version and the operation.
*
* Triggers the `submit` action with request
* { opData: opData, channelPrefix: null }
* and the `after submit` action with the request
* { opData: opData, snapshot: modifiedSnapshot }
*/
UserAgent.prototype.submit = function(collection, docName, opData, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
var agent = this;
agent.trigger('submit', collection, docName, {opData: opData, channelPrefix:null}, function(err, action) {
if (err) return callback(err);
collection = action.collection;
docName = action.docName;
opData = action.opData;
options.channelPrefix = action.channelPrefix;
if (!opData.preValidate) opData.preValidate = agent.instance.preValidate;
if (!opData.validate) opData.validate = agent.instance.validate;
agent.backend.submit(collection, docName, opData, options, function(err, v, ops, snapshot) {
if (err) return callback(err);
agent.trigger('after submit', collection, docName, {opData: opData, snapshot: snapshot}, function(err) {
if (err) return callback(err);
agent.filterOps(collection, docName, ops, function(err, filteredOps) {
if (err) return callback(err);
callback(null, v, filteredOps);
});
});
});
});
};
/** Helper to filter query result sets */
UserAgent.prototype._filterQueryResults = function(collection, results, callback) {
// The filter function is asyncronous. We can run all of the query results in parallel.
var agent = this;
async.each(results, function(data, innerCb) {
agent.filterDoc(collection, data.docName, data, innerCb);
}, function(error) {
callback(error, results);
});
};
/**
* Execute a query and fetch matching documents.
*
* The result is an array of the matching documents. Each document has in
* addtion the `docName` property set to its name.
*
* Triggers the `query` action with the request
* { query: query, fetch: true, options: options }
*/
UserAgent.prototype.queryFetch = function(collection, query, options, callback) {
var agent = this;
// Should we emit 'query' or 'query fetch' here?
agent.trigger('query', collection, null, {query:query, fetch:true, options: options}, function(err, action) {
if (err) return callback(err);
collection = action.collection;
query = action.query;
agent.backend.queryFetch(collection, query, options, function(err, results, extra) {
if (err) return callback(err);
agent._filterQueryResults(collection, results, function(err, results) {
if (err) return callback(err);
callback(null, results, extra);
});
});
});
};
/**
* Get an QueryEmitter for the query
*
* The returned emitter fires 'diff' event every time the result of the query
* changes.
*
* Triggers the `query` action with the request
* { query: query, options: options }
*/
UserAgent.prototype.query = function(collection, query, options, callback) {
var agent = this;
agent.trigger('query', collection, null, {query: query, options: options}, function(err, action) {
if (err) return callback(err);
collection = action.collection;
query = action.query;
agent.backend.query(collection, query, options, function(err, emitter, results, extra) {
if (err) return callback(err);
// Override emitDiff to filter all inserted items
emitter.emitDiff = function(diff) {
async.each(diff, function(item, cb) {
if (item.type === 'insert') {
agent._filterQueryResults(collection, item.values, cb);
return;
}
cb();
}, function(err) {
if (err) return emitter.emitError(err);
emitter.onDiff(diff);
});
};
// TODO: This is buggy. If the emitter emits a diff during a slow piece of
// middleware, it'll be lost.
agent._filterQueryResults(collection, results, function(err, results) {
// Also if there's an error here, the emitter is never removed.
if (err) return callback(err);
callback(null, emitter, results, extra);
});
});
});
};