-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathfirestore_fn.py
611 lines (503 loc) · 21.2 KB
/
firestore_fn.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
# Copyright 2022 Google Inc.
#
# 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.
"""
Module for Cloud Functions that are triggered by Firestore.
"""
# pylint: disable=protected-access
import dataclasses as _dataclass
import functools as _functools
import typing as _typing
import google.events.cloud.firestore as _firestore
import google.cloud.firestore_v1 as _firestore_v1
import firebase_functions.private.util as _util
import firebase_functions.private.path_pattern as _path_pattern
import firebase_functions.core as _core
import cloudevents.http as _ce
from firebase_admin import initialize_app, get_app, _apps, _DEFAULT_APP_NAME
from google.cloud._helpers import _datetime_to_pb_timestamp
from google.cloud.firestore_v1 import _helpers as _firestore_helpers
from google.cloud.firestore_v1 import DocumentSnapshot, DocumentReference
from firebase_functions.options import FirestoreOptions
from firebase_functions.core import Change
_event_type_written = "google.cloud.firestore.document.v1.written"
_event_type_created = "google.cloud.firestore.document.v1.created"
_event_type_updated = "google.cloud.firestore.document.v1.updated"
_event_type_deleted = "google.cloud.firestore.document.v1.deleted"
_event_type_written_with_auth_context = "google.cloud.firestore.document.v1.written.withAuthContext"
_event_type_created_with_auth_context = "google.cloud.firestore.document.v1.created.withAuthContext"
_event_type_updated_with_auth_context = "google.cloud.firestore.document.v1.updated.withAuthContext"
_event_type_deleted_with_auth_context = "google.cloud.firestore.document.v1.deleted.withAuthContext"
@_dataclass.dataclass(frozen=True)
class Event(_core.CloudEvent[_core.T]):
"""
A CloudEvent that contains a ``DocumentSnapshot`` or a ``Change<DocumentSnapshot>``.
"""
location: str
"""
The location of the database.
"""
project: str
"""
The project identifier.
"""
database: str
"""
The Firestore database.
"""
namespace: str
"""
The Firestore namespace.
"""
document: str
"""
The document path.
"""
params: dict[str, str]
"""
An dict containing the values of the path patterns.
Only named capture groups are populated - {key}, {key=*}, {key=**}
"""
_E1 = Event[Change[DocumentSnapshot | None]]
_E2 = Event[DocumentSnapshot | None]
_C1 = _typing.Callable[[_E1], None]
_C2 = _typing.Callable[[_E2], None]
AuthType = _typing.Literal["service_account", "api_key", "system",
"unauthenticated", "unknown"]
@_dataclass.dataclass(frozen=True)
class AuthEvent(Event[_core.T]):
auth_type: AuthType
"""The type of principal that triggered the event"""
auth_id: str
"""The unique identifier for the principal"""
_E3 = AuthEvent[Change[DocumentSnapshot | None]]
_E4 = AuthEvent[DocumentSnapshot | None]
_C3 = _typing.Callable[[_E3], None]
_C4 = _typing.Callable[[_E4], None]
def _firestore_endpoint_handler(
func: _C1 | _C2 | _C3 | _C4,
event_type: str,
document_pattern: _path_pattern.PathPattern,
raw: _ce.CloudEvent,
) -> None:
event_attributes = raw._get_attributes()
event_data: _typing.Any = raw.get_data()
firestore_event_data: _firestore.DocumentEventData
content_type: str = event_attributes["datacontenttype"]
if "application/json" in content_type or isinstance(event_data, dict):
firestore_event_data = _typing.cast(
_firestore.DocumentEventData,
_firestore.DocumentEventData.from_json(event_data))
elif "application/protobuf" in content_type or isinstance(
event_data, bytes):
firestore_event_data = _typing.cast(
_firestore.DocumentEventData,
_firestore.DocumentEventData.deserialize(event_data))
else:
actual_type = type(event_data)
raise TypeError(f"Firestore: Cannot parse event payload of data type "
f"'{actual_type}' and content type '{content_type}'.")
event_location = event_attributes["location"]
event_project = event_attributes["project"]
event_namespace = event_attributes["namespace"]
event_document = event_attributes["document"]
event_database = event_attributes["database"]
event_auth_type = event_attributes["authtype"]
event_auth_id = event_attributes["authid"]
time = event_attributes["time"]
event_time = _util.timestamp_conversion(time)
if _DEFAULT_APP_NAME not in _apps:
initialize_app()
app = get_app()
firestore_client = _firestore_v1.Client(project=app.project_id,
database=event_database)
firestore_ref: DocumentReference = firestore_client.document(event_document)
value_snapshot: DocumentSnapshot | None = None
old_value_snapshot: DocumentSnapshot | None = None
if firestore_event_data.value:
document_dict = _firestore_helpers.decode_dict(
firestore_event_data.value.fields, firestore_client)
value_snapshot = _firestore_v1.DocumentSnapshot(
firestore_ref,
document_dict,
True,
_datetime_to_pb_timestamp(event_time),
firestore_event_data.value.create_time,
firestore_event_data.value.update_time,
)
if firestore_event_data.old_value:
document_dict = _firestore_helpers.decode_dict(
firestore_event_data.old_value.fields, firestore_client)
old_value_snapshot = _firestore_v1.DocumentSnapshot(
firestore_ref,
document_dict,
True,
_datetime_to_pb_timestamp(event_time),
firestore_event_data.old_value.create_time,
firestore_event_data.old_value.update_time,
)
if event_type == _event_type_deleted:
firestore_event_data = _typing.cast(_firestore.DocumentEventData,
old_value_snapshot)
if event_type == _event_type_created:
firestore_event_data = _typing.cast(_firestore.DocumentEventData,
value_snapshot)
if event_type in (_event_type_written, _event_type_updated):
firestore_event_data = _typing.cast(
_firestore.DocumentEventData,
Change(
before=old_value_snapshot,
after=value_snapshot,
))
params: dict[str, str] = {
**document_pattern.extract_matches(event_document),
}
database_event = Event(
project=event_project,
namespace=event_namespace,
database=event_database,
location=event_location,
document=event_document,
specversion=event_attributes["specversion"],
id=event_attributes["id"],
source=event_attributes["source"],
type=event_attributes["type"],
time=event_time,
data=firestore_event_data,
subject=event_attributes["subject"],
params=params,
)
if event_type.endswith(".withAuthContext"):
database_event_with_auth_context = AuthEvent(**vars(database_event),
auth_type=event_auth_type,
auth_id=event_auth_id)
func(database_event_with_auth_context)
else:
# mypy cannot infer that the event type is correct, hence the cast
_typing.cast(_C1 | _C2, func)(database_event)
@_util.copy_func_kwargs(FirestoreOptions)
def on_document_written(**kwargs) -> _typing.Callable[[_C1], _C1]:
"""
Event handler that triggers when a document is created, updated, or deleted in Firestore.
Example:
.. code-block:: python
@on_document_written(document="*")
def example(event: Event[Change[DocumentSnapshot]]) -> None:
pass
:param \\*\\*kwargs: Firestore options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.FirestoreOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.firestore_fn.Event` \\[
:exc:`firebase_functions.db.Change` \\] \\], `None` \\]
A function that takes a Firestore event and returns ``None``.
"""
options = FirestoreOptions(**kwargs)
def on_document_written_inner_decorator(func: _C1):
document_pattern = _path_pattern.PathPattern(
_util.normalize_path(options.document))
@_functools.wraps(func)
def on_document_written_wrapped(raw: _ce.CloudEvent):
return _firestore_endpoint_handler(
func,
_event_type_written,
document_pattern,
raw,
)
_util.set_func_endpoint_attr(
on_document_written_wrapped,
options._endpoint(
event_type=_event_type_written,
func_name=func.__name__,
document_pattern=document_pattern,
),
)
return on_document_written_wrapped
return on_document_written_inner_decorator
@_util.copy_func_kwargs(FirestoreOptions)
def on_document_written_with_auth_context(**kwargs
) -> _typing.Callable[[_C1], _C1]:
"""
Event handler that triggers when a document is created, updated, or deleted in Firestore.
This trigger will also provide the authentication context of the principal who triggered
the event.
Example:
.. code-block:: python
@on_document_written_with_auth_context(document="*")
def example(event: AuthEvent[Change[DocumentSnapshot]]) -> None:
pass
:param \\*\\*kwargs: Firestore options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.FirestoreOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.firestore_fn.AuthEvent` \\[
:exc:`firebase_functions.db.Change` \\] \\], `None` \\]
A function that takes a Firestore event and returns ``None``.
"""
options = FirestoreOptions(**kwargs)
def on_document_written_with_auth_context_inner_decorator(func: _C1):
document_pattern = _path_pattern.PathPattern(
_util.normalize_path(options.document))
@_functools.wraps(func)
def on_document_written_with_auth_context_wrapped(raw: _ce.CloudEvent):
return _firestore_endpoint_handler(
func,
_event_type_written_with_auth_context,
document_pattern,
raw,
)
_util.set_func_endpoint_attr(
on_document_written_with_auth_context_wrapped,
options._endpoint(
event_type=_event_type_written,
func_name=func.__name__,
document_pattern=document_pattern,
),
)
return on_document_written_with_auth_context_wrapped
return on_document_written_with_auth_context_inner_decorator
@_util.copy_func_kwargs(FirestoreOptions)
def on_document_updated(**kwargs) -> _typing.Callable[[_C1], _C1]:
"""
Event handler that triggers when a document is updated in Firestore.
Example:
.. code-block:: python
@on_document_updated(document="*")
def example(event: Event[Change[DocumentSnapshot]]) -> None:
pass
:param \\*\\*kwargs: Firestore options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.FirestoreOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.firestore_fn.Event` \\[
:exc:`firebase_functions.db.Change` \\] \\], `None` \\]
A function that takes a Firestore event and returns ``None``.
"""
options = FirestoreOptions(**kwargs)
def on_document_updated_inner_decorator(func: _C1):
document_pattern = _path_pattern.PathPattern(
_util.normalize_path(options.document))
@_functools.wraps(func)
def on_document_updated_wrapped(raw: _ce.CloudEvent):
return _firestore_endpoint_handler(
func,
_event_type_updated,
document_pattern,
raw,
)
_util.set_func_endpoint_attr(
on_document_updated_wrapped,
options._endpoint(
event_type=_event_type_updated,
func_name=func.__name__,
document_pattern=document_pattern,
),
)
return on_document_updated_wrapped
return on_document_updated_inner_decorator
@_util.copy_func_kwargs(FirestoreOptions)
def on_document_updated_with_auth_context(**kwargs
) -> _typing.Callable[[_C1], _C1]:
"""
Event handler that triggers when a document is updated in Firestore.
This trigger will also provide the authentication context of the principal who triggered
the event.
Example:
.. code-block:: python
@on_document_updated_with_auth_context(document="*")
def example(event: AuthEvent[Change[DocumentSnapshot]]) -> None:
pass
:param \\*\\*kwargs: Firestore options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.FirestoreOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.firestore_fn.AuthEvent` \\[
:exc:`firebase_functions.db.Change` \\] \\], `None` \\]
A function that takes a Firestore event and returns ``None``.
"""
options = FirestoreOptions(**kwargs)
def on_document_updated_with_auth_context_inner_decorator(func: _C1):
document_pattern = _path_pattern.PathPattern(
_util.normalize_path(options.document))
@_functools.wraps(func)
def on_document_updated_with_auth_context_wrapped(raw: _ce.CloudEvent):
return _firestore_endpoint_handler(
func,
_event_type_updated_with_auth_context,
document_pattern,
raw,
)
_util.set_func_endpoint_attr(
on_document_updated_with_auth_context_wrapped,
options._endpoint(
event_type=_event_type_updated_with_auth_context,
func_name=func.__name__,
document_pattern=document_pattern,
),
)
return on_document_updated_with_auth_context_wrapped
return on_document_updated_with_auth_context_inner_decorator
@_util.copy_func_kwargs(FirestoreOptions)
def on_document_created(**kwargs) -> _typing.Callable[[_C2], _C2]:
"""
Event handler that triggers when a document is created in Firestore.
Example:
.. code-block:: python
@on_document_created(document="*")
def example(event: Event[DocumentSnapshot]):
pass
:param \\*\\*kwargs: Firestore options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.FirestoreOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.firestore_fn.Event` \\[
:exc:`object` \\] \\], `None` \\]
A function that takes a Firestore event and returns ``None``.
"""
options = FirestoreOptions(**kwargs)
def on_document_created_inner_decorator(func: _C2):
document_pattern = _path_pattern.PathPattern(
_util.normalize_path(options.document))
@_functools.wraps(func)
def on_document_created_wrapped(raw: _ce.CloudEvent):
return _firestore_endpoint_handler(
func,
_event_type_created,
document_pattern,
raw,
)
_util.set_func_endpoint_attr(
on_document_created_wrapped,
options._endpoint(
event_type=_event_type_created,
func_name=func.__name__,
document_pattern=document_pattern,
),
)
return on_document_created_wrapped
return on_document_created_inner_decorator
@_util.copy_func_kwargs(FirestoreOptions)
def on_document_created_with_auth_context(**kwargs
) -> _typing.Callable[[_C2], _C2]:
"""
Event handler that triggers when a document is created in Firestore.
This trigger will also provide the authentication context of the principal who triggered
the event.
Example:
.. code-block:: python
@on_document_created_with_auth_context(document="*")
def example(event: AuthEvent[DocumentSnapshot]):
pass
:param \\*\\*kwargs: Firestore options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.FirestoreOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.firestore_fn.AuthEvent` \\[
:exc:`object` \\] \\], `None` \\]
A function that takes a Firestore event and returns ``None``.
"""
options = FirestoreOptions(**kwargs)
def on_document_created_with_auth_context_inner_decorator(func: _C2):
document_pattern = _path_pattern.PathPattern(
_util.normalize_path(options.document))
@_functools.wraps(func)
def on_document_created_with_auth_context_wrapped(raw: _ce.CloudEvent):
return _firestore_endpoint_handler(
func,
_event_type_created_with_auth_context,
document_pattern,
raw,
)
_util.set_func_endpoint_attr(
on_document_created_with_auth_context_wrapped,
options._endpoint(
event_type=_event_type_created_with_auth_context,
func_name=func.__name__,
document_pattern=document_pattern,
),
)
return on_document_created_with_auth_context_wrapped
return on_document_created_with_auth_context_inner_decorator
@_util.copy_func_kwargs(FirestoreOptions)
def on_document_deleted(**kwargs) -> _typing.Callable[[_C2], _C2]:
"""
Event handler that triggers when a document is deleted in Firestore.
Example:
.. code-block:: python
@on_document_deleted(document="*")
def example(event: Event[DocumentSnapshot]) -> None:
pass
:param \\*\\*kwargs: Firestore options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.FirestoreOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.firestore_fn.Event` \\[
:exc:`object` \\] \\], `None` \\]
A function that takes a Firestore event and returns ``None``.
"""
options = FirestoreOptions(**kwargs)
def on_document_deleted_inner_decorator(func: _C2):
document_pattern = _path_pattern.PathPattern(
_util.normalize_path(options.document))
@_functools.wraps(func)
def on_document_deleted_wrapped(raw: _ce.CloudEvent):
return _firestore_endpoint_handler(
func,
_event_type_deleted,
document_pattern,
raw,
)
_util.set_func_endpoint_attr(
on_document_deleted_wrapped,
options._endpoint(
event_type=_event_type_deleted,
func_name=func.__name__,
document_pattern=document_pattern,
),
)
return on_document_deleted_wrapped
return on_document_deleted_inner_decorator
@_util.copy_func_kwargs(FirestoreOptions)
def on_document_deleted_with_auth_context(**kwargs
) -> _typing.Callable[[_C2], _C2]:
"""
Event handler that triggers when a document is deleted in Firestore.
This trigger will also provide the authentication context of the principal who triggered
the event.
Example:
.. code-block:: python
@on_document_deleted_with_auth_context(document="*")
def example(event: AuthEvent[DocumentSnapshot]) -> None:
pass
:param \\*\\*kwargs: Firestore options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.FirestoreOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.firestore_fn.AuthEvent` \\[
:exc:`object` \\] \\], `None` \\]
A function that takes a Firestore event and returns ``None``.
"""
options = FirestoreOptions(**kwargs)
def on_document_deleted_with_auth_context_inner_decorator(func: _C2):
document_pattern = _path_pattern.PathPattern(
_util.normalize_path(options.document))
@_functools.wraps(func)
def on_document_deleted_with_auth_context_wrapped(raw: _ce.CloudEvent):
return _firestore_endpoint_handler(
func,
_event_type_deleted_with_auth_context,
document_pattern,
raw,
)
_util.set_func_endpoint_attr(
on_document_deleted_with_auth_context_wrapped,
options._endpoint(
event_type=_event_type_deleted_with_auth_context,
func_name=func.__name__,
document_pattern=document_pattern,
),
)
return on_document_deleted_with_auth_context_wrapped
return on_document_deleted_with_auth_context_inner_decorator