-
Notifications
You must be signed in to change notification settings - Fork 76
/
stream.js
415 lines (371 loc) · 10.5 KB
/
stream.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
'use strict'
/** @module stream */
// NOTE: Although implemented in a separate module, streaming shares internal
// responsibilities with both Client and HTTP interfaces, such as updating last
// seen transaction timestamp. Therefore, this implementation
// sometimes breaks encapsulation and calls internal getters and methods. As a
// general rule: it's okay to call internal methods. You can interpret this
// as calling for a package visible method in languages with fine-grained
// visibility control. However, DO NOT change any internal state from outside of
// its context as it'd most certainly lead to errors.
require('abort-controller/polyfill')
var RequestResult = require('./RequestResult')
var errors = require('./errors')
var json = require('./_json')
var http = require('./_http')
var q = require('./query')
var util = require('./_util')
var DefaultEvents = ['start', 'error', 'version', 'history_rewrite']
var DocumentStreamEvents = DefaultEvents.concat(['snapshot'])
/**
* The internal stream client interface. This class handles the network side of
* a stream subscription.
*
* @constructor
* @param {Client} client The FaunaDB client.
* @param {module:query~ExprArg} expression The FQL expression you are subscribing to.
* @param {module:stream~Options} options The stream options.
* @param {function} onEvent The stream event's callback function.
* @private
*/
function StreamClient(client, expression, options, onEvent) {
options = util.applyDefaults(options, {
fields: null,
})
this._client = client
this._onEvent = onEvent
this._query = q.wrap(expression)
this._urlParams = options.fields ? { fields: options.fields.join(',') } : null
this._abort = new AbortController()
this._state = 'idle'
}
/**
* Takes a snapshot of the current query. Assumes the subscribed query returns a
* reference.
*/
StreamClient.prototype.snapshot = function() {
var self = this
self._client
.query(q.Get(self._query))
.then(function(doc) {
self._onEvent({
type: 'snapshot',
event: doc,
})
})
.catch(function(error) {
self._onEvent({
type: 'error',
event: error,
})
})
}
/** Initiates the stream subscription. */
StreamClient.prototype.subscribe = function() {
var self = this
if (self._state === 'idle') {
self._state = 'open'
} else {
throw new Error(
'Subscription#start should not be called several times, ' +
'consider instantiating a new stream instead.'
)
}
var body = JSON.stringify(self._query)
var startTime = Date.now()
var buffer = ''
function onResponse(response) {
var endTime = Date.now()
var parsed
try {
parsed = json.parseJSON(response.body)
} catch (_) {
parsed = response.body
}
var result = new RequestResult(
'POST',
'stream',
self._urlParams,
body,
self._query,
response.body,
parsed,
response.status,
response.headers,
startTime,
endTime
)
self._client._handleRequestResult(response, result)
}
function onData(data) {
var result = json.parseJSONStreaming(buffer + data)
buffer = result.buffer
result.values.forEach(function(event) {
if (event.txn !== undefined) {
self._client.syncLastTxnTime(event.txn)
}
if (event.event === 'error') {
onError(new errors.StreamErrorEvent(event))
} else {
self._onEvent(event)
}
})
}
function onError(error) {
// AbortError is triggered as result of calling
// close() on a Subscription. There's no need to relay this event back up.
if (error instanceof http.AbortError) {
return
}
self._onEvent({
type: 'error',
event: error,
})
}
self._client._http
.execute({
method: 'POST',
path: 'stream',
body: body,
query: self._urlParams,
signal: this._abort.signal,
streamConsumer: {
onError: onError,
onData: onData,
},
})
.then(onResponse)
.catch(onError)
}
/** Closes the stream subscription by aborting its underlying http request. */
StreamClient.prototype.close = function() {
if (this._state !== 'closed') {
this._state = 'closed'
this._abort.abort()
}
}
/**
* Event dispatch interface for stream subscription.
*
* @constructor
* @param {string[]} allowedEvents List of allowed events.
* @private
*/
function EventDispatcher(allowedEvents) {
this._allowedEvents = allowedEvents
this._listeners = {}
}
/** Subscribe to an event
*
* @param {string} type The event type.
* @param {module:stream~Subscription~eventCalllback} callback
* The event's callback.
*/
EventDispatcher.prototype.on = function(type, callback) {
if (this._allowedEvents.indexOf(type) === -1) {
throw new Error('Unknown event type: ' + type)
}
if (this._listeners[type] === undefined) {
this._listeners[type] = []
}
this._listeners[type].push(callback)
}
/**
* Dispatch the given event to the appropriate listeners.
*
* @param {Object} event The event.
*/
EventDispatcher.prototype.dispatch = function(event) {
var listeners = this._listeners[event.type]
if (!listeners) {
return
}
for (var i = 0; i < listeners.length; i++) {
listeners[i].call(null, event.event, event)
}
}
/**
* Stream's start event. A stream subscription always begins with a start event.
* Upcoming events are guaranteed to have transaction timestamps equal to or greater than
* the stream's start timestamp.
*
* @event module:stream~Subscription#start
* @type {object}
* @property {string} type='start'
* The event type.
* @property {number} txn
* The event's transaction timestamp.
* @property {module:number} event
* The stream start timestamp.
*/
/**
* A version event occurs upon any modifications to the current state of the
* subscribed document.
*
* @event module:stream~Subscription#version
* @type {object}
* @property {string} type='version'
* The event type.
* @property {number} txn
* The event's transaction timestamp.
* @property {object} event
* The event's data.
*/
/**
* A history rewrite event occurs upon any modifications to the history of the
* subscribed document.
*
* @event module:stream~Subscription#history_rewrite
* @type {object}
* @property {string} type='history_rewrite'
* The event type.
* @property {number} txn
* The event's transaction timestamp.
* @property {object} event
* The event's data.
*/
/**
* A snapshot event. A snapshot event is fired once the `document` stream helper
* finishes loading the subscribed document's snapshot data. See {@link
* Client#stream} for more details on the `document` stream helper.
*
* @event module:stream~Subscription#snapshot
* @type {object}
* @property {string} type='snapshot'
* The event type.
* @property {number} txn
* The event's transaction timestamp.
* @property {object} event
* The event's data.
*/
/**
* An error event is fired both for client and server errors that may occur as
* a result of a subscription.
*
* @event module:stream~Subscription#error
* @type {object}
* @property {string} type='error'
* The event type.
* @property {?number} txn
* The event's transaction timestamp.
* @property {Error} event
* The underlying error.
*/
/**
* @typedef {Object} Options
* @property {string[]} [fields=['action', 'document', 'diff', 'prev']]
* The fields event fields to opt-in during stream subscription. Possible
* options:
* * 'action': The action type
* * 'document': The document's data
* * 'diff': The difference between 'document' and 'prev'
* * 'prev': The event's previous data
*/
/**
* The callback to be executed when an new event occurs.
*
* @callback module:stream~Subscription~eventCalllback
* @param {any} data The event's data field.
* @param {object} event The event's entire object.
*/
/**
* A stream subscription which dispatches events received to the registered
* listener functions. This class must be constructed via {@link Client#stream}
* method.
*
* @constructor
* @param {StreamClient} client
* Internal stream client interface.
* @param {EventDispatcher} dispatcher
* Internal event dispatcher interface.
*/
function Subscription(client, dispatcher) {
this._client = client
this._dispatcher = dispatcher
}
/**
* Subscribes to an event type.
*
* @param {string} event
* The event's type.
* @param {module:stream~Subscription~eventCalllback} callback
* A callback function.
*
* @returns {module:stream~Subscription} This instance.
*/
Subscription.prototype.on = function(type, callback) {
this._dispatcher.on(type, callback)
return this
}
/**
* Initiates the underlying subscription network calls.
* @returns {module:stream~Subscription} This instance.
*/
Subscription.prototype.start = function() {
this._client.subscribe()
return this
}
/**
* Stops the current subscription and closes the underlying network connection.
*/
Subscription.prototype.close = function() {
this._client.close()
}
/**
* Stream API factory function. See {@link Client#stream} for details on how to
* use stream's public interface.
* @private
*/
function StreamAPI(client) {
var api = function(expression, options) {
var dispatcher = new EventDispatcher(DefaultEvents)
var streamClient = new StreamClient(client, expression, options, function(
event
) {
dispatcher.dispatch(event)
})
return new Subscription(streamClient, dispatcher)
}
api.document = function(expression, options) {
var buffer = []
var buffering = true
var dispatcher = new EventDispatcher(DocumentStreamEvents)
var streamClient = new StreamClient(client, expression, options, onEvent)
function onEvent(event) {
switch (event.type) {
case 'start':
dispatcher.dispatch(event)
streamClient.snapshot()
break
case 'snapshot':
resume(event)
break
case 'error':
dispatcher.dispatch(event)
break
default:
if (buffering) {
buffer.push(event)
} else {
dispatcher.dispatch(event)
}
}
}
function resume(snapshotEvent) {
dispatcher.dispatch(snapshotEvent)
for (var i = 0; i < buffer.length; i++) {
var bufferedEvent = buffer[i]
if (bufferedEvent.txn > snapshotEvent.event.ts) {
dispatcher.dispatch(bufferedEvent)
}
}
buffering = false
buffer = null
}
return new Subscription(streamClient, dispatcher)
}
return api
}
module.exports = {
StreamAPI: StreamAPI,
}