-
Notifications
You must be signed in to change notification settings - Fork 69
/
watch.py
724 lines (594 loc) · 24.8 KB
/
watch.py
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
# Copyright 2017 Google LLC 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.
import collections
from enum import Enum
import functools
import logging
import threading
from google.api_core.bidi import ResumableBidiRpc
from google.api_core.bidi import BackgroundConsumer
from google.api_core import exceptions
import grpc # type: ignore
from google.cloud.firestore_v1.types.firestore import ListenRequest
from google.cloud.firestore_v1.types.firestore import Target
from google.cloud.firestore_v1.types.firestore import TargetChange
from google.cloud.firestore_v1 import _helpers
TargetChangeType = TargetChange.TargetChangeType
_LOGGER = logging.getLogger(__name__)
WATCH_TARGET_ID = 0x5079 # "Py"
GRPC_STATUS_CODE = {
"OK": 0,
"CANCELLED": 1,
"UNKNOWN": 2,
"INVALID_ARGUMENT": 3,
"DEADLINE_EXCEEDED": 4,
"NOT_FOUND": 5,
"ALREADY_EXISTS": 6,
"PERMISSION_DENIED": 7,
"UNAUTHENTICATED": 16,
"RESOURCE_EXHAUSTED": 8,
"FAILED_PRECONDITION": 9,
"ABORTED": 10,
"OUT_OF_RANGE": 11,
"UNIMPLEMENTED": 12,
"INTERNAL": 13,
"UNAVAILABLE": 14,
"DATA_LOSS": 15,
"DO_NOT_USE": -1,
}
_RPC_ERROR_THREAD_NAME = "Thread-OnRpcTerminated"
_RECOVERABLE_STREAM_EXCEPTIONS = (
exceptions.Aborted,
exceptions.Cancelled,
exceptions.Unknown,
exceptions.DeadlineExceeded,
exceptions.ResourceExhausted,
exceptions.InternalServerError,
exceptions.ServiceUnavailable,
exceptions.Unauthenticated,
)
_TERMINATING_STREAM_EXCEPTIONS = (exceptions.Cancelled,)
DocTreeEntry = collections.namedtuple("DocTreeEntry", ["value", "index"])
class WatchDocTree(object):
# TODO: Currently this uses a dict. Other implementations use a rbtree.
# The performance of this implementation should be investigated and may
# require modifying the underlying datastructure to a rbtree.
def __init__(self):
self._dict = {}
self._index = 0
def keys(self):
return list(self._dict.keys())
def _copy(self):
wdt = WatchDocTree()
wdt._dict = self._dict.copy()
wdt._index = self._index
self = wdt
return self
def insert(self, key, value):
self = self._copy()
self._dict[key] = DocTreeEntry(value, self._index)
self._index += 1
return self
def find(self, key):
return self._dict[key]
def remove(self, key):
self = self._copy()
del self._dict[key]
return self
def __iter__(self):
for k in self._dict:
yield k
def __len__(self):
return len(self._dict)
def __contains__(self, k):
return k in self._dict
class ChangeType(Enum):
ADDED = 1
REMOVED = 2
MODIFIED = 3
class DocumentChange(object):
def __init__(self, type, document, old_index, new_index):
"""DocumentChange
Args:
type (ChangeType):
document (document.DocumentSnapshot):
old_index (int):
new_index (int):
"""
# TODO: spec indicated an isEqual param also
self.type = type
self.document = document
self.old_index = old_index
self.new_index = new_index
class WatchResult(object):
def __init__(self, snapshot, name, change_type):
self.snapshot = snapshot
self.name = name
self.change_type = change_type
def _maybe_wrap_exception(exception):
"""Wraps a gRPC exception class, if needed."""
if isinstance(exception, grpc.RpcError):
return exceptions.from_grpc_error(exception)
return exception
def document_watch_comparator(doc1, doc2):
assert doc1 == doc2, "Document watches only support one document."
return 0
def _should_recover(exception):
wrapped = _maybe_wrap_exception(exception)
return isinstance(wrapped, _RECOVERABLE_STREAM_EXCEPTIONS)
def _should_terminate(exception):
wrapped = _maybe_wrap_exception(exception)
return isinstance(wrapped, _TERMINATING_STREAM_EXCEPTIONS)
class Watch(object):
def __init__(
self,
document_reference,
firestore,
target,
comparator,
snapshot_callback,
document_snapshot_cls,
):
"""
Args:
firestore:
target:
comparator:
snapshot_callback: Callback method to process snapshots.
Args:
docs (List(DocumentSnapshot)): A callback that returns the
ordered list of documents stored in this snapshot.
changes (List(str)): A callback that returns the list of
changed documents since the last snapshot delivered for
this watch.
read_time (string): The ISO 8601 time at which this
snapshot was obtained.
document_snapshot_cls: factory for instances of DocumentSnapshot
"""
self._document_reference = document_reference
self._firestore = firestore
self._targets = target
self._comparator = comparator
self._document_snapshot_cls = document_snapshot_cls
self._snapshot_callback = snapshot_callback
self._api = firestore._firestore_api
self._closing = threading.Lock()
self._closed = False
self._set_documents_pfx(firestore._database_string)
self.resume_token = None
# Initialize state for on_snapshot
# The sorted tree of QueryDocumentSnapshots as sent in the last
# snapshot. We only look at the keys.
self.doc_tree = WatchDocTree()
# A map of document names to QueryDocumentSnapshots for the last sent
# snapshot.
self.doc_map = {}
# The accumulates map of document changes (keyed by document name) for
# the current snapshot.
self.change_map = {}
# The current state of the query results.
self.current = False
# We need this to track whether we've pushed an initial set of changes,
# since we should push those even when there are no changes, if there
# aren't docs.
self.has_pushed = False
self._init_stream()
def _init_stream(self):
rpc_request = self._get_rpc_request
self._rpc = ResumableBidiRpc(
start_rpc=self._api._transport.listen,
should_recover=_should_recover,
should_terminate=_should_terminate,
initial_request=rpc_request,
metadata=self._firestore._rpc_metadata,
)
self._rpc.add_done_callback(self._on_rpc_done)
# The server assigns and updates the resume token.
self._consumer = BackgroundConsumer(self._rpc, self.on_snapshot)
self._consumer.start()
@classmethod
def for_document(
cls,
document_ref,
snapshot_callback,
document_snapshot_cls,
):
"""
Creates a watch snapshot listener for a document. snapshot_callback
receives a DocumentChange object, but may also start to get
targetChange and such soon
Args:
document_ref: Reference to Document
snapshot_callback: callback to be called on snapshot
document_snapshot_cls: class to make snapshots with
reference_class_instance: class make references
"""
return cls(
document_ref,
document_ref._client,
{
"documents": {"documents": [document_ref._document_path]},
"target_id": WATCH_TARGET_ID,
},
document_watch_comparator,
snapshot_callback,
document_snapshot_cls,
)
@classmethod
def for_query(cls, query, snapshot_callback, document_snapshot_cls):
parent_path, _ = query._parent._parent_info()
query_target = Target.QueryTarget(
parent=parent_path, structured_query=query._to_protobuf()
)
return cls(
query,
query._client,
{"query": query_target._pb, "target_id": WATCH_TARGET_ID},
query._comparator,
snapshot_callback,
document_snapshot_cls,
)
def _get_rpc_request(self):
if self.resume_token is not None:
self._targets["resume_token"] = self.resume_token
else:
self._targets.pop("resume_token", None)
return ListenRequest(
database=self._firestore._database_string, add_target=self._targets
)
def _set_documents_pfx(self, database_string):
self._documents_pfx = f"{database_string}/documents/"
self._documents_pfx_len = len(self._documents_pfx)
@property
def is_active(self):
"""bool: True if this manager is actively streaming.
Note that ``False`` does not indicate this is complete shut down,
just that it stopped getting new messages.
"""
return self._consumer is not None and self._consumer.is_active
def close(self, reason=None):
"""Stop consuming messages and shutdown all helper threads.
This method is idempotent. Additional calls will have no effect.
Args:
reason (Any): The reason to close this. If None, this is considered
an "intentional" shutdown.
"""
with self._closing:
if self._closed:
return
# Stop consuming messages.
if self.is_active:
_LOGGER.debug("Stopping consumer.")
self._consumer.stop()
self._consumer = None
self._rpc.close()
self._rpc = None
self._closed = True
_LOGGER.debug("Finished stopping manager.")
if reason:
# Raise an exception if a reason is provided
_LOGGER.debug("reason for closing: %s" % reason)
if isinstance(reason, Exception):
raise reason
raise RuntimeError(reason)
def _on_rpc_done(self, future):
"""Triggered whenever the underlying RPC terminates without recovery.
This is typically triggered from one of two threads: the background
consumer thread (when calling ``recv()`` produces a non-recoverable
error) or the grpc management thread (when cancelling the RPC).
This method is *non-blocking*. It will start another thread to deal
with shutting everything down. This is to prevent blocking in the
background consumer and preventing it from being ``joined()``.
"""
_LOGGER.info("RPC termination has signaled manager shutdown.")
future = _maybe_wrap_exception(future)
thread = threading.Thread(
name=_RPC_ERROR_THREAD_NAME, target=self.close, kwargs={"reason": future}
)
thread.daemon = True
thread.start()
def unsubscribe(self):
self.close()
def _on_snapshot_target_change_no_change(self, target_change):
_LOGGER.debug("on_snapshot: target change: NO_CHANGE")
no_target_ids = (
target_change.target_ids is None or len(target_change.target_ids) == 0
)
if no_target_ids and target_change.read_time and self.current:
# TargetChange.TargetChangeType.CURRENT followed by
# TargetChange.TargetChangeType.NO_CHANGE
# signals a consistent state. Invoke the onSnapshot
# callback as specified by the user.
self.push(target_change.read_time, target_change.resume_token)
def _on_snapshot_target_change_add(self, target_change):
_LOGGER.debug("on_snapshot: target change: ADD")
target_id = target_change.target_ids[0]
if target_id != WATCH_TARGET_ID:
raise RuntimeError("Unexpected target ID %s sent by server" % target_id)
def _on_snapshot_target_change_remove(self, target_change):
_LOGGER.debug("on_snapshot: target change: REMOVE")
if target_change.cause.code:
code = target_change.cause.code
message = target_change.cause.message
else:
code = 13
message = "internal error"
error_message = "Error %s: %s" % (code, message)
raise RuntimeError(error_message)
def _on_snapshot_target_change_reset(self, target_change):
# Whatever changes have happened so far no longer matter.
_LOGGER.debug("on_snapshot: target change: RESET")
self._reset_docs()
def _on_snapshot_target_change_current(self, target_change):
_LOGGER.debug("on_snapshot: target change: CURRENT")
self.current = True
_target_changetype_dispatch = {
TargetChangeType.NO_CHANGE: _on_snapshot_target_change_no_change,
TargetChangeType.ADD: _on_snapshot_target_change_add,
TargetChangeType.REMOVE: _on_snapshot_target_change_remove,
TargetChangeType.RESET: _on_snapshot_target_change_reset,
TargetChangeType.CURRENT: _on_snapshot_target_change_current,
}
def _strip_document_pfx(self, document_name):
if document_name.startswith(self._documents_pfx):
document_name = document_name[self._documents_pfx_len :]
return document_name
def on_snapshot(self, proto):
"""Process a response from the bi-directional gRPC stream.
Collect changes and push the changes in a batch to the customer
when we receive 'current' from the listen response.
Args:
proto(`google.cloud.firestore_v1.types.ListenResponse`):
Callback method that receives a object to
"""
if proto is None:
self.close()
return
pb = proto._pb
which = pb.WhichOneof("response_type")
if which == "target_change":
target_change_type = pb.target_change.target_change_type
_LOGGER.debug(f"on_snapshot: target change: {target_change_type}")
meth = self._target_changetype_dispatch.get(target_change_type)
if meth is None:
message = f"Unknown target change type: {target_change_type}"
_LOGGER.info(f"on_snapshot: {message}")
self.close(reason=ValueError(message))
try:
# Use 'proto' vs 'pb' for datetime handling
meth(self, proto.target_change)
except Exception as exc2:
_LOGGER.debug(f"meth(proto) exc: {exc2}")
raise
# NOTE:
# in other implementations, such as node, the backoff is reset here
# in this version bidi rpc is just used and will control this.
elif which == "document_change":
_LOGGER.debug("on_snapshot: document change")
# No other target_ids can show up here, but we still need to see
# if the targetId was in the added list or removed list.
changed = WATCH_TARGET_ID in pb.document_change.target_ids
removed = WATCH_TARGET_ID in pb.document_change.removed_target_ids
# google.cloud.firestore_v1.types.Document
# Use 'proto' vs 'pb' for datetime handling
document = proto.document_change.document
if changed:
_LOGGER.debug("on_snapshot: document change: CHANGED")
data = _helpers.decode_dict(document.fields, self._firestore)
# Create a snapshot. As Document and Query objects can be
# passed we need to get a Document Reference in a more manual
# fashion than self._document_reference
document_name = self._strip_document_pfx(document.name)
document_ref = self._firestore.document(document_name)
snapshot = self._document_snapshot_cls(
reference=document_ref,
data=data,
exists=True,
read_time=None,
create_time=document.create_time,
update_time=document.update_time,
)
self.change_map[document.name] = snapshot
elif removed:
_LOGGER.debug("on_snapshot: document change: REMOVED")
self.change_map[document.name] = ChangeType.REMOVED
# NB: document_delete and document_remove (as far as we, the client,
# are concerned) are functionally equivalent
elif which == "document_delete":
_LOGGER.debug("on_snapshot: document change: DELETE")
name = pb.document_delete.document
self.change_map[name] = ChangeType.REMOVED
elif which == "document_remove":
_LOGGER.debug("on_snapshot: document change: REMOVE")
name = pb.document_remove.document
self.change_map[name] = ChangeType.REMOVED
elif which == "filter":
_LOGGER.debug("on_snapshot: filter update")
if pb.filter.count != self._current_size():
# First, shut down current stream
_LOGGER.info("Filter mismatch -- restarting stream.")
thread = threading.Thread(
name=_RPC_ERROR_THREAD_NAME,
target=self.close,
)
thread.start()
thread.join() # wait for shutdown to complete
# Then, remove all the current results.
self._reset_docs()
# Finally, restart stream.
self._init_stream()
else:
_LOGGER.debug("UNKNOWN TYPE. UHOH")
message = f"Unknown listen response type: {proto}"
self.close(reason=ValueError(message))
def push(self, read_time, next_resume_token):
"""Invoke the callback with a new snapshot
Build the sntapshot from the current set of changes.
Clear the current changes on completion.
"""
deletes, adds, updates = self._extract_changes(
self.doc_map, self.change_map, read_time
)
updated_tree, updated_map, appliedChanges = self._compute_snapshot(
self.doc_tree, self.doc_map, deletes, adds, updates
)
if not self.has_pushed or len(appliedChanges):
# TODO: It is possible in the future we will have the tree order
# on insert. For now, we sort here.
key = functools.cmp_to_key(self._comparator)
keys = sorted(updated_tree.keys(), key=key)
self._snapshot_callback(keys, appliedChanges, read_time)
self.has_pushed = True
self.doc_tree = updated_tree
self.doc_map = updated_map
self.change_map.clear()
self.resume_token = next_resume_token
@staticmethod
def _extract_changes(doc_map, changes, read_time):
deletes = []
adds = []
updates = []
for name, value in changes.items():
if value == ChangeType.REMOVED:
if name in doc_map:
deletes.append(name)
elif name in doc_map:
if read_time is not None:
value.read_time = read_time
updates.append(value)
else:
if read_time is not None:
value.read_time = read_time
adds.append(value)
return (deletes, adds, updates)
def _compute_snapshot(
self, doc_tree, doc_map, delete_changes, add_changes, update_changes
):
updated_tree = doc_tree
updated_map = doc_map
assert len(doc_tree) == len(doc_map), (
"The document tree and document map should have the same "
+ "number of entries."
)
def delete_doc(name, updated_tree, updated_map):
"""
Applies a document delete to the document tree and document map.
Returns the corresponding DocumentChange event.
"""
assert name in updated_map, "Document to delete does not exist"
old_document = updated_map.get(name)
# TODO: If a document doesn't exist this raises IndexError. Handle?
existing = updated_tree.find(old_document)
old_index = existing.index
updated_tree = updated_tree.remove(old_document)
del updated_map[name]
return (
DocumentChange(ChangeType.REMOVED, old_document, old_index, -1),
updated_tree,
updated_map,
)
def add_doc(new_document, updated_tree, updated_map):
"""
Applies a document add to the document tree and the document map.
Returns the corresponding DocumentChange event.
"""
name = new_document.reference._document_path
assert name not in updated_map, "Document to add already exists"
updated_tree = updated_tree.insert(new_document, None)
new_index = updated_tree.find(new_document).index
updated_map[name] = new_document
return (
DocumentChange(ChangeType.ADDED, new_document, -1, new_index),
updated_tree,
updated_map,
)
def modify_doc(new_document, updated_tree, updated_map):
"""
Applies a document modification to the document tree and the
document map.
Returns the DocumentChange event for successful modifications.
"""
name = new_document.reference._document_path
assert name in updated_map, "Document to modify does not exist"
old_document = updated_map.get(name)
if old_document.update_time != new_document.update_time:
remove_change, updated_tree, updated_map = delete_doc(
name, updated_tree, updated_map
)
add_change, updated_tree, updated_map = add_doc(
new_document, updated_tree, updated_map
)
return (
DocumentChange(
ChangeType.MODIFIED,
new_document,
remove_change.old_index,
add_change.new_index,
),
updated_tree,
updated_map,
)
return None, updated_tree, updated_map
# Process the sorted changes in the order that is expected by our
# clients (removals, additions, and then modifications). We also need
# to sort the individual changes to assure that old_index/new_index
# keep incrementing.
appliedChanges = []
key = functools.cmp_to_key(self._comparator)
# Deletes are sorted based on the order of the existing document.
delete_changes = sorted(delete_changes)
for name in delete_changes:
change, updated_tree, updated_map = delete_doc(
name, updated_tree, updated_map
)
appliedChanges.append(change)
add_changes = sorted(add_changes, key=key)
_LOGGER.debug("walk over add_changes")
for snapshot in add_changes:
_LOGGER.debug("in add_changes")
change, updated_tree, updated_map = add_doc(
snapshot, updated_tree, updated_map
)
appliedChanges.append(change)
update_changes = sorted(update_changes, key=key)
for snapshot in update_changes:
change, updated_tree, updated_map = modify_doc(
snapshot, updated_tree, updated_map
)
if change is not None:
appliedChanges.append(change)
assert len(updated_tree) == len(updated_map), (
"The update document tree and document map "
"should have the same number of entries."
)
return (updated_tree, updated_map, appliedChanges)
def _current_size(self):
"""Return the current count of all documents.
Count includes the changes from the current changeMap.
"""
deletes, adds, _ = self._extract_changes(self.doc_map, self.change_map, None)
return len(self.doc_map) + len(adds) - len(deletes)
def _reset_docs(self):
"""
Helper to clear the docs on RESET or filter mismatch.
"""
_LOGGER.debug("resetting documents")
self.change_map.clear()
self.resume_token = None
# Mark each document as deleted. If documents are not deleted
# they will be sent again by the server.
for snapshot in self.doc_tree.keys():
name = snapshot.reference._document_path
self.change_map[name] = ChangeType.REMOVED
self.current = False