-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathdb_fn.py
322 lines (269 loc) · 10.3 KB
/
db_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
# 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 the Firebase Realtime Database.
"""
# pylint: disable=protected-access
import dataclasses as _dataclass
import functools as _functools
import typing as _typing
import datetime as _dt
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_functions.options import DatabaseOptions
from firebase_functions.core import Change, T
_event_type_written = "google.firebase.database.ref.v1.written"
_event_type_created = "google.firebase.database.ref.v1.created"
_event_type_updated = "google.firebase.database.ref.v1.updated"
_event_type_deleted = "google.firebase.database.ref.v1.deleted"
@_dataclass.dataclass(frozen=True)
class Event(_core.CloudEvent[T]):
"""
A CloudEvent that contains a DataSnapshot or a Change<DataSnapshot>.
"""
firebase_database_host: str
"""
The domain of the database instance.
"""
instance: str
"""
The instance ID portion of the fully qualified resource name.
"""
reference: str
"""
The database reference path.
"""
location: str
"""
The location of the database
"""
params: dict[str, str]
"""
A dict containing the values of the path patterns.
Only named capture groups are populated - {key}, {key=*}, {key=**}
"""
_E1 = Event[Change[_typing.Any | None]]
_E2 = Event[_typing.Any | None]
_C1 = _typing.Callable[[_E1], None]
_C2 = _typing.Callable[[_E2], None]
def _db_endpoint_handler(
func: _C1 | _C2,
event_type: str,
ref_pattern: _path_pattern.PathPattern,
instance_pattern: _path_pattern.PathPattern,
raw: _ce.CloudEvent,
) -> None:
event_attributes = raw._get_attributes()
event_data: _typing.Any = raw.get_data()
database_event_data = event_data
if event_type == _event_type_deleted:
database_event_data = database_event_data["data"]
if event_type == _event_type_created:
database_event_data = database_event_data["delta"]
if event_type in (_event_type_written, _event_type_updated):
before = event_data["data"]
after = event_data["delta"]
# Merge delta into data to generate an 'after' view of the data.
if isinstance(before, dict) and isinstance(after, dict):
after = _util.prune_nones(_util.deep_merge(before, after))
database_event_data = Change(
before=before,
after=after,
)
event_instance = event_attributes["instance"]
event_ref = event_attributes["ref"]
params: dict[str, str] = {
**ref_pattern.extract_matches(event_ref),
**instance_pattern.extract_matches(event_instance),
}
database_event = Event(
firebase_database_host=event_attributes["firebasedatabasehost"],
instance=event_instance,
reference=event_ref,
location=event_attributes["location"],
specversion=event_attributes["specversion"],
id=event_attributes["id"],
source=event_attributes["source"],
type=event_attributes["type"],
time=_dt.datetime.strptime(
event_attributes["time"],
"%Y-%m-%dT%H:%M:%S.%f%z",
),
data=database_event_data,
subject=event_attributes["subject"],
params=params,
)
_core._with_init(func)(database_event)
@_util.copy_func_kwargs(DatabaseOptions)
def on_value_written(**kwargs) -> _typing.Callable[[_C1], _C1]:
"""
Event handler that triggers when data is created, updated, or deleted in Realtime Database.
Example:
.. code-block:: python
@on_value_written(reference="*")
def example(event: Event[Change[object]]) -> None:
pass
:param \\*\\*kwargs: Database options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.DatabaseOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.db_fn.Event` \\[
:exc:`firebase_functions.core.Change` \\] \\], `None` \\]
A function that takes a Database Event and returns None.
"""
options = DatabaseOptions(**kwargs)
def on_value_written_inner_decorator(func: _C1):
ref_pattern = _path_pattern.PathPattern(options.reference)
instance_pattern = _path_pattern.PathPattern(
options.instance if options.instance is not None else "*")
@_functools.wraps(func)
def on_value_written_wrapped(raw: _ce.CloudEvent):
return _db_endpoint_handler(
func,
_event_type_written,
ref_pattern,
instance_pattern,
raw,
)
_util.set_func_endpoint_attr(
on_value_written_wrapped,
options._endpoint(
event_type=_event_type_written,
func_name=func.__name__,
instance_pattern=instance_pattern,
),
)
return on_value_written_wrapped
return on_value_written_inner_decorator
@_util.copy_func_kwargs(DatabaseOptions)
def on_value_updated(**kwargs) -> _typing.Callable[[_C1], _C1]:
"""
Event handler that triggers when data is updated in Realtime Database.
Example:
.. code-block:: python
@on_value_updated(reference="*")
def example(event: Event[Change[object]]) -> None:
pass
:param \\*\\*kwargs: Database options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.DatabaseOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.db_fn.Event` \\[
:exc:`firebase_functions.core.Change` \\] \\], `None` \\]
A function that takes a Database Event and returns None.
"""
options = DatabaseOptions(**kwargs)
def on_value_updated_inner_decorator(func: _C1):
ref_pattern = _path_pattern.PathPattern(options.reference)
instance_pattern = _path_pattern.PathPattern(
options.instance if options.instance is not None else "*")
@_functools.wraps(func)
def on_value_updated_wrapped(raw: _ce.CloudEvent):
return _db_endpoint_handler(
func,
_event_type_updated,
ref_pattern,
instance_pattern,
raw,
)
_util.set_func_endpoint_attr(
on_value_updated_wrapped,
options._endpoint(
event_type=_event_type_updated,
func_name=func.__name__,
instance_pattern=instance_pattern,
),
)
return on_value_updated_wrapped
return on_value_updated_inner_decorator
@_util.copy_func_kwargs(DatabaseOptions)
def on_value_created(**kwargs) -> _typing.Callable[[_C2], _C2]:
"""
Event handler that triggers when data is created in Realtime Database.
Example:
.. code-block:: python
@on_value_created(reference="*")
def example(event: Event[object]):
pass
:param \\*\\*kwargs: Database options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.DatabaseOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.db_fn.Event` \\[
:exc:`object` \\] \\], `None` \\]
A function that takes a Database Event and returns None.
"""
options = DatabaseOptions(**kwargs)
def on_value_created_inner_decorator(func: _C2):
ref_pattern = _path_pattern.PathPattern(options.reference)
instance_pattern = _path_pattern.PathPattern(
options.instance if options.instance is not None else "*")
@_functools.wraps(func)
def on_value_created_wrapped(raw: _ce.CloudEvent):
return _db_endpoint_handler(
func,
_event_type_created,
ref_pattern,
instance_pattern,
raw,
)
_util.set_func_endpoint_attr(
on_value_created_wrapped,
options._endpoint(
event_type=_event_type_created,
func_name=func.__name__,
instance_pattern=instance_pattern,
),
)
return on_value_created_wrapped
return on_value_created_inner_decorator
@_util.copy_func_kwargs(DatabaseOptions)
def on_value_deleted(**kwargs) -> _typing.Callable[[_C2], _C2]:
"""
Event handler that triggers when data is deleted in Realtime Database.
Example:
.. code-block:: python
@on_value_deleted(reference="*")
def example(event: Event[object]) -> None:
pass
:param \\*\\*kwargs: Database options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.DatabaseOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.db_fn.Event` \\[
:exc:`object` \\] \\], `None` \\]
A function that takes a Database Event and returns None.
"""
options = DatabaseOptions(**kwargs)
def on_value_deleted_inner_decorator(func: _C2):
ref_pattern = _path_pattern.PathPattern(options.reference)
instance_pattern = _path_pattern.PathPattern(
options.instance if options.instance is not None else "*")
@_functools.wraps(func)
def on_value_deleted_wrapped(raw: _ce.CloudEvent):
return _db_endpoint_handler(
func,
_event_type_deleted,
ref_pattern,
instance_pattern,
raw,
)
_util.set_func_endpoint_attr(
on_value_deleted_wrapped,
options._endpoint(
event_type=_event_type_deleted,
func_name=func.__name__,
instance_pattern=instance_pattern,
),
)
return on_value_deleted_wrapped
return on_value_deleted_inner_decorator