-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathapi.py
1475 lines (1301 loc) · 60 KB
/
api.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 2018 Google LLC
#
# 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
#
# https://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.
"""This module contains the "roll-up" class, :class:`~.API`.
Everything else in the :mod:`~.schema` module is usually accessed
through an :class:`~.API` object.
"""
import collections
import dataclasses
import itertools
import keyword
import os
import sys
from types import MappingProxyType
from typing import Callable, Container, Dict, FrozenSet, Mapping, Optional, Sequence, Set, Tuple
import yaml
from google.api_core import exceptions
from google.api import client_pb2 # type: ignore
from google.api import http_pb2 # type: ignore
from google.api import resource_pb2 # type: ignore
from google.api import service_pb2 # type: ignore
from google.cloud import extended_operations_pb2 as ex_ops_pb2 # type: ignore
from google.gapic.metadata import gapic_metadata_pb2 # type: ignore
from google.longrunning import operations_pb2 # type: ignore
from google.iam.v1 import iam_policy_pb2 # type: ignore
from google.cloud.location import locations_pb2 # type: ignore
from google.protobuf import descriptor_pb2 # type: ignore
from google.protobuf.json_format import MessageToJson
from google.protobuf.json_format import ParseDict
from google.protobuf.descriptor import ServiceDescriptor
import grpc # type: ignore
from google.protobuf.descriptor_pb2 import MethodDescriptorProto
from google.api import annotations_pb2 # type: ignore
from gapic.schema import metadata
from gapic.schema import mixins
from gapic.schema import wrappers
from gapic.schema import naming as api_naming
from gapic.utils import cached_property
from gapic.utils import nth
from gapic.utils import Options
from gapic.utils import to_snake_case
from gapic.utils import RESERVED_NAMES
TRANSPORT_GRPC = "grpc"
TRANSPORT_GRPC_ASYNC = "grpc-async"
TRANSPORT_REST = "rest"
class MethodSettingsError(ValueError):
"""
Raised when `google.api.client_pb2.MethodSettings` contains
an invalid value.
"""
pass
class ClientLibrarySettingsError(ValueError):
"""
Raised when `google.api.client_pb2.ClientLibrarySettings` contains
an invalid value.
"""
pass
@dataclasses.dataclass(frozen=True)
class Proto:
"""A representation of a particular proto file within an API."""
file_pb2: descriptor_pb2.FileDescriptorProto
services: Mapping[str, wrappers.Service]
all_messages: Mapping[str, wrappers.MessageType]
all_enums: Mapping[str, wrappers.EnumType]
file_to_generate: bool
meta: metadata.Metadata = dataclasses.field(
default_factory=metadata.Metadata,
)
def __getattr__(self, name: str):
return getattr(self.file_pb2, name)
@classmethod
def build(
cls,
file_descriptor: descriptor_pb2.FileDescriptorProto,
file_to_generate: bool,
naming: api_naming.Naming,
opts: Options = Options(),
prior_protos: Optional[Mapping[str, 'Proto']] = None,
load_services: bool = True,
all_resources: Optional[Mapping[str, wrappers.MessageType]] = None,
) -> 'Proto':
"""Build and return a Proto instance.
Args:
file_descriptor (~.FileDescriptorProto): The protocol buffer
object describing the proto file.
file_to_generate (bool): Whether this is a file which is
to be directly generated, or a dependency.
naming (~.Naming): The :class:`~.Naming` instance associated
with the API.
prior_protos (~.Proto): Previous, already processed protos.
These are needed to look up messages in imported protos.
load_services (bool): Toggle whether the proto file should
load its services. Not doing so enables a two-pass fix for
LRO response and metadata types in certain situations.
"""
return _ProtoBuilder(
file_descriptor,
file_to_generate=file_to_generate,
naming=naming,
opts=opts,
prior_protos=prior_protos or {},
load_services=load_services,
all_resources=all_resources or {},
).proto
@cached_property
def enums(self) -> Mapping[str, wrappers.EnumType]:
"""Return top-level enums on the proto."""
return collections.OrderedDict([
(k, v) for k, v in self.all_enums.items()
if not v.meta.address.parent
])
@cached_property
def messages(self) -> Mapping[str, wrappers.MessageType]:
"""Return top-level messages on the proto."""
return collections.OrderedDict(
(k, v) for k, v in self.all_messages.items()
if not v.meta.address.parent
)
@cached_property
def resource_messages(self) -> Mapping[str, wrappers.MessageType]:
"""Return the file level resources of the proto."""
file_resource_messages = (
(res.type, wrappers.CommonResource.build(res).message_type)
for res in self.file_pb2.options.Extensions[resource_pb2.resource_definition]
)
resource_messages = (
(msg.options.Extensions[resource_pb2.resource].type, msg)
for msg in self.messages.values()
if msg.options.Extensions[resource_pb2.resource].type
)
return collections.OrderedDict(
itertools.chain(
file_resource_messages, resource_messages,
)
)
@property
def module_name(self) -> str:
"""Return the appropriate module name for this service.
Returns:
str: The module name for this service (which is the service
name in snake case).
"""
return to_snake_case(self.name.split('/')[-1][:-len('.proto')])
@cached_property
def names(self) -> FrozenSet[str]:
"""Return a set of names used by this proto.
This is used for detecting naming collisions in the module names
used for imports.
"""
# Add names of all enums, messages, and fields.
answer: Set[str] = {e.name for e in self.all_enums.values()}
for message in self.all_messages.values():
answer.update(f.name for f in message.fields.values())
answer.add(message.name)
# Identify any import module names where the same module name is used
# from distinct packages.
modules: Dict[str, Set[str]] = collections.defaultdict(set)
for m in self.all_messages.values():
for t in m.recursive_field_types:
modules[t.ident.module].add(t.ident.package)
answer.update(
module_name
for module_name, packages in modules.items()
if len(packages) > 1 or module_name in RESERVED_NAMES
)
# Return the set of collision names.
return frozenset(answer)
@cached_property
def python_modules(self) -> Sequence[Tuple[str, str]]:
"""Return a sequence of Python modules, for import.
The results of this method are in alphabetical order (by package,
then module), and do not contain duplicates.
Returns:
Sequence[Tuple[str, str]]: The package and module pair, intended
for use in a ``from package import module`` type
of statement.
"""
self_reference = self.meta.address.python_import
answer = {
t.ident.python_import
for m in self.all_messages.values()
# Quick check: We do make sure that we are not trying to have
# a module import itself.
for t in m.field_types if t.ident.python_import != self_reference
}
# Done; return the sorted sequence.
return tuple(sorted(answer))
def disambiguate(self, string: str) -> str:
"""Return a disambiguated string for the context of this proto.
This is used for avoiding naming collisions. Generally, this method
returns the same string, but it returns a modified version if
it will cause a naming collision with messages or fields in this proto.
"""
if string in self.names:
return self.disambiguate(f'_{string}')
return string
@dataclasses.dataclass(frozen=True)
class API:
"""A representation of a full API.
This represents a top-down view of a complete API, as loaded from a
set of protocol buffer files. Once the descriptors are loaded
(see :meth:`load`), this object contains every message, method, service,
and everything else needed to write a client library.
An instance of this object is made available to every template
(as ``api``).
"""
naming: api_naming.Naming
all_protos: Mapping[str, Proto]
service_yaml_config: service_pb2.Service
subpackage_view: Tuple[str, ...] = dataclasses.field(default_factory=tuple)
@classmethod
def build(
cls,
file_descriptors: Sequence[descriptor_pb2.FileDescriptorProto],
package: str = '',
opts: Options = Options(),
prior_protos: Optional[Mapping[str, 'Proto']] = None,
) -> 'API':
"""Build the internal API schema based on the request.
Args:
file_descriptors (Sequence[~.FileDescriptorProto]): A list of
:class:`~.FileDescriptorProto` objects describing the
API.
package (str): A protocol buffer package, as a string, for which
code should be explicitly generated (including subpackages).
Protos with packages outside this list are considered imports
rather than explicit targets.
opts (~.options.Options): CLI options passed to the generator.
prior_protos (~.Proto): Previous, already processed protos.
These are needed to look up messages in imported protos.
Primarily used for testing.
"""
# Save information about the overall naming for this API.
naming = api_naming.Naming.build(*filter(
lambda fd: fd.package.startswith(package),
file_descriptors,
), opts=opts)
# "metadata", "retry", "timeout", and "request" are reserved words in client methods.
invalid_module_names = set(keyword.kwlist) | {
"metadata", "retry", "timeout", "request"}
def disambiguate_keyword_sanitize_fname(
full_path: str,
visited_names: Container[str]) -> str:
path, fname = os.path.split(full_path)
name, ext = os.path.splitext(fname)
# Replace `.` with `_` in the basename as
# `.` is not a valid character for modules names.
# See https://peps.python.org/pep-0008/#package-and-module-names
if "." in name:
name = name.replace(".", "_")
full_path = os.path.join(path, name + ext)
if name in invalid_module_names or full_path in visited_names:
name += "_"
full_path = os.path.join(path, name + ext)
if full_path in visited_names:
return disambiguate_keyword_sanitize_fname(full_path, visited_names)
return full_path
# Iterate over each FileDescriptorProto and fill out a Proto
# object describing it, and save these to the instance.
#
# The first pass gathers messages and enums but NOT services or methods.
# This is a workaround for a limitation in protobuf annotations for
# long running operations: the annotations are strings that reference
# message types but do not require a proto import.
# This hack attempts to address a common case where API authors,
# not wishing to generate an 'unused import' warning,
# don't import the proto file defining the real response or metadata
# type into the proto file that defines an LRO.
# We just load all the APIs types first and then
# load the services and methods with the full scope of types.
pre_protos: Dict[str, Proto] = dict(prior_protos or {})
for fd in file_descriptors:
fd.name = disambiguate_keyword_sanitize_fname(fd.name, pre_protos)
pre_protos[fd.name] = Proto.build(
file_descriptor=fd,
file_to_generate=fd.package.startswith(package),
naming=naming,
opts=opts,
prior_protos=pre_protos,
# Ugly, ugly hack.
load_services=False,
)
# A file descriptor's file-level resources are NOT visible to any importers.
# The only way to make referenced resources visible is to aggregate them at
# the API level and then pass that around.
all_file_resources = collections.ChainMap(
*(proto.resource_messages for proto in pre_protos.values())
)
# Second pass uses all the messages and enums defined in the entire API.
# This allows LRO returning methods to see all the types in the API,
# bypassing the above missing import problem.
protos: Dict[str, Proto] = {
name: Proto.build(
file_descriptor=proto.file_pb2,
file_to_generate=proto.file_to_generate,
naming=naming,
opts=opts,
prior_protos=pre_protos,
all_resources=MappingProxyType(all_file_resources),
)
for name, proto in pre_protos.items()
}
# Parse the google.api.Service proto from the service_yaml data.
service_yaml_config = service_pb2.Service()
ParseDict(
opts.service_yaml_config,
service_yaml_config,
ignore_unknown_fields=True
)
# Done; return the API.
return cls(naming=naming,
all_protos=protos,
service_yaml_config=service_yaml_config)
@cached_property
def enums(self) -> Mapping[str, wrappers.EnumType]:
"""Return a map of all enums available in the API."""
return collections.ChainMap({},
*[p.all_enums for p in self.protos.values()],
)
@cached_property
def messages(self) -> Mapping[str, wrappers.MessageType]:
"""Return a map of all messages available in the API."""
return collections.ChainMap({},
*[p.all_messages for p in self.protos.values()],
)
@cached_property
def top_level_messages(self) -> Mapping[str, wrappers.MessageType]:
"""Return a map of all messages that are NOT nested."""
return {
k: v
for p in self.protos.values()
for k, v in p.messages.items()
}
@cached_property
def top_level_enums(self) -> Mapping[str, wrappers.EnumType]:
"""Return a map of all messages that are NOT nested."""
return {
k: v
for p in self.protos.values()
for k, v in p.enums.items()
}
@cached_property
def protos(self) -> Mapping[str, Proto]:
"""Return a map of all protos specific to this API.
This property excludes imported protos that are dependencies
of this API but not being directly generated.
"""
view = self.subpackage_view
return collections.OrderedDict([
(k, v) for k, v in self.all_protos.items()
if v.file_to_generate and
v.meta.address.subpackage[:len(view)] == view
])
@cached_property
def services(self) -> Mapping[str, wrappers.Service]:
"""Return a map of all services available in the API."""
return collections.ChainMap({},
*[p.services for p in self.protos.values()],
)
@cached_property
def http_options(self) -> Mapping[str, Sequence[wrappers.HttpRule]]:
"""Return a map of API-wide http rules."""
def make_http_options(rule: http_pb2.HttpRule
) -> Sequence[wrappers.HttpRule]:
http_options = [rule] + list(rule.additional_bindings)
opt_gen = (wrappers.HttpRule.try_parse_http_rule(http_rule)
for http_rule in http_options)
return [rule for rule in opt_gen if rule]
result: Mapping[str, Sequence[http_pb2.HttpRule]] = {
rule.selector: make_http_options(rule)
for rule in self.service_yaml_config.http.rules
}
return result
@cached_property
def subpackages(self) -> Mapping[str, 'API']:
"""Return a map of all subpackages, if any.
Each value in the mapping is another API object, but the ``protos``
property only shows protos belonging to the subpackage.
"""
answer: Dict[str, API] = collections.OrderedDict()
# Get the actual subpackages we have.
#
# Note that this intentionally only goes one level deep; nested
# subpackages can be accessed by requesting subpackages of the
# derivative API objects returned here.
level = len(self.subpackage_view)
for subpkg_name in sorted({p.meta.address.subpackage[0]
for p in self.protos.values()
if len(p.meta.address.subpackage) > level and
p.meta.address.subpackage[:level] == self.subpackage_view}):
answer[subpkg_name] = dataclasses.replace(self,
subpackage_view=self.subpackage_view +
(subpkg_name,),
)
return answer
def gapic_metadata(self, options: Options) -> gapic_metadata_pb2.GapicMetadata:
gm = gapic_metadata_pb2.GapicMetadata(
schema="1.0",
comment="This file maps proto services/RPCs to the corresponding library clients/methods",
language="python",
proto_package=self.naming.proto_package,
library_package=".".join(
self.naming.module_namespace +
(self.naming.versioned_module_name,)
),
)
for service in sorted(self.services.values(), key=lambda s: s.name):
service_desc = gm.services.get_or_create(service.name)
# At least one of "grpc" or "rest" is guaranteed to be present because
# of the way that Options instances are created.
# This assumes the options are generated by the class method factory.
transports = []
if "grpc" in options.transport:
transports.append((TRANSPORT_GRPC, service.client_name))
transports.append(
(TRANSPORT_GRPC_ASYNC, service.async_client_name))
if "rest" in options.transport:
transports.append((TRANSPORT_REST, service.client_name))
methods = sorted(service.methods.values(), key=lambda m: m.name)
for tprt, client_name in transports:
transport = service_desc.clients.get_or_create(tprt)
transport.library_client = client_name
for method in methods:
method_desc = transport.rpcs.get_or_create(method.name)
method_desc.methods.append(to_snake_case(method.name))
return gm
def gapic_metadata_json(self, options: Options) -> str:
return MessageToJson(self.gapic_metadata(options), sort_keys=True)
def requires_package(self, pkg: Tuple[str, ...]) -> bool:
pkg_has_iam_mixin = self.has_iam_mixin and \
pkg == ('google', 'iam', 'v1')
return pkg_has_iam_mixin or any(
message.ident.package == pkg
for proto in self.all_protos.values()
for message in proto.all_messages.values()
)
def get_custom_operation_service(self, method: "wrappers.Method") -> "wrappers.Service":
"""Return the extended operation service that should be polled for progress
from a given initial method.
Precondition: `method` returns an Extended Operation type message
and has an `operation_polling_service` annotation.
"""
if not method.output.is_extended_operation:
raise ValueError(
f"Method is not an extended operation LRO: {method.name}")
op_serv_name = self.naming.proto_package + "." + \
method.options.Extensions[ex_ops_pb2.operation_service]
op_serv = self.services.get(op_serv_name)
if not op_serv:
raise ValueError(
f"No such service: {op_serv_name}"
)
if not op_serv.operation_polling_method:
raise ValueError(
f"Service is not an extended operation operation service: {op_serv.name}")
return op_serv
@cached_property
def mixin_api_signatures(self):
"""Compile useful info about MixIn API signatures.
Returns:
Mapping[str, wrappers.MixinMethod]: Useful info
about MixIn methods present for the main API.
"""
return {name: mixins.MIXINS_MAP[name] for name in self.mixin_api_methods}
@cached_property
def mixin_api_methods(self) -> Dict[str, MethodDescriptorProto]:
methods: Dict[str, MethodDescriptorProto] = {}
if self.has_location_mixin:
methods = {**methods, **
self._get_methods_from_service(locations_pb2)}
if not self._has_iam_overrides and self.has_iam_mixin:
methods = {**methods, **
self._get_methods_from_service(iam_policy_pb2)}
if self.has_operations_mixin:
methods = {**methods, **
self._get_methods_from_service(operations_pb2)}
return methods
@cached_property
def mixin_http_options(self):
"""Gather HTTP options for the MixIn methods."""
api_methods = self.mixin_api_methods
res = {}
for s in api_methods:
m = api_methods[s]
http = m.options.Extensions[annotations_pb2.http]
http_options = [http] + list(http.additional_bindings)
opt_gen = (wrappers.MixinHttpRule.try_parse_http_rule(http_rule)
for http_rule in http_options)
res[s] = [rule for rule in opt_gen if rule]
return res
@cached_property
def all_methods(self) -> Mapping[str, MethodDescriptorProto]:
"""Return a map of all methods for the API.
Returns:
Mapping[str, MethodDescriptorProto]: A mapping of MethodDescriptorProto
values for the API.
"""
return {
f"{service_key}.{method_key}": method_value
for service_key, service_value in self.services.items()
for method_key, method_value in service_value.methods.items()
}
def enforce_valid_method_settings(
self, service_method_settings: Sequence[client_pb2.MethodSettings]
) -> None:
"""
Checks each `google.api.client.MethodSettings` provided for validity and
raises an exception if invalid values are found. If
`google.api.client.MethodSettings.auto_populated_fields`
is set, verify each field against the criteria of AIP-4235
(https://google.aip.dev/client-libraries/4235). All of the conditions
below must be true:
- The field must be of type string
- The field must be at the top-level of the request message
- The RPC must be a unary RPC (i.e. streaming RPCs are not supported)
- The field must not be annotated with google.api.field_behavior = REQUIRED.
- The field must be annotated with google.api.field_info.format = UUID4.
Note that the field presence requirements in AIP-4235 should be checked at run
time.
Args:
service_method_settings (Sequence[client_pb2.MethodSettings]): Method
settings to be used when generating API methods.
Returns:
None
Raises:
MethodSettingsError: if fields in `method_settings.auto_populated_fields`
cannot be automatically populated.
"""
all_errors: dict = {}
selectors_seen: set = set()
for method_settings in service_method_settings:
# Check if this selector is defind more than once
if method_settings.selector in selectors_seen:
all_errors[method_settings.selector] = ["Duplicate selector"]
continue
selectors_seen.add(method_settings.selector)
method_descriptor = self.all_methods.get(method_settings.selector)
# Check if this selector can be mapped to a method in the API.
if not method_descriptor:
all_errors[method_settings.selector] = [
"Method was not found."
]
continue
if method_settings.auto_populated_fields:
# Check if the selector maps to a streaming method
if (
method_descriptor.client_streaming
or method_descriptor.server_streaming
):
all_errors[method_settings.selector] = [
"Method is not a unary method."
]
continue
top_level_request_message = self.messages[
method_descriptor.input_type.lstrip(".")
]
selector_errors = []
for field_str in method_settings.auto_populated_fields:
if field_str not in top_level_request_message.fields:
selector_errors.append(
f"Field `{field_str}` was not found"
)
else:
field = top_level_request_message.fields[field_str]
if field.type != wrappers.PrimitiveType.build(str):
selector_errors.append(
f"Field `{field_str}` is not of type string."
)
if field.required:
selector_errors.append(
f"Field `{field_str}` is a required field."
)
if not field.uuid4:
selector_errors.append(
f"Field `{field_str}` is not annotated with "
"`google.api.field_info.format = \"UUID4\"."
)
if selector_errors:
all_errors[method_settings.selector] = selector_errors
if all_errors:
raise MethodSettingsError(yaml.dump(all_errors))
@cached_property
def all_library_settings(
self,
) -> Mapping[str, Sequence[client_pb2.ClientLibrarySettings]]:
"""Return a map of all `google.api.client.ClientLibrarySettings` to be used
when generating client libraries.
https://github.com/googleapis/googleapis/blob/master/google/api/client.proto#L130
Returns:
Mapping[str, Sequence[client_pb2.ClientLibrarySettings]]: A mapping of all library
settings read from the service YAML.
Raises:
gapic.schema.api.ClientLibrarySettingsError: Raised when `google.api.client_pb2.ClientLibrarySettings`
contains an invalid value.
"""
self.enforce_valid_library_settings(
self.service_yaml_config.publishing.library_settings
)
result = {
library_setting.version: client_pb2.ClientLibrarySettings(
version=library_setting.version,
python_settings=library_setting.python_settings,
)
for library_setting in self.service_yaml_config.publishing.library_settings
}
# NOTE: Add default settings for the current proto package
# for the following cases:
# - if library settings are not specified in the service config.
# - if library_settings.version != self.naming.proto_package (proto package name)
if self.naming.proto_package not in result:
result[self.naming.proto_package] = client_pb2.ClientLibrarySettings(
version=self.naming.proto_package
)
return result
def enforce_valid_library_settings(
self, client_library_settings: Sequence[client_pb2.ClientLibrarySettings]
) -> None:
"""
Checks each `google.api.client.ClientLibrarySettings` provided for validity and
raises an exception if invalid values are found.
Args:
client_library_settings (Sequence[client_pb2.ClientLibrarySettings]): Client
library settings to be used when generating API methods.
Returns:
None
Raises:
ClientLibrarySettingsError: if fields in `client_library_settings.experimental_features`
are not supported.
"""
all_errors: dict = {}
versions_seen: set = set()
for library_settings in client_library_settings:
# Check if this version is defind more than once
if library_settings.version in versions_seen:
all_errors[library_settings.version] = ["Duplicate version"]
continue
versions_seen.add(library_settings.version)
if all_errors:
raise ClientLibrarySettingsError(yaml.dump(all_errors))
@cached_property
def all_method_settings(self) -> Mapping[str, Sequence[client_pb2.MethodSettings]]:
"""Return a map of all `google.api.client.MethodSettings` to be used
when generating methods.
https://github.com/googleapis/googleapis/blob/7dab3de7ec79098bb367b6b2ac3815512a49dd56/google/api/client.proto#L325
Returns:
Mapping[str, Sequence[client_pb2.MethodSettings]]: A mapping of all method
settings read from the service YAML.
Raises:
gapic.schema.api.MethodSettingsError: if the method settings do not
meet the requirements of https://google.aip.dev/client-libraries/4235.
"""
self.enforce_valid_method_settings(
self.service_yaml_config.publishing.method_settings
)
return {
method_setting.selector: client_pb2.MethodSettings(
selector=method_setting.selector,
long_running=method_setting.long_running,
auto_populated_fields=method_setting.auto_populated_fields,
)
for method_setting in self.service_yaml_config.publishing.method_settings
}
@cached_property
def has_location_mixin(self) -> bool:
return len(list(filter(lambda api: api.name == "google.cloud.location.Locations", self.service_yaml_config.apis))) > 0
@cached_property
def has_iam_mixin(self) -> bool:
return len(list(filter(lambda api: api.name == "google.iam.v1.IAMPolicy", self.service_yaml_config.apis))) > 0
@cached_property
def has_operations_mixin(self) -> bool:
return len(list(filter(lambda api: api.name == "google.longrunning.Operations", self.service_yaml_config.apis))) > 0
@cached_property
def _has_iam_overrides(self) -> bool:
if not self.has_iam_mixin:
return False
iam_mixin_methods: Dict[str, MethodDescriptorProto] = self._get_methods_from_service(
iam_policy_pb2)
for (_, s) in self.services.items():
for m_name in iam_mixin_methods:
if m_name in s.methods:
return True
return False
def _get_methods_from_service(self, service_pb) -> Dict[str, MethodDescriptorProto]:
services = service_pb.DESCRIPTOR.services_by_name
methods = {}
methods_to_generate = {}
for service_name in services:
service: ServiceDescriptor = services[service_name]
for method in service.methods:
fqn = "{}.{}.{}".format(
service_pb.DESCRIPTOR.package, service.name, method.name)
methods[fqn] = method
for rule in self.service_yaml_config.http.rules:
if rule.selector in methods:
m = methods[rule.selector]
x = descriptor_pb2.MethodDescriptorProto()
m.CopyToProto(x)
x.options.Extensions[annotations_pb2.http].CopyFrom(rule)
methods_to_generate[x.name] = x
return methods_to_generate
def get_extended_operations_services(self, service) -> Set["wrappers.Service"]:
"""Return a set of all the extended operation services used by the input service.
Precondition: `service` is NOT an extended operation service
"""
return set(
self.get_custom_operation_service(m)
for m in service.methods.values()
if m.operation_service
)
class _ProtoBuilder:
"""A "builder class" for Proto objects.
The sole purpose of this class is to accept the information from the
file descriptor and "piece together" the components of the :class:`~.Proto`
object in-place.
This allows the public :class:`~.Proto` object to be frozen, and free
of the setup machinations.
The correct usage of this class is always to create an instance, call
the :attr:`proto` property, and then throw the builder away. Additionally,
there should be no reason to use this class outside of this module.
"""
EMPTY = descriptor_pb2.SourceCodeInfo.Location()
def __init__(
self,
file_descriptor: descriptor_pb2.FileDescriptorProto,
file_to_generate: bool,
naming: api_naming.Naming,
opts: Options = Options(),
prior_protos: Optional[Mapping[str, Proto]] = None,
load_services: bool = True,
all_resources: Optional[Mapping[str, wrappers.MessageType]] = None,
):
self.proto_messages: Dict[str, wrappers.MessageType] = {}
self.proto_enums: Dict[str, wrappers.EnumType] = {}
self.proto_services: Dict[str, wrappers.Service] = {}
self.file_descriptor = file_descriptor
self.file_to_generate = file_to_generate
self.prior_protos = prior_protos or {}
self.opts = opts
# Iterate over the documentation and place it into a dictionary.
#
# The comments in protocol buffers are sorted by a concept called
# the "path", which is a sequence of integers described in more
# detail below; this code simply shifts from a list to a dict,
# with tuples of paths as the dictionary keys.
self.docs: Dict[Tuple[int, ...],
descriptor_pb2.SourceCodeInfo.Location] = {}
for location in file_descriptor.source_code_info.location:
self.docs[tuple(location.path)] = location
# Everything has an "address", which is the proto where the thing
# was declared.
#
# We put this together by a baton pass of sorts: everything in
# this file *starts with* this address, which is appended to
# for each item as it is loaded.
self.address = metadata.Address(
api_naming=naming,
module=file_descriptor.name.split('/')[-1][:-len('.proto')],
package=tuple(file_descriptor.package.split('.')),
)
# Now iterate over the FileDescriptorProto and pull out each of
# the messages, enums, and services.
#
# The hard-coded path keys sent here are based on how descriptor.proto
# works; it uses the proto message number of the pieces of each
# message (e.g. the hard-code `4` for `message_type` immediately
# below is because `repeated DescriptorProto message_type = 4;` in
# descriptor.proto itself).
self._load_children(file_descriptor.enum_type, self._load_enum,
address=self.address, path=(5,),
resources=all_resources or {})
self._load_children(file_descriptor.message_type, self._load_message,
address=self.address, path=(4,),
resources=all_resources or {})
# Edge case: Protocol buffers is not particularly picky about
# ordering, and it is possible that a message will have had a field
# referencing another message which appears later in the file
# (or itself, recursively).
#
# In this situation, we would not have come across the message yet,
# and the field would have its original textual reference to the
# message (`type_name`) but not its resolved message wrapper.
orphan_field_gen = (
(field.type_name.lstrip('.'), field)
for message in self.proto_messages.values()
for field in message.fields.values()
if field.type_name and not (field.message or field.enum)
)
for key, field in orphan_field_gen:
maybe_msg_type = self.proto_messages.get(key)
maybe_enum_type = self.proto_enums.get(key)
if maybe_msg_type:
object.__setattr__(field, 'message', maybe_msg_type)
elif maybe_enum_type:
object.__setattr__(field, 'enum', maybe_enum_type)
else:
raise TypeError(
f"Unknown type referenced in "
f"{self.file_descriptor.name}: '{key}'"
)
# Only generate the service if this is a target file to be generated.
# This prevents us from generating common services (e.g. LRO) when
# they are being used as an import just to get types declared in the
# same files.
if file_to_generate and load_services:
self._load_children(file_descriptor.service, self._load_service,
address=self.address, path=(6,),
resources=all_resources or {})
# TODO(lukesneeringer): oneofs are on path 7.
@property
def proto(self) -> Proto:
"""Return a Proto dataclass object."""
# Create a "context-naïve" proto.
# This has everything but is ignorant of naming collisions in the
# ultimate file that will be written.
naive = Proto(
all_enums=self.proto_enums,
all_messages=self.proto_messages,
file_pb2=self.file_descriptor,
file_to_generate=self.file_to_generate,
services=self.proto_services,
meta=metadata.Metadata(
address=self.address,
),
)
# If this is not a file being generated, we do not need to
# do anything else.
if not self.file_to_generate:
return naive
visited_messages: Set[wrappers.MessageType] = set()
# Return a context-aware proto object.
return dataclasses.replace(
naive,
all_enums=collections.OrderedDict(
(k, v.with_context(collisions=naive.names))
for k, v in naive.all_enums.items()
),
all_messages=collections.OrderedDict(
(k, v.with_context(
collisions=naive.names,
visited_messages=visited_messages,
))
for k, v in naive.all_messages.items()
),
services=collections.OrderedDict(
# Note: services bind to themselves because services get their
# own output files.
(k, v.with_context(
collisions=v.names,
visited_messages=visited_messages,
))
for k, v in naive.services.items()
),
meta=naive.meta.with_context(collisions=naive.names),
)
@cached_property
def api_enums(self) -> Mapping[str, wrappers.EnumType]:
return collections.ChainMap(
{},
self.proto_enums,
# This is actually fine from a typing perspective:
# we're agglutinating all the prior protos' enums, which are
# stored in maps. This is just a convenient way to expand it out.
*[p.all_enums for p in self.prior_protos.values()], # type: ignore
)
@cached_property