-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathoptions.py
1195 lines (1016 loc) · 38 KB
/
options.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
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 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 options that can be used to configure Cloud Functions
deployments.
"""
# pylint: disable=protected-access
import enum as _enum
import dataclasses as _dataclasses
import re as _re
import typing as _typing
from zoneinfo import ZoneInfo as _ZoneInfo
import firebase_functions.private.manifest as _manifest
import firebase_functions.private.util as _util
import firebase_functions.private.path_pattern as _path_pattern
from firebase_functions.params import SecretParam, Expression
Timezone = _ZoneInfo
"""An alias of the zoneinfo.ZoneInfo for convenience."""
RESET_VALUE = _util.Sentinel(
"Special configuration value to reset configuration to platform default.")
"""Special configuration value to reset configuration to platform default."""
class VpcEgressSetting(str, _enum.Enum):
"""Valid settings for VPC egress."""
PRIVATE_RANGES_ONLY = "PRIVATE_RANGES_ONLY"
ALL_TRAFFIC = "ALL_TRAFFIC"
def __str__(self) -> str:
return self.value
class IngressSetting(str, _enum.Enum):
"""What kind of traffic can access the function."""
ALLOW_ALL = "ALLOW_ALL"
ALLOW_INTERNAL_ONLY = "ALLOW_INTERNAL_ONLY"
ALLOW_INTERNAL_AND_GCLB = "ALLOW_INTERNAL_AND_GCLB"
def __str__(self) -> str:
return self.value
@_dataclasses.dataclass(frozen=True)
class CorsOptions:
"""
CORS options for HTTP functions.
Internally this maps to Flask-Cors configuration. See:
https://flask-cors.corydolphin.com/en/latest/configuration.html
"""
cors_origins: str | list[str] | _re.Pattern | None = None
"""
The origin(s) to allow requests from. An origin configured here that matches the value of
the ``Origin`` header in a preflight ``OPTIONS`` request is returned as the value of the
``Access-Control-Allow-Origin`` response header.
"""
cors_methods: str | list[str] | None = None
"""
The method(s) which the allowed origins are allowed to access.
These are included in the ``Access-Control-Allow-Methods`` response headers
to the preflight ``OPTIONS`` requests.
"""
class MemoryOption(int, _enum.Enum):
"""
Available memory options supported by Cloud Functions.
"""
MB_128 = 128
MB_256 = 256
MB_512 = 512
GB_1 = 1 << 10
GB_2 = 2 << 10
GB_4 = 4 << 10
GB_8 = 8 << 10
GB_16 = 16 << 10
GB_32 = 32 << 10
def __str__(self) -> str:
return f"{self.value}MB"
class SupportedRegion(str, _enum.Enum):
"""
All regions supported by Cloud Functions (2nd gen).
"""
ASIA_NORTHEAST1 = "asia-northeast1"
ASIA_EAST1 = "asia-east1"
ASIA_NORTHEAST2 = "asia-northeast2"
EUROPE_NORTH1 = "europe-north1"
EUROPE_WEST1 = "europe-west1"
EUROPE_WEST4 = "europe-west4"
US_CENTRAL1 = "us-central1"
US_EAST1 = "us-east1"
US_EAST4 = "us-east4"
US_WEST1 = "us-west1"
ASIA_EAST2 = "asia-east2"
ASIA_NORTHEAST3 = "asia-northeast3"
ASIA_SOUTHEAST1 = "asia-southeast1"
ASIA_SOUTHEAST2 = "asia-southeast2"
ASIA_SOUTH1 = "asia-south1"
AUSTRALIA_SOUTHEAST1 = "australia-southeast1"
EUROPE_CENTRAL2 = "europe-central2"
EUROPE_WEST2 = "europe-west2"
EUROPE_WEST3 = "europe-west3"
EUROPE_WEST6 = "europe-west6"
NORTHAMERICA_NORTHEAST1 = "northamerica-northeast1"
SOUTHAMERICA_EAST1 = "southamerica-east1"
US_WEST2 = "us-west2"
US_WEST3 = "us-west3"
US_WEST4 = "us-west4"
def __str__(self) -> str:
return self.value
@_dataclasses.dataclass(frozen=True)
class RateLimits():
"""
How congestion control should be applied to the function.
"""
max_concurrent_dispatches: int | Expression[
int] | _util.Sentinel | None = None
"""
The maximum number of requests that can be outstanding at a time.
If left unspecified, defaults to 1000.
"""
max_dispatches_per_second: int | Expression[
int] | _util.Sentinel | None = None
"""
The maximum number of requests that can be invoked per second.
If left unspecified, defaults to 500.
"""
@_dataclasses.dataclass(frozen=True)
class RetryConfig():
"""
How a task should be retried in the event of a non-2xx return.
"""
max_attempts: int | Expression[int] | _util.Sentinel | None = None
"""
The maximum number of times a request should be attempted.
If left unspecified, defaults to 3.
"""
max_retry_seconds: int | Expression[int] | _util.Sentinel | None = None
"""
The maximum amount of time for retrying a failed task.
If left unspecified will retry indefinitely.
"""
max_backoff_seconds: int | Expression[int] | _util.Sentinel | None = None
"""
The maximum amount of time to wait between attempts.
If left unspecified defaults to 1hr.
"""
max_doublings: int | Expression[int] | _util.Sentinel | None = None
"""
The maximum number of times to double the backoff between
retries. If left unspecified defaults to 16.
"""
min_backoff_seconds: int | Expression[int] | _util.Sentinel | None = None
"""
The minimum time to wait between attempts.
"""
@_dataclasses.dataclass(frozen=True, kw_only=True)
class RuntimeOptions:
"""
``RuntimeOptions`` are options that can be set on any function or globally.
Internal use only.
"""
region: SupportedRegion | str | list[SupportedRegion | str] | None = None
"""
Region where functions should be deployed.
HTTP functions can specify more than one region.
"""
memory: int | MemoryOption | Expression[int] | _util.Sentinel | None = None
"""
Amount of memory to allocate to a function.
A value of ``RESET_VALUE`` restores the defaults of 256MB.
"""
timeout_sec: int | Expression[int] | _util.Sentinel | None = None
"""
Timeout for the function in sections. Possible values are 0 to 540.
HTTP functions can specify a higher timeout.
A value of ``RESET_VALUE`` restores the default of 60s
The minimum timeout for a 2nd gen function is 1s. The maximum timeout for a
function depends on the type of function: Event handling functions have a
maximum timeout of 540s (9 minutes). HTTP and callable functions have a
maximum timeout of 3,600s (1 hour). Task queue functions have a maximum
timeout of 1,800s (30 minutes)
"""
min_instances: int | Expression[int] | _util.Sentinel | None = None
"""
Minimum number of actual instances to be running at a given time.
Instances are billed for memory allocation and 10% of CPU allocation
while idle.
A value of ``RESET_VALUE`` restores the default minimum instances.
"""
max_instances: int | Expression[int] | _util.Sentinel | None = None
"""
Maximum number of instances to be running in parallel.
A value of ``RESET_VALUE`` restores the default max instances.
"""
concurrency: int | Expression[int] | _util.Sentinel | None = None
"""
Number of requests a function can serve at once.
Can be applied only to functions running on Cloud Functions (2nd gen).
A value of ``RESET_VALUE`` restores the default concurrency (80 when CPU >= 1, 1 otherwise).
Concurrency cannot be set to any value other than 1 if `cpu` is less than 1.
The maximum value for concurrency is 1,000.
"""
cpu: int | _typing.Literal["gcf_gen1"] | _util.Sentinel | None = None
"""
Fractional number of CPUs to allocate to a function.
Defaults to 1 for functions with <= 2GB RAM and increases for larger memory sizes.
This is different from the defaults when using the gcloud utility and is different from
the fixed amount assigned in Cloud Functions (1st gen).
To revert to the CPU amounts used in gcloud or in Cloud Functions (1st gen), set this
to the value "gcf_gen1"
"""
vpc_connector: str | _util.Sentinel | None = None
"""
Connect function to specified VPC connector.
A value of ``RESET_VALUE`` removes the VPC connector.
"""
vpc_connector_egress_settings: VpcEgressSetting | _util.Sentinel | None = None
"""
Egress settings for VPC connector.
A value of ``RESET_VALUE`` turns off VPC connector egress settings.
"""
service_account: str | _util.Sentinel | None = None
"""
Specific service account for the function to run as.
A value of ``RESET_VALUE`` restores the default service account.
"""
ingress: IngressSetting | _util.Sentinel | None = None
"""
Ingress settings which control where this function can be called from.
A value of ``RESET_VALUE`` turns off ingress settings.
"""
labels: dict[str, str] | None = None
"""
User labels to set on the function.
"""
secrets: list[str] | list[SecretParam] | _util.Sentinel | None = None
"""
Secrets to bind to a function.
"""
enforce_app_check: bool | None = None
"""
Determines whether Firebase AppCheck is enforced.
When true, requests with invalid tokens auto respond with a 401
Unauthorized response.
When false, requests with invalid tokens set ``event.app`` to ``None``.
"""
preserve_external_changes: bool | None = None
"""
Controls whether function configuration modified outside of function source is preserved.
Internally defaults to false.
When setting configuration available in the underlying platform that is not yet available
in the Cloud Functions SDK, we highly recommend setting `preserve_external_changes` to
`True`. Otherwise, when the SDK releases a new version
with support for the missing configuration, your function's manually configured setting
may inadvertently be wiped out.
"""
def _asdict_with_global_options(self) -> dict:
"""
Returns the provider options merged with globally defined options.
"""
# We don't use dataclasses.asdict with a custom dict factory since
# it internally converts dataclasses to dicts automatically but
# we don't want that since we want to represent certain dataclasses
# (such as params) differently (not as a dict) when converting to
# a manifest representation.
provider_options = _manifest._dict_to_spec(self.__dict__)
global_options = _manifest._dict_to_spec(_GLOBAL_OPTIONS.__dict__)
merged_options: dict = {**global_options, **provider_options}
if self.labels is not None and _GLOBAL_OPTIONS.labels is not None:
merged_options["labels"] = {**_GLOBAL_OPTIONS.labels, **self.labels}
if "labels" not in merged_options:
merged_options["labels"] = {}
preserve_external_changes: bool = merged_options.get(
"preserve_external_changes",
False,
)
resettable_options = [
"memory",
"timeout_sec",
"min_instances",
"max_instances",
"ingress",
"concurrency",
"service_account",
"vpc_connector",
"vpc_connector_egress_settings",
]
if not preserve_external_changes:
for option in resettable_options:
if option not in merged_options:
merged_options[option] = RESET_VALUE
if self.secrets and not self.secrets == _util.Sentinel:
def convert_secret(secret) -> str:
secret_value = secret
if isinstance(secret, SecretParam):
secret_value = secret.name
return secret_value
merged_options["secrets"] = list(
map(convert_secret, _typing.cast(list, self.secrets)))
# _util.Sentinel values are converted to `None` in ManifestEndpoint generation
# after other None values are removed - so as to keep them in the generated
# YAML output as 'null' values.
return merged_options
def _endpoint(self, **kwargs) -> _manifest.ManifestEndpoint:
assert kwargs["func_name"] is not None
options_dict = self._asdict_with_global_options()
options = self.__class__(**options_dict)
secret_envs: list[
_manifest.SecretEnvironmentVariable] | _util.Sentinel = []
if options.secrets is not None:
if isinstance(options.secrets, list):
def convert_secret(
secret) -> _manifest.SecretEnvironmentVariable:
return {"key": secret}
secret_envs = list(
map(convert_secret, _typing.cast(list, options.secrets)))
elif options.secrets is _util.Sentinel:
secret_envs = _typing.cast(_util.Sentinel, options.secrets)
region: list[str] | None = None
if isinstance(options.region, list):
region = _typing.cast(list, options.region)
elif options.region is not None:
region = [_typing.cast(str, options.region)]
vpc: _manifest.VpcSettings | None = None
if isinstance(options.vpc_connector, str):
vpc = ({
"connector":
options.vpc_connector,
"egressSettings":
options.vpc_connector_egress_settings.value if isinstance(
options.vpc_connector_egress_settings, VpcEgressSetting)
else options.vpc_connector_egress_settings
} if options.vpc_connector_egress_settings is not None else {
"connector": options.vpc_connector
})
endpoint = _manifest.ManifestEndpoint(
entryPoint=kwargs["func_name"],
region=region,
availableMemoryMb=options.memory,
labels=options.labels,
maxInstances=options.max_instances,
minInstances=options.min_instances,
concurrency=options.concurrency,
serviceAccountEmail=options.service_account,
timeoutSeconds=options.timeout_sec,
cpu=options.cpu,
ingressSettings=options.ingress,
secretEnvironmentVariables=secret_envs,
vpc=vpc,
)
return endpoint
@_dataclasses.dataclass(frozen=True, kw_only=True)
class TaskQueueOptions(RuntimeOptions):
"""
Options specific to tasks function types.
"""
retry_config: RetryConfig | None = None
"""
How a task should be retried in the event of a non-2xx return.
"""
rate_limits: RateLimits | None = None
"""
How congestion control should be applied to the function.
"""
invoker: str | list[str] | _typing.Literal["private"] | None = None
"""
Who can enqueue tasks for this function.
Note:
If left unspecified, only service accounts which have
`roles/cloudtasks.enqueuer` and `roles/cloudfunctions.invoker`
will have permissions.
"""
def _endpoint(
self,
**kwargs,
) -> _manifest.ManifestEndpoint:
rate_limits: _manifest.RateLimits | None = _manifest.RateLimits(
maxConcurrentDispatches=self.rate_limits.max_concurrent_dispatches,
maxDispatchesPerSecond=self.rate_limits.max_dispatches_per_second,
) if self.rate_limits is not None else None
retry_config: _manifest.RetryConfigTasks | None = _manifest.RetryConfigTasks(
maxAttempts=self.retry_config.max_attempts,
maxRetrySeconds=self.retry_config.max_retry_seconds,
maxBackoffSeconds=self.retry_config.max_backoff_seconds,
maxDoublings=self.retry_config.max_doublings,
minBackoffSeconds=self.retry_config.min_backoff_seconds,
) if self.retry_config is not None else None
kwargs_merged = {
**_dataclasses.asdict(super()._endpoint(**kwargs)),
"taskQueueTrigger":
_manifest.TaskQueueTrigger(
rateLimits=rate_limits,
retryConfig=retry_config,
),
}
return _manifest.ManifestEndpoint(
**_typing.cast(_typing.Dict, kwargs_merged))
def _required_apis(self) -> list[_manifest.ManifestRequiredApi]:
return [
_manifest.ManifestRequiredApi(
api="cloudtasks.googleapis.com",
reason="Needed for task queue functions",
)
]
# TODO refactor Storage & Database options to use this base class.
@_dataclasses.dataclass(frozen=True, kw_only=True)
class EventHandlerOptions(RuntimeOptions):
"""
Options specific to any event handling function.
Internal use only.
"""
retry: bool | Expression[bool] | _util.Sentinel | None = None
"""
Whether failed executions should be delivered again.
"""
def _endpoint(
self,
**kwargs,
) -> _manifest.ManifestEndpoint:
assert kwargs["event_filters"] is not None
assert kwargs["event_type"] is not None
event_trigger = _manifest.EventTrigger(
eventType=kwargs["event_type"],
retry=self.retry if self.retry is not None else False,
eventFilters=kwargs["event_filters"],
)
kwargs_merged = {
**_dataclasses.asdict(super()._endpoint(**kwargs)),
"eventTrigger":
event_trigger,
}
return _manifest.ManifestEndpoint(
**_typing.cast(_typing.Dict, kwargs_merged))
@_dataclasses.dataclass(frozen=True, kw_only=True)
class PubSubOptions(EventHandlerOptions):
"""
Options specific to Pub/Sub function types.
Internal use only.
"""
topic: str
"""
The Pub/Sub topic to watch for message events.
"""
def _endpoint(
self,
**kwargs,
) -> _manifest.ManifestEndpoint:
event_filters: _typing.Any = {
"topic": self.topic,
}
event_type = "google.cloud.pubsub.topic.v1.messagePublished"
return _manifest.ManifestEndpoint(**_typing.cast(
_typing.Dict,
_dataclasses.asdict(super()._endpoint(
**kwargs, event_filters=event_filters, event_type=event_type))))
class AlertType(str, _enum.Enum):
"""
The underlying alert type of the Firebase alerts provider.
"""
CRASHLYTICS_NEW_FATAL_ISSUE = "crashlytics.newFatalIssue"
"""
Crashlytics new fatal issue alerts.
"""
CRASHLYTICS_NEW_NONFATAL_ISSUE = "crashlytics.newNonfatalIssue"
"""
Crashlytics new non-fatal issue alerts.
"""
CRASHLYTICS_REGRESSION = "crashlytics.regression"
"""
Crashlytics regression alerts.
"""
CRASHLYTICS_STABILITY_DIGEST = "crashlytics.stabilityDigest"
"""
Crashlytics stability digest alerts.
"""
CRASHLYTICS_VELOCITY = "crashlytics.velocity"
"""
Crashlytics velocity alerts.
"""
CRASHLYTICS_NEW_ANR_ISSUE = "crashlytics.newAnrIssue"
"""
Crashlytics new ANR issue alerts.
"""
BILLING_PLAN_UPDATE = "billing.planUpdate"
"""
Billing plan update alerts.
"""
BILLING_PLAN_AUTOMATED_UPDATE = "billing.planAutomatedUpdate"
"""
Billing automated plan update alerts.
"""
APP_DISTRIBUTION_NEW_TESTER_IOS_DEVICE = "appDistribution.newTesterIosDevice"
"""
App Distribution new tester iOS device alerts.
"""
APP_DISTRIBUTION_IN_APP_FEEDBACK = "appDistribution.inAppFeedback"
"""
App Distribution in-app feedback alerts.
"""
PERFORMANCE_THRESHOLD = "performance.threshold"
"""
Performance threshold alerts.
"""
def __str__(self) -> str:
return self.value
@_dataclasses.dataclass(frozen=True, kw_only=True)
class FirebaseAlertOptions(EventHandlerOptions):
"""
Options specific to Firebase alert function types.
Internal use only.
"""
alert_type: str | AlertType
"""
The Firebase alert type to listen to. Can be an ``AlertType`` enum
or string.
"""
app_id: str | None = None
"""
An optional app ID to scope down alerts.
"""
def _endpoint(
self,
**kwargs,
) -> _manifest.ManifestEndpoint:
event_filters: _typing.Any = {
"alerttype": self.alert_type,
}
if self.app_id is not None:
event_filters["appid"] = self.app_id
event_type = "google.firebase.firebasealerts.alerts.v1.published"
return _manifest.ManifestEndpoint(**_typing.cast(
_typing.Dict,
_dataclasses.asdict(super()._endpoint(
**kwargs,
event_filters=event_filters,
event_type=event_type,
))))
@_dataclasses.dataclass(frozen=True, kw_only=True)
class AppDistributionOptions(EventHandlerOptions):
"""
Options specific to app distribution functions.
Internal use only.
"""
app_id: str | None = None
"""
An optional app ID to scope down alerts.
"""
def _endpoint(
self,
**kwargs,
) -> _manifest.ManifestEndpoint:
assert kwargs["alert_type"] is not None
return FirebaseAlertOptions(
alert_type=kwargs["alert_type"],
app_id=self.app_id,
)._endpoint(**kwargs)
@_dataclasses.dataclass(frozen=True, kw_only=True)
class PerformanceOptions(EventHandlerOptions):
"""
Options specific to performance alerts functions.
Internal use only.
"""
app_id: str | None = None
"""
An optional app ID to scope down alerts.
"""
def _endpoint(
self,
**kwargs,
) -> _manifest.ManifestEndpoint:
assert kwargs["alert_type"] is not None
return FirebaseAlertOptions(
alert_type=kwargs["alert_type"],
app_id=self.app_id,
)._endpoint(**kwargs)
@_dataclasses.dataclass(frozen=True, kw_only=True)
class CrashlyticsOptions(EventHandlerOptions):
"""
Options specific to Crashlytics alert functions.
Internal use only.
"""
app_id: str | None = None
"""
An optional app ID to scope down alerts.
"""
def _endpoint(
self,
**kwargs,
) -> _manifest.ManifestEndpoint:
assert kwargs["alert_type"] is not None
return FirebaseAlertOptions(
alert_type=kwargs["alert_type"],
app_id=self.app_id,
)._endpoint(**kwargs)
@_dataclasses.dataclass(frozen=True, kw_only=True)
class BillingOptions(EventHandlerOptions):
"""
Options specific to billing alert functions.
Internal use only.
"""
def _endpoint(
self,
**kwargs,
) -> _manifest.ManifestEndpoint:
assert kwargs["alert_type"] is not None
return FirebaseAlertOptions(
alert_type=kwargs["alert_type"],)._endpoint(**kwargs)
@_dataclasses.dataclass(frozen=True, kw_only=True)
class EventarcTriggerOptions(EventHandlerOptions):
"""
Options that can be set on an Eventarc trigger.
Internal use only.
"""
event_type: str
"""
Type of the event to trigger on.
"""
channel: str | None = None
"""
ID of the channel. Can be either:
* fully qualified channel resource name:
`projects/{project}/locations/{location}/channels/{channel-id}`
* partial resource name with location and channel ID, in which case
the runtime project ID of the function will be used:
`locations/{location}/channels/{channel-id}`
* partial channel ID, in which case the runtime project ID of the
function and `us-central1` as location will be used:
`{channel-id}`
If not specified, the default Firebase channel is used:
`projects/{project}/locations/us-central1/channels/firebase`
"""
filters: dict[str, str] | None = None
"""
Eventarc event exact match filter.
"""
def _endpoint(
self,
**kwargs,
) -> _manifest.ManifestEndpoint:
event_filters = {} if self.filters is None else self.filters
endpoint = _manifest.ManifestEndpoint(**_typing.cast(
_typing.Dict,
_dataclasses.asdict(super()._endpoint(
**kwargs,
event_filters=event_filters,
event_type=self.event_type,
))))
assert endpoint.eventTrigger is not None
channel = (self.channel if self.channel is not None else
"locations/us-central1/channels/firebase")
endpoint.eventTrigger["channel"] = channel
return endpoint
def _required_apis(self) -> list[_manifest.ManifestRequiredApi]:
return [
_manifest.ManifestRequiredApi(
api="eventarcpublishing.googleapis.com",
reason="Needed for custom event functions",
)
]
@_dataclasses.dataclass(frozen=True, kw_only=True)
class ScheduleOptions(RuntimeOptions):
"""
Options that can be set on a ``Schedule`` trigger.
"""
schedule: str
"""
The schedule, in Unix Crontab or AppEngine syntax.
"""
timezone: Timezone | Expression[str] | _util.Sentinel | None = None
"""
The timezone that the schedule executes in.
"""
retry_count: int | Expression[int] | _util.Sentinel | None = None
"""
The number of retry attempts for a failed run.
"""
max_retry_seconds: int | Expression[int] | _util.Sentinel | None = None
"""
The time limit for retrying.
"""
max_backoff_seconds: int | Expression[int] | _util.Sentinel | None = None
"""
The maximum amount of time to wait between attempts.
"""
max_doublings: int | Expression[int] | _util.Sentinel | None = None
"""
The maximum number of times to double the backoff between
retries.
"""
min_backoff_seconds: int | Expression[int] | _util.Sentinel | None = None
"""
The minimum time to wait between attempts.
"""
def _endpoint(
self,
**kwargs,
) -> _manifest.ManifestEndpoint:
retry_config: _manifest.RetryConfigScheduler = _manifest.RetryConfigScheduler(
retryCount=self.retry_count,
maxRetrySeconds=self.max_retry_seconds,
maxBackoffSeconds=self.max_backoff_seconds,
maxDoublings=self.max_doublings,
minBackoffSeconds=self.min_backoff_seconds,
)
time_zone: str | Expression[str] | _util.Sentinel | None = None
if isinstance(self.timezone, Timezone):
time_zone = self.timezone.key
else:
time_zone = self.timezone
kwargs_merged = {
**_dataclasses.asdict(super()._endpoint(**kwargs)),
"scheduleTrigger":
_manifest.ScheduleTrigger(
schedule=self.schedule,
timeZone=time_zone,
retryConfig=retry_config,
),
}
return _manifest.ManifestEndpoint(
**_typing.cast(_typing.Dict, kwargs_merged))
def _required_apis(self) -> list[_manifest.ManifestRequiredApi]:
return [
_manifest.ManifestRequiredApi(
api="cloudscheduler.googleapis.com",
reason="Needed for scheduled functions.",
)
]
@_dataclasses.dataclass(frozen=True, kw_only=True)
class StorageOptions(RuntimeOptions):
"""
Options specific to Cloud Storage function types.
Internal use only.
"""
bucket: str | Expression[str] | None = None
"""
The name of the bucket to watch for Storage events.
"""
def _endpoint(
self,
**kwargs,
) -> _manifest.ManifestEndpoint:
assert kwargs["event_type"] is not None
bucket = self.bucket
if bucket is None:
firebase_config = _util.firebase_config()
if firebase_config is not None:
bucket = firebase_config.storage_bucket
if bucket is None:
raise ValueError(
"Missing bucket name. If you are unit testing, please specify a bucket name"
" by providing a bucket name directly to the event handler or by setting the"
" FIREBASE_CONFIG environment variable.")
event_filters: _typing.Any = {
"bucket": bucket,
}
event_trigger = _manifest.EventTrigger(
eventType=kwargs["event_type"],
retry=False,
eventFilters=event_filters,
)
kwargs_merged = {
**_dataclasses.asdict(super()._endpoint(**kwargs)),
"eventTrigger":
event_trigger,
}
return _manifest.ManifestEndpoint(
**_typing.cast(_typing.Dict, kwargs_merged))
@_dataclasses.dataclass(frozen=True, kw_only=True)
class DatabaseOptions(RuntimeOptions):
"""
Options specific to Realtime Database function types.
Internal use only.
"""
reference: str
"""
Specify the handler to trigger on a database reference(s).
This value can either be a single reference or a pattern.
Examples: '/foo/bar', '/foo/{bar}'
"""
instance: str | None = None
"""
Specify the handler to trigger on a database instance(s).
If present, this value can either be a single instance or a pattern.
Examples: 'my-instance-1', 'my-instance-\\*'
Note: The capture syntax cannot be used for 'instance'.
"""
def _endpoint(
self,
**kwargs,
) -> _manifest.ManifestEndpoint:
assert kwargs["event_type"] is not None
assert kwargs["instance_pattern"] is not None
instance_pattern: _path_pattern.PathPattern = kwargs["instance_pattern"]
event_filter_instance = instance_pattern.value
event_filters: _typing.Any = {}
event_filters_path_patterns: _typing.Any = {
# Note: Eventarc always treats ref as a path pattern
"ref": self.reference.strip("/"),
}
if instance_pattern.has_wildcards:
event_filters_path_patterns["instance"] = event_filter_instance
else:
event_filters["instance"] = event_filter_instance
event_trigger = _manifest.EventTrigger(
eventType=kwargs["event_type"],
retry=False,
eventFilters=event_filters,
eventFilterPathPatterns=event_filters_path_patterns,
)
kwargs_merged = {
**_dataclasses.asdict(super()._endpoint(**kwargs)),
"eventTrigger":
event_trigger,
}
return _manifest.ManifestEndpoint(
**_typing.cast(_typing.Dict, kwargs_merged))
@_dataclasses.dataclass(frozen=True, kw_only=True)
class BlockingOptions(RuntimeOptions):
"""
Options that can be set on an Auth Blocking trigger.
Internal use only.
"""
id_token: bool | None = None
"""
Pass the ID Token credential to the function.
"""
access_token: bool | None = None
"""
Pass the access token credential to the function.
"""
refresh_token: bool | None = None
"""
Pass the refresh token credential to the function.
"""
def _endpoint(
self,
**kwargs,
) -> _manifest.ManifestEndpoint:
assert kwargs["event_type"] is not None
blocking_trigger = _manifest.BlockingTrigger(
eventType=kwargs["event_type"],