-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathstorage_fn.py
423 lines (343 loc) · 12.7 KB
/
storage_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
# 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.
"""
Functions to handle events from Google Cloud Storage.
"""
# pylint: disable=protected-access
import dataclasses as _dataclasses
import datetime as _dt
import functools as _functools
import typing as _typing
import cloudevents.http as _ce
import firebase_functions.private.util as _util
from firebase_functions.core import CloudEvent, _with_init
from firebase_functions.options import StorageOptions
_event_type_archived = "google.cloud.storage.object.v1.archived"
_event_type_finalized = "google.cloud.storage.object.v1.finalized"
_event_type_deleted = "google.cloud.storage.object.v1.deleted"
_event_type_metadata_updated = "google.cloud.storage.object.v1.metadataUpdated"
@_dataclasses.dataclass(frozen=True)
class CustomerEncryption:
"""
Metadata of customer-supplied encryption key,
if the object is encrypted by such a key.
"""
encryption_algorithm: str
"""
The encryption algorithm.
"""
key_sha256: str
"""
SHA256 hash value of the encryption key.
"""
@_dataclasses.dataclass(frozen=True)
class StorageObjectData:
"""
An object within Google Cloud Storage.
"""
bucket: str
"""
The name of the bucket containing this object.
"""
cache_control: str | None
"""
Cache-Control directive for the object data,
matching [RFC 7234 §5.2]([https://tools.ietf.org/html/rfc7234#section-5.2"]).
"""
component_count: int | None
"""
Number of underlying components that make up this object.
Components are accumulated by compose operations.
"""
content_disposition: str | None
"""
Content-Disposition of the object data,
matching [RFC 6266]([https://tools.ietf.org/html/rfc6266"]).
"""
content_encoding: str | None
"""
Content-Encoding of the object data,
matching [RFC 7231 §3.1.2.2](https://tools.ietf.org/html/rfc7231#section-3.1.2.2)
"""
content_language: str | None
"""
Content-Language of the object data,
matching [RFC 7231 §3.1.3.2](https://tools.ietf.org/html/rfc7231#section-3.1.3.2)
"""
content_type: str | None
"""
Content-Type of the object data, matching
[RFC 7231 §3.1.1.5](https://tools.ietf.org/html/rfc7231#section-3.1.1.5)
If an object is stored without a Content-Type, it is served as
`application/octet-stream`.
"""
crc32c: str | None
"""
CRC32c checksum. For more information about using the CRC32c checksum, see
[Hashes and ETags: Best Practices](https://cloud.google.com/storage/docs/hashes-etags#_JSONAPI).
"""
customer_encryption: CustomerEncryption | None
"""
Metadata of customer-supplied encryption key, if the object is encrypted by
such a key.
"""
etag: str | None
"""
HTTP 1.1 Entity tag for the object.
"""
generation: int
"""
The content generation of this object. Used for object versioning.
"""
id: str
"""
The ID of the object, including the bucket name, object name, and
generation number.
"""
kind: str | None
"""
The kind of item this is. For objects, this is always `storage#object`.
"""
md5_hash: str | None
"""
MD5 hash of the data; encoded using base64.
"""
media_link: str | None
"""
Media download link.
"""
metadata: dict[str, str] | None
"""
User-provided metadata, in key/value pairs.
"""
metageneration: int
"""
The version of the metadata for this object at this generation.
Used for preconditions and for detecting changes in metadata.
A metageneration number is only meaningful in the context of a particular
generation of a particular object.
"""
name: str
"""
The name of the object.
"""
self_link: str | None
"""
The link to this object.
"""
size: int
"""
Content-Length of the data in bytes.
"""
storage_class: str
"""
Storage class of the object.
"""
time_created: str | None
"""
The creation time of the object.
"""
time_deleted: str | None
"""
The deletion time of the object.
"""
time_storage_class_updated: str | None
"""
The time at which the object's storage class was last changed.
"""
updated: str | None
"""
The modification time of the object metadata.
"""
_E1 = CloudEvent[StorageObjectData]
_C1 = _typing.Callable[[_E1], None]
def _message_handler(
func: _C1,
raw: _ce.CloudEvent,
) -> None:
event_attributes = raw._get_attributes()
data: _typing.Any = raw.get_data()
message: StorageObjectData = StorageObjectData(
# Required fields:
bucket=data["bucket"],
generation=data["generation"],
id=data["id"],
metageneration=data["metageneration"],
name=data["name"],
size=data["size"],
storage_class=data["storageClass"],
# Optional fields:
cache_control=data.get("cacheControl"),
component_count=data.get("componentCount"),
content_disposition=data.get("contentDisposition"),
content_encoding=data.get("contentEncoding"),
content_language=data.get("contentLanguage"),
content_type=data.get("contentType"),
crc32c=data.get("crc32c"),
etag=data.get("etag"),
kind=data.get("kind"),
md5_hash=data.get("md5Hash"),
media_link=data.get("mediaLink"),
metadata=data.get("metadata"),
self_link=data.get("selfLink"),
time_created=data.get("timeCreated"),
time_deleted=data.get("timeDeleted"),
time_storage_class_updated=data.get("timeStorageClassUpdated"),
updated=data.get("updated"),
# Custom type fields:
customer_encryption=CustomerEncryption(
encryption_algorithm=data["customerEncryption"]
["encryptionAlgorithm"],
key_sha256=data["customerEncryption"]["keySha256"],
) if data.get("customerEncryption") is not None else None,
)
event: CloudEvent[StorageObjectData] = CloudEvent(
data=message,
id=event_attributes["id"],
source=event_attributes["source"],
specversion=event_attributes["specversion"],
subject=event_attributes["subject"]
if "subject" in event_attributes else None,
time=_dt.datetime.strptime(
event_attributes["time"],
"%Y-%m-%dT%H:%M:%S.%f%z",
),
type=event_attributes["type"],
)
_with_init(func)(event)
@_util.copy_func_kwargs(StorageOptions)
def on_object_archived(**kwargs) -> _typing.Callable[[_C1], _C1]:
"""
Event handler sent only when a bucket has enabled object versioning.
This event indicates that the live version of an object has become an
archived version, either because it was archived or because it was
overwritten by the upload of an object of the same name.
Example:
.. code-block:: python
@on_object_archived()
def example(event: CloudEvent[StorageObjectData]) -> None:
pass
:param \\*\\*kwargs: Storage options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.StorageOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.core.CloudEvent` \\[
:exc:`firebase_functions.storage.StorageObjectData` \\] \\], `None` \\]
A function that takes a CloudEvent and returns None.
"""
options = StorageOptions(**kwargs)
def on_object_archived_inner_decorator(func: _C1):
@_functools.wraps(func)
def on_object_archived_wrapped(raw: _ce.CloudEvent):
return _message_handler(func, raw)
_util.set_func_endpoint_attr(
on_object_archived_wrapped,
options._endpoint(func_name=func.__name__,
event_type=_event_type_archived),
)
return on_object_archived_wrapped
return on_object_archived_inner_decorator
@_util.copy_func_kwargs(StorageOptions)
def on_object_finalized(**kwargs) -> _typing.Callable[[_C1], _C1]:
"""
Event handler which fires every time a Google Cloud Storage object
creation occurs.
Sent when a new object (or a new generation of an existing object)
is successfully created in the bucket. This includes copying or rewriting
an existing object. A failed upload does not trigger this event.
Example:
.. code-block:: python
@on_object_finalized()
def example(event: CloudEvent[StorageObjectData]) -> None:
pass
:param \\*\\*kwargs: Storage options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.StorageOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.core.CloudEvent` \\[
:exc:`firebase_functions.storage.StorageObjectData` \\] \\], `None` \\]
A function that takes a CloudEvent and returns None.
"""
options = StorageOptions(**kwargs)
def on_object_finalized_inner_decorator(func: _C1):
@_functools.wraps(func)
def on_object_finalized_wrapped(raw: _ce.CloudEvent):
return _message_handler(func, raw)
_util.set_func_endpoint_attr(
on_object_finalized_wrapped,
options._endpoint(func_name=func.__name__,
event_type=_event_type_finalized),
)
return on_object_finalized_wrapped
return on_object_finalized_inner_decorator
@_util.copy_func_kwargs(StorageOptions)
def on_object_deleted(**kwargs) -> _typing.Callable[[_C1], _C1]:
"""
Event handler which fires every time a Google Cloud Storage deletion occurs.
Sent when an object has been permanently deleted. This includes objects
that are overwritten or are deleted as part of the bucket's lifecycle
configuration. For buckets with object versioning enabled, this is not
sent when an object is archived, even if archival occurs
via the `storage.objects.delete` method.
Example:
.. code-block:: python
@on_object_deleted()
def example(event: CloudEvent[StorageObjectData]) -> None:
pass
:param \\*\\*kwargs: Storage options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.StorageOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.core.CloudEvent` \\[
:exc:`firebase_functions.storage.StorageObjectData` \\] \\], `None` \\]
A function that takes a CloudEvent and returns None.
"""
options = StorageOptions(**kwargs)
def on_object_deleted_inner_decorator(func: _C1):
@_functools.wraps(func)
def on_object_deleted_wrapped(raw: _ce.CloudEvent):
return _message_handler(func, raw)
_util.set_func_endpoint_attr(
on_object_deleted_wrapped,
options._endpoint(func_name=func.__name__,
event_type=_event_type_deleted),
)
return on_object_deleted_wrapped
return on_object_deleted_inner_decorator
@_util.copy_func_kwargs(StorageOptions)
def on_object_metadata_updated(**kwargs) -> _typing.Callable[[_C1], _C1]:
"""
Event handler which fires every time the metadata of an existing object
changes.
Example:
.. code-block:: python
@on_object_metadata_updated()
def example(event: CloudEvent[StorageObjectData]) -> None:
pass
:param \\*\\*kwargs: Storage options.
:type \\*\\*kwargs: as :exc:`firebase_functions.options.StorageOptions`
:rtype: :exc:`typing.Callable`
\\[ \\[ :exc:`firebase_functions.core.CloudEvent` \\[
:exc:`firebase_functions.storage.StorageObjectData` \\] \\], `None` \\]
A function that takes a CloudEvent and returns None.
"""
options = StorageOptions(**kwargs)
def on_object_metadata_updated_inner_decorator(func: _C1):
@_functools.wraps(func)
def on_object_metadata_updated_wrapped(raw: _ce.CloudEvent):
return _message_handler(func, raw)
_util.set_func_endpoint_attr(
on_object_metadata_updated_wrapped,
options._endpoint(func_name=func.__name__,
event_type=_event_type_metadata_updated),
)
return on_object_metadata_updated_wrapped
return on_object_metadata_updated_inner_decorator