/
watch.js
2488 lines (2232 loc) · 80.1 KB
/
watch.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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
import assert from 'power-assert';
import duplexify from 'duplexify';
import is from 'is';
import through2 from 'through2';
import {Firestore} from '../src/index';
import {DocumentSnapshot} from '../src/document';
import {setTimeoutHandler} from '../src/backoff';
import {createInstance} from '../test/util/helpers';
// Change the argument to 'console.log' to enable debug output.
Firestore.setLogFunction(() => {});
let PROJECT_ID = process.env.PROJECT_ID;
if (!PROJECT_ID) {
PROJECT_ID = 'test-project';
}
/**
* Asserts that the given list of docs match.
* @param actual The computed docs array.
* @param expected The expected docs array.
*/
const docsEqual = function(actual, expected) {
assert.equal(actual.length, expected.length);
for (let i = 0; i < actual.size; i++) {
assert.equal(actual[i].ref.id, expected[i].ref.id);
assert.deepStrictEqual(actual[i].data(), expected[i].data());
assert.ok(is.string(expected[i].createTime));
assert.ok(is.string(expected[i].updateTime));
}
};
/**
* Asserts that the given query snapshot matches the expected results.
* @param lastSnapshot The previous snapshot that this snapshot is based upon.
* @param version The current snapshot version to use for the comparison.
* @param actual A QuerySnapshot with results.
* @param expected Array of DocumentSnapshot.
*/
const snapshotsEqual = function(lastSnapshot, version, actual, expected) {
let localDocs = [].concat(lastSnapshot.docs);
assert.equal(actual.docChanges.length, expected.docChanges.length);
for (let i = 0; i < expected.docChanges.length; i++) {
assert.equal(actual.docChanges[i].type, expected.docChanges[i].type);
assert.equal(
actual.docChanges[i].doc.ref.id, expected.docChanges[i].doc.ref.id);
assert.deepStrictEqual(
actual.docChanges[i].doc.data(), expected.docChanges[i].doc.data());
let readVersion =
actual.docChanges[i].type === 'removed' ? version - 1 : version;
assert.ok(actual.docChanges[i].doc.readTime.isEqual(
new Firestore.Timestamp(0, readVersion)));
if (actual.docChanges[i].oldIndex !== -1) {
localDocs.splice(actual.docChanges[i].oldIndex, 1);
}
if (actual.docChanges[i].newIndex !== -1) {
localDocs.splice(
actual.docChanges[i].newIndex, 0, actual.docChanges[i].doc);
}
}
docsEqual(actual.docs, expected.docs);
docsEqual(localDocs, expected.docs);
assert.ok(actual.readTime.isEqual(new Firestore.Timestamp(0, version)));
assert.equal(actual.size, expected.docs.length);
return {docs: actual.docs, docChanges: actual.docChanges};
};
/*
* Helper for constructing a snapshot.
*/
const snapshot = function(ref, data) {
const snapshot = new DocumentSnapshot.Builder();
snapshot.ref = ref;
snapshot.fieldsProto = ref.firestore._serializer.encodeFields(data);
snapshot.readTime = new Firestore.Timestamp(0, 0);
snapshot.createTime = new Firestore.Timestamp(0, 0);
snapshot.updateTime = new Firestore.Timestamp(0, 0);
return snapshot.build();
};
/*
* Helpers for constructing document changes.
*/
const docChange = function(type, ref, data) {
return {
type: type,
doc: snapshot(ref, data),
};
};
const added = (ref, data) => docChange('added', ref, data);
const modified = (ref, data) => docChange('modified', ref, data);
const removed = (ref, data) => docChange('removed', ref, data);
const EMPTY = {
docs: [],
docChanges: []
};
/** Captures stream data and makes it available via deferred Promises. */
class DeferredListener {
constructor() {
this.pendingData = [];
this.pendingListeners = [];
}
/**
* Makes stream data available via the Promises set in the 'await' call. If no
* Promise has been set, the data will be cached.
*/
on(type, data) {
let listener = this.pendingListeners.shift();
if (listener) {
assert.equal(
listener.type, type,
`Expected message of type '${listener.type}' but got '${type}' ` +
`with '${JSON.stringify(data)}'.`);
listener.resolve(data);
} else {
this.pendingData.push({
type: type,
data: data,
});
}
}
/**
* Returns a Promise with the next result from the underlying stream. The
* Promise resolves immediately if pending data is available, otherwise it
* resolves when the next chunk arrives.
*/
await(expectedType) {
let data = this.pendingData.shift();
if (data) {
assert.equal(
data.type, expectedType,
`Expected message of type '${expectedType}' but got '${data.type}' ` +
`with '${JSON.stringify(data.data)}'.`);
return Promise.resolve(data.data);
}
return new Promise(resolve => this.pendingListeners.push({
type: expectedType,
resolve: resolve,
}));
}
}
/**
* Handles stream operations for the Firestore Listen API. StreamHelper
* supports one stream at a time, but multiple streams can be processed through
* sequential invocations of the Listen API.
*/
class StreamHelper {
constructor() {
this.streamCount = 0;
this.deferredListener = new DeferredListener();
}
/** Returns the GAPIC callback to use with this stream helper. */
getListenCallback() {
return () => {
// Create a mock backend whose stream we can return.
++this.streamCount;
this.readStream = through2.obj();
this.writeStream = through2.obj();
this.readStream.once(
'data', result => this.deferredListener.on('data', result));
this.readStream.on(
'error', error => this.deferredListener.on('error', error));
this.readStream.on('end', () => this.deferredListener.on('end'));
this.readStream.on('close', () => this.deferredListener.on('close'));
this.deferredListener.on('open', {});
this.backendStream = duplexify.obj(this.readStream, this.writeStream);
return this.backendStream;
};
}
/**
* Returns a Promise with the next results from the underlying stream.
*/
await(type) {
return this.deferredListener.await(type);
}
/** Waits for a destroyed stream to be re-opened. */
awaitReopen() {
return this.await('error')
.then(() => this.await('close'))
.then(() => this.awaitOpen());
}
/**
* Waits for the stream to open and to receive its first message (the
* AddTarget message).
*/
awaitOpen() {
return this.await('open').then(() => this.await('data'));
}
/**
* Sends a message to the currently active stream.
*/
write(data) {
this.writeStream.write(data);
}
/**
* Closes the currently active stream.
*/
close() {
this.backendStream.emit('end');
}
/**
* Destroys the currently active stream with the optionally provided error.
* If omitted, the stream is closed with a GRPC Status of UNAVAILABLE.
*/
destroyStream(err) {
if (!err) {
err = new Error('Server disconnect');
err.code = 14; // Unavailable
}
this.readStream.destroy(err);
}
}
/**
* Encapsulates the stream logic for the Watch API.
*/
class WatchHelper {
/**
* @param streamHelper The StreamHelper base class for this Watch operation.
* @param reference The CollectionReference or DocumentReference that is being
* watched.
* @param targetId The target ID of the watch stream.
*/
constructor(streamHelper, reference, targetId) {
this.reference = reference;
this.serializer = reference.firestore._serializer;
this.streamHelper = streamHelper;
this.targetId = targetId;
this.snapshotVersion = 0;
this.deferredListener = new DeferredListener();
}
/**
* Returns a Promise with the next result from the underlying stream.
*/
await(type) {
return this.deferredListener.await(type);
}
/**
* Creates a watch, starts a listen, and asserts that the request got
* processed.
*
* @return The unsubscribe handler for the listener.
*/
startWatch() {
this.unsubscribe = this.reference.onSnapshot(
snapshot => {
this.deferredListener.on('snapshot', snapshot);
},
error => {
this.deferredListener.on('error', error);
});
return this.unsubscribe;
}
/**
* Ends the listen stream.
*
* @return A Promise that will be fulfilled when the backend saw the end.
*/
endWatch() {
this.unsubscribe();
return this.streamHelper.await('end');
}
/**
* Sends a target change from the backend simulating adding the query target.
*
* @param {number=} targetId The target ID to send. If omitted, uses the
* default target ID.
*/
sendAddTarget(targetId) {
this.streamHelper.write({
targetChange: {
targetChangeType: 'ADD',
targetIds: [targetId !== undefined ? targetId : this.targetId],
},
});
}
/**
* Sends a target change from the backend simulating removing a query target.
*
* @param {number} cause The optional code indicating why the target was removed.
*/
sendRemoveTarget(cause) {
const proto = {
targetChange: {
targetChangeType: 'REMOVE',
targetIds: [this.targetId],
},
};
if (cause) {
proto.targetChange.cause = {
code: cause,
message: 'test remove',
};
}
this.streamHelper.write(proto);
}
/**
* Sends a target change from the backend of type 'NO_CHANGE'. If specified,
* includes a resume token.
*/
sendSnapshot(version, resumeToken) {
this.snapshotVersion = version;
let proto = {
targetChange: {
targetChangeType: 'NO_CHANGE',
targetIds: [],
readTime: {seconds: 0, nanos: version},
},
};
if (resumeToken) {
proto.targetChange.resumeToken = resumeToken;
}
this.streamHelper.write(proto);
}
/**
* Sends a target change from the backend of type 'CURRENT'.
*/
sendCurrent(resumeToken) {
let proto = {
targetChange: {
targetChangeType: 'CURRENT',
targetIds: [this.targetId],
},
};
if (resumeToken) {
proto.targetChange.resumeToken = resumeToken;
}
this.streamHelper.write(proto);
}
/**
* Sends a doc change from the backend to the client.
*
* @param ref The document reference.
* @param data The data for the doc in proto JSON format.
*/
sendDoc(ref, data) {
this.streamHelper.write({
documentChange: {
document: {
name: ref.formattedName,
fields: this.serializer.encodeFields(data),
createTime: {seconds: 1, nanos: 2},
updateTime: {seconds: 3, nanos: this.snapshotVersion},
},
targetIds: [this.targetId],
},
});
}
/**
* Sends a doc removal from the backend to the client.
*
* @param ref The document reference.
* @param data The data for the doc in proto JSON format.
*/
sendDocRemove(ref, data) {
this.streamHelper.write({
documentChange: {
document: {
name: ref.formattedName,
fields: this.serializer.encodeFields(data),
},
removedTargetIds: [this.targetId],
},
});
}
/**
* Sends a doc delete from the backend to the client.
*
* @param ref The document reference.
*/
sendDocDelete(ref) {
this.streamHelper.write({
documentDelete: {
document: ref.formattedName,
removedTargetIds: [this.targetId],
},
});
}
/**
* A wrapper for writing tests that successfully run a watch.
*/
runTest(expectedRequest, func) {
this.startWatch();
return this.streamHelper.awaitOpen()
.then(request => {
assert.deepStrictEqual(request, expectedRequest);
return func();
})
.then(() => {
return this.endWatch();
});
}
/**
* A wrapper for writing tests that fail to run a watch.
*/
runFailedTest(expectedRequest, func, expectedError) {
this.startWatch();
return this.streamHelper.awaitOpen()
.then(request => {
assert.deepStrictEqual(request, expectedRequest);
return func();
})
.then(() => {
return this.await('error');
})
.then(err => {
assert.equal(err.message, expectedError);
});
}
}
describe('Query watch', function() {
// The collection to query.
let colRef;
// The documents used in this query.
let doc1, doc2, doc3, doc4;
let firestore;
let targetId;
let watchHelper;
let streamHelper;
let lastSnapshot;
// The proto JSON that should be sent for the query.
const collQueryJSON = () => {
return {
database: `projects/${PROJECT_ID}/databases/(default)`,
addTarget: {
query: {
parent: `projects/${PROJECT_ID}/databases/(default)`,
structuredQuery: {
from: [{collectionId: 'col'}],
},
},
targetId: targetId,
},
};
};
const includeQuery = () => {
return colRef.where('included', '==', 'yes');
};
// The proto JSON that should be sent for the query.
const includeQueryJSON = () => {
return {
database: `projects/${PROJECT_ID}/databases/(default)`,
addTarget: {
query: {
parent: `projects/${PROJECT_ID}/databases/(default)`,
structuredQuery: {
from: [{collectionId: 'col'}],
where: {
fieldFilter: {
field: {
fieldPath: 'included',
},
op: 'EQUAL',
value: {
stringValue: 'yes',
},
},
},
},
},
targetId: targetId,
},
};
};
// The proto JSON that should be sent for a resumed query.
const resumeTokenQuery = resumeToken => {
return {
database: `projects/${PROJECT_ID}/databases/(default)`,
addTarget: {
query: {
parent: `projects/${PROJECT_ID}/databases/(default)`,
structuredQuery: {
from: [{collectionId: 'col'}],
},
},
targetId: targetId,
resumeToken: resumeToken,
},
};
};
const sortedQuery = () => {
return colRef.orderBy('foo', 'desc');
};
// The proto JSON that should be sent for the query.
const sortedQueryJSON = () => {
return {
database: `projects/${PROJECT_ID}/databases/(default)`,
addTarget: {
query: {
parent: `projects/${PROJECT_ID}/databases/(default)`,
structuredQuery: {
from: [{collectionId: 'col'}],
orderBy: [{direction: 'DESCENDING', field: {fieldPath: 'foo'}}],
},
},
targetId: targetId,
},
};
};
/** The GAPIC callback that executes the listen. */
let listenCallback;
beforeEach(function() {
// We are intentionally skipping the delays to ensure fast test execution.
// The retry semantics are uneffected by this, as we maintain their
// asynchronous behavior.
setTimeoutHandler(setImmediate);
targetId = 0x1;
streamHelper = new StreamHelper();
listenCallback = streamHelper.getListenCallback();
return createInstance({listen: () => listenCallback()})
.then(firestoreClient => {
firestore = firestoreClient;
watchHelper = new WatchHelper(
streamHelper, firestore.collection('col'), targetId);
colRef = firestore.collection('col');
doc1 = firestore.doc('col/doc1');
doc2 = firestore.doc('col/doc2');
doc3 = firestore.doc('col/doc3');
doc4 = firestore.doc('col/doc4');
lastSnapshot = EMPTY;
});
});
afterEach(function() {
setTimeoutHandler(setTimeout);
});
it('with invalid callbacks', function() {
assert.throws(() => {
colRef.onSnapshot('foo');
}, /Argument "onNext" is not a valid function./);
assert.throws(() => {
colRef.onSnapshot(() => {}, 'foo');
}, /Argument "onError" is not a valid function./);
});
it('without error callback', function(done) {
let unsubscribe = colRef.onSnapshot(() => {
unsubscribe();
done();
});
streamHelper.awaitOpen().then(() => {
watchHelper.sendAddTarget();
watchHelper.sendCurrent();
watchHelper.sendSnapshot(1);
});
});
it('handles invalid listen protos', function() {
return watchHelper.runFailedTest(collQueryJSON(), () => {
// Mock the server responding to the query with an invalid proto.
streamHelper.write({invalid: true});
}, 'Unknown listen response type: {"invalid":true}');
});
it('handles invalid target change protos', function() {
return watchHelper.runFailedTest(
collQueryJSON(),
() => {
// Mock the server responding to the query with an invalid proto.
streamHelper.write({
targetChange: {
targetChangeType: 'INVALID',
targetIds: [0xfeed],
},
});
},
'Unknown target change type: {"targetChangeType":"INVALID",' +
'"targetIds":[65261]}');
});
it('handles remove target change protos', function() {
return watchHelper.runFailedTest(collQueryJSON(), () => {
watchHelper.sendRemoveTarget();
}, 'Error 13: internal error');
});
it('handles remove target change with code', function() {
return watchHelper.runFailedTest(collQueryJSON(), () => {
watchHelper.sendRemoveTarget(7);
}, 'Error 7: test remove');
});
it('rejects an unknown target', function() {
return watchHelper.runFailedTest(collQueryJSON(), () => {
watchHelper.sendAddTarget(2);
}, 'Unexpected target ID sent by server');
});
it('re-opens on unexpected stream end', function() {
return watchHelper.runTest(collQueryJSON(), () => {
watchHelper.sendAddTarget();
watchHelper.sendCurrent();
watchHelper.sendSnapshot(1, [0xabcd]);
return watchHelper.await('snapshot')
.then(() => {
streamHelper.close();
return streamHelper.await('end');
})
.then(() => {
return streamHelper.awaitOpen();
})
.then(() => {
streamHelper.close();
return streamHelper.await('end');
})
.then(() => {
return streamHelper.awaitOpen();
})
.then(() => {
assert.equal(streamHelper.streamCount, 3);
});
});
});
it('doesn\'t re-open inactive stream', function() {
// This test uses the normal timeout handler since it relies on the actual
// backoff window during the the stream recovery. We then use this window to
// unsubscribe from the Watch stream and make sure that we don't
// re-open the stream once the backoff expires.
setTimeoutHandler(setTimeout);
const unsubscribe = watchHelper.startWatch();
return streamHelper.awaitOpen()
.then(request => {
assert.deepStrictEqual(request, collQueryJSON());
watchHelper.sendAddTarget();
watchHelper.sendCurrent();
watchHelper.sendSnapshot(1, [0xabcd]);
return watchHelper.await('snapshot');
})
.then(() => {
streamHelper.close();
return streamHelper.await('end');
})
.then(() => {
unsubscribe();
assert.equal(streamHelper.streamCount, 1);
});
});
it('retries based on error code', function() {
const expectRetry = {
/* Cancelled */ 1: true,
/* Unknown */ 2: true,
/* InvalidArgument */ 3: false,
/* DeadlineExceeded */ 4: true,
/* NotFound */ 5: false,
/* AlreadyExists */ 6: false,
/* PermissionDenied */ 7: false,
/* ResourceExhausted */ 8: true,
/* FailedPrecondition */ 9: false,
/* Aborted */ 10: false,
/* OutOfRange */ 11: false,
/* Unimplemented */ 12: false,
/* Internal */ 13: true,
/* Unavailable */ 14: true,
/* DataLoss */ 15: false,
/* Unauthenticated */ 16: true,
};
let result = Promise.resolve();
for (const statusCode in expectRetry) {
if (expectRetry.hasOwnProperty(statusCode)) {
result = result.then(() => {
const err = new Error('GRPC Error');
err.code = Number(statusCode);
if (expectRetry[statusCode]) {
return watchHelper.runTest(collQueryJSON(), () => {
watchHelper.sendAddTarget();
watchHelper.sendCurrent();
watchHelper.sendSnapshot(1, [0xabcd]);
return watchHelper.await('snapshot').then(() => {
streamHelper.destroyStream(err);
return streamHelper.awaitReopen();
});
});
} else {
return watchHelper.runFailedTest(collQueryJSON(), () => {
watchHelper.sendAddTarget();
watchHelper.sendCurrent();
watchHelper.sendSnapshot(1, [0xabcd]);
return watchHelper.await('snapshot')
.then(() => {
streamHelper.destroyStream(err);
})
.then(() => {
return streamHelper.await('error');
})
.then(() => {
return streamHelper.await('close');
});
}, 'GRPC Error');
}
});
}
}
return result;
});
it('retries with unknown code', function() {
return watchHelper.runTest(collQueryJSON(), () => {
watchHelper.sendAddTarget();
watchHelper.sendCurrent();
watchHelper.sendSnapshot(1, [0xabcd]);
return watchHelper.await('snapshot').then(() => {
streamHelper.destroyStream(new Error('Unknown'));
return streamHelper.awaitReopen();
});
});
});
it('handles changing a doc', function() {
return watchHelper.runTest(collQueryJSON(), () => {
// Mock the server responding to the query.
watchHelper.sendAddTarget();
watchHelper.sendCurrent();
watchHelper.sendSnapshot(1);
return watchHelper.await('snapshot')
.then(results => {
lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY);
// Add a result.
watchHelper.sendDoc(doc1, {foo: 'a'});
watchHelper.sendSnapshot(2);
return watchHelper.await('snapshot');
})
.then(results => {
lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, {
docs: [snapshot(doc1, {foo: 'a'})],
docChanges: [added(doc1, {foo: 'a'})],
});
// Add another result.
watchHelper.sendDoc(doc2, {foo: 'b'});
watchHelper.sendSnapshot(3);
return watchHelper.await('snapshot');
})
.then(results => {
lastSnapshot = snapshotsEqual(lastSnapshot, 3, results, {
docs: [snapshot(doc1, {foo: 'a'}), snapshot(doc2, {foo: 'b'})],
docChanges: [added(doc2, {foo: 'b'})],
});
// Change a result.
watchHelper.sendDoc(doc2, {bar: 'c'});
watchHelper.sendSnapshot(4);
return watchHelper.await('snapshot');
})
.then(results => {
snapshotsEqual(lastSnapshot, 4, results, {
docs: [snapshot(doc1, {foo: 'a'}), snapshot(doc2, {bar: 'c'})],
docChanges: [modified(doc2, {bar: 'c'})],
});
});
});
});
it('reconnects after error', function() {
let resumeToken = [0xabcd];
return watchHelper.runTest(collQueryJSON(), () => {
// Mock the server responding to the query.
watchHelper.sendAddTarget();
watchHelper.sendCurrent(resumeToken);
watchHelper.sendSnapshot(1);
return watchHelper.await('snapshot')
.then(results => {
lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY);
// Add a result.
watchHelper.sendDoc(doc1, {foo: 'a'});
watchHelper.sendSnapshot(2, resumeToken);
return watchHelper.await('snapshot');
})
.then(results => {
lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, {
docs: [snapshot(doc1, {foo: 'a'})],
docChanges: [added(doc1, {foo: 'a'})],
});
assert.equal(1, streamHelper.streamCount);
streamHelper.destroyStream();
return streamHelper.awaitReopen();
})
.then(request => {
assert.deepStrictEqual(request, resumeTokenQuery(resumeToken));
watchHelper.sendAddTarget();
watchHelper.sendDoc(doc2, {foo: 'b'});
resumeToken = [0xbcde];
watchHelper.sendSnapshot(3, resumeToken);
return watchHelper.await('snapshot');
})
.then(results => {
lastSnapshot = snapshotsEqual(lastSnapshot, 3, results, {
docs: [snapshot(doc1, {foo: 'a'}), snapshot(doc2, {foo: 'b'})],
docChanges: [added(doc2, {foo: 'b'})],
});
streamHelper.destroyStream();
return streamHelper.awaitReopen();
})
.then(request => {
assert.deepStrictEqual(request, resumeTokenQuery(resumeToken));
watchHelper.sendAddTarget();
watchHelper.sendDoc(doc3, {foo: 'c'});
watchHelper.sendSnapshot(4, resumeToken);
return watchHelper.await('snapshot');
})
.then(results => {
assert.equal(3, streamHelper.streamCount);
snapshotsEqual(lastSnapshot, 4, results, {
docs: [
snapshot(doc1, {foo: 'a'}),
snapshot(doc2, {foo: 'b'}),
snapshot(doc3, {foo: 'c'}),
],
docChanges: [added(doc3, {foo: 'c'})],
});
});
});
});
it('ignores changes sent after the last snapshot', function() {
return watchHelper.runTest(collQueryJSON(), () => {
// Mock the server responding to the query.
watchHelper.sendAddTarget();
watchHelper.sendCurrent([0x0]);
watchHelper.sendSnapshot(1);
return watchHelper.await('snapshot')
.then(results => {
lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY);
// Add a result.
watchHelper.sendDoc(doc1, {foo: 'a'});
watchHelper.sendDoc(doc2, {foo: 'b'});
watchHelper.sendSnapshot(2, [0x1]);
return watchHelper.await('snapshot');
})
.then(results => {
lastSnapshot = snapshotsEqual(lastSnapshot, 2, results, {
docs: [snapshot(doc1, {foo: 'a'}), snapshot(doc2, {foo: 'b'})],
docChanges: [added(doc1, {foo: 'a'}), added(doc2, {foo: 'b'})],
});
assert.equal(1, streamHelper.streamCount);
// This document delete will be ignored.
watchHelper.sendDocDelete(doc1);
streamHelper.destroyStream();
return streamHelper.awaitReopen();
})
.then(() => {
watchHelper.sendDocDelete(doc2);
watchHelper.sendSnapshot(3, [0x2]);
return watchHelper.await('snapshot');
})
.then(results => {
lastSnapshot = snapshotsEqual(lastSnapshot, 3, results, {
docs: [snapshot(doc1, {foo: 'a'})],
docChanges: [removed(doc2, {foo: 'b'})],
});
});
});
});
it('ignores non-matching tokens', function() {
return watchHelper.runTest(collQueryJSON(), () => {
// Mock the server responding to the query.
watchHelper.sendAddTarget();
watchHelper.sendCurrent();
let resumeToken = [0x1];
watchHelper.sendSnapshot(1, resumeToken);
return watchHelper.await('snapshot')
.then(results => {
lastSnapshot = snapshotsEqual(lastSnapshot, 1, results, EMPTY);
// Add a result.
watchHelper.sendDoc(doc1, {foo: 'a'});
// Send snapshot with non-matching target id. No snapshot will be
// send.
streamHelper.write({
targetChange: {
targetChangeType: 'NO_CHANGE',
targetIds: [0xfeed],
readTime: {seconds: 0, nanos: 0},
resumeToken: [0x2],
},
});
resumeToken = [0x3];
// Send snapshot with matching target id but no resume token.
// The old token continues to be used.
streamHelper.write({
targetChange: {
targetChangeType: 'NO_CHANGE',
targetIds: [],
readTime: {seconds: 0, nanos: 0},
resumeToken: resumeToken,
},
});
return watchHelper.await('snapshot');
})
.then(results => {
lastSnapshot = snapshotsEqual(lastSnapshot, 0, results, {
docs: [snapshot(doc1, {foo: 'a'})],
docChanges: [added(doc1, {foo: 'a'})],
});
streamHelper.destroyStream();
return streamHelper.awaitReopen();
})
.then(request => {
assert.deepStrictEqual(request, resumeTokenQuery(resumeToken));
assert.equal(streamHelper.streamCount, 2);
});