-
Notifications
You must be signed in to change notification settings - Fork 48
/
Parser.java
1118 lines (1032 loc) · 50.3 KB
/
Parser.java
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 2020 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
//
// 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.
package com.google.api.generator.gapic.protoparser;
import com.google.api.ClientProto;
import com.google.api.DocumentationRule;
import com.google.api.HttpRule;
import com.google.api.ResourceDescriptor;
import com.google.api.ResourceProto;
import com.google.api.generator.engine.ast.TypeNode;
import com.google.api.generator.engine.ast.VaporReference;
import com.google.api.generator.gapic.model.Field;
import com.google.api.generator.gapic.model.GapicBatchingSettings;
import com.google.api.generator.gapic.model.GapicContext;
import com.google.api.generator.gapic.model.GapicLanguageSettings;
import com.google.api.generator.gapic.model.GapicLroRetrySettings;
import com.google.api.generator.gapic.model.GapicServiceConfig;
import com.google.api.generator.gapic.model.HttpBindings;
import com.google.api.generator.gapic.model.LongrunningOperation;
import com.google.api.generator.gapic.model.Message;
import com.google.api.generator.gapic.model.Method;
import com.google.api.generator.gapic.model.OperationResponse;
import com.google.api.generator.gapic.model.ResourceName;
import com.google.api.generator.gapic.model.ResourceReference;
import com.google.api.generator.gapic.model.Service;
import com.google.api.generator.gapic.model.SourceCodeInfoLocation;
import com.google.api.generator.gapic.model.Transport;
import com.google.api.generator.gapic.utils.ResourceNameConstants;
import com.google.cloud.ExtendedOperationsProto;
import com.google.cloud.OperationResponseMapping;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.longrunning.OperationInfo;
import com.google.longrunning.OperationsProto;
import com.google.protobuf.DescriptorProtos.FieldOptions;
import com.google.protobuf.DescriptorProtos.FileDescriptorProto;
import com.google.protobuf.DescriptorProtos.MessageOptions;
import com.google.protobuf.DescriptorProtos.MethodOptions;
import com.google.protobuf.DescriptorProtos.ServiceOptions;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.DescriptorValidationException;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.Descriptors.MethodDescriptor;
import com.google.protobuf.Descriptors.ServiceDescriptor;
import com.google.protobuf.compiler.PluginProtos.CodeGeneratorRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Parser {
private static final String COMMA = ",";
private static final String COLON = ":";
private static final String DEFAULT_PORT = "443";
private static final String DOT = ".";
private static final String SLASH = "/";
private static final ResourceName WILDCARD_RESOURCE_NAME =
ResourceName.createWildcard("*", "com.google.api.wildcard.placeholder");
// Mirrors the sanitizer allowlist.
private static final Set<String> MIXIN_ALLOWLIST =
ImmutableSet.of(
"google.iam.v1.IAMPolicy",
"google.longrunning.Operations",
"google.cloud.location.Locations");
// These must be kept in sync with the above protos' java_package options.
private static final Set<String> MIXIN_JAVA_PACKAGE_ALLOWLIST =
ImmutableSet.of("com.google.iam.v1", "com.google.longrunning", "com.google.cloud.location");
// Allow other parsers to access this.
protected static final SourceCodeInfoParser SOURCE_CODE_INFO_PARSER = new SourceCodeInfoParser();
static class GapicParserException extends RuntimeException {
public GapicParserException(String errorMessage) {
super(errorMessage);
}
}
public static GapicContext parse(CodeGeneratorRequest request) {
Optional<String> gapicYamlConfigPathOpt =
PluginArgumentParser.parseGapicYamlConfigPath(request);
Optional<List<GapicBatchingSettings>> batchingSettingsOpt =
BatchingSettingsConfigParser.parse(gapicYamlConfigPathOpt);
Optional<List<GapicLroRetrySettings>> lroRetrySettingsOpt =
GapicLroRetrySettingsParser.parse(gapicYamlConfigPathOpt);
Optional<GapicLanguageSettings> languageSettingsOpt =
GapicLanguageSettingsParser.parse(gapicYamlConfigPathOpt);
Optional<String> transportOpt = PluginArgumentParser.parseTransport(request);
boolean willGenerateMetadata = PluginArgumentParser.hasMetadataFlag(request);
Optional<String> serviceConfigPathOpt = PluginArgumentParser.parseJsonConfigPath(request);
String serviceConfigPath = serviceConfigPathOpt.isPresent() ? serviceConfigPathOpt.get() : null;
Optional<GapicServiceConfig> serviceConfigOpt = ServiceConfigParser.parse(serviceConfigPath);
if (serviceConfigOpt.isPresent()) {
GapicServiceConfig serviceConfig = serviceConfigOpt.get();
serviceConfig.setLroRetrySettings(lroRetrySettingsOpt);
serviceConfig.setBatchingSettings(batchingSettingsOpt);
serviceConfig.setLanguageSettings(languageSettingsOpt);
serviceConfigOpt = Optional.of(serviceConfig);
}
Optional<String> serviceYamlConfigPathOpt =
PluginArgumentParser.parseServiceYamlConfigPath(request);
Optional<com.google.api.Service> serviceYamlProtoOpt =
serviceYamlConfigPathOpt.isPresent()
? ServiceYamlParser.parse(serviceYamlConfigPathOpt.get())
: Optional.empty();
// Collect the resource references seen in messages.
Set<ResourceReference> outputResourceReferencesSeen = new HashSet<>();
// Keep message and resource name parsing separate for cleaner logic.
// While this takes an extra pass through the protobufs, the extra time is relatively trivial
// and is worth the larger reduced maintenance cost.
Map<String, Message> messages = parseMessages(request, outputResourceReferencesSeen);
Map<String, ResourceName> resourceNames = parseResourceNames(request);
messages = updateResourceNamesInMessages(messages, resourceNames.values());
// Contains only resource names that are actually used. Usage refers to the presence of a
// request message's field in an RPC's method_signature annotation. That is, resource name
// definitions
// or references that are simply defined, but not used in such a manner, will not have
// corresponding Java helper
// classes generated.
Set<ResourceName> outputArgResourceNames = new HashSet<>();
List<Service> mixinServices = new ArrayList<>();
Transport transport = Transport.parse(transportOpt.orElse(Transport.GRPC.toString()));
List<Service> services =
parseServices(
request,
messages,
resourceNames,
outputArgResourceNames,
serviceYamlProtoOpt,
serviceConfigOpt,
mixinServices,
transport);
Preconditions.checkState(!services.isEmpty(), "No services found to generate");
// TODO(vam-google): Figure out whether we should keep this allowlist or bring
// back the unused resource names for all APIs.
// Temporary workaround for Ads, who still need these resource names.
if (services.get(0).protoPakkage().startsWith("google.ads.googleads.v")) {
Function<ResourceName, String> typeNameFn =
r -> r.resourceTypeString().substring(r.resourceTypeString().indexOf("/") + 1);
Function<Set<ResourceName>, Set<String>> typeStringSetFn =
sr -> sr.stream().map(r -> typeNameFn.apply(r)).collect(Collectors.toSet());
// Include all resource names present in message types for backwards-compatibility with the
// monolith. In the future, this should be removed on a client library major semver update.
// Resolve type name collisions with the ones present in the method arguments.
final Set<String> typeStringSet = typeStringSetFn.apply(outputArgResourceNames);
outputArgResourceNames.addAll(
resourceNames.values().stream()
.filter(r -> r.hasParentMessageName() && !typeStringSet.contains(typeNameFn.apply(r)))
.collect(Collectors.toSet()));
String servicePackage = services.get(0).pakkage();
Map<String, ResourceName> patternsToResourceNames =
ResourceParserHelpers.createPatternResourceNameMap(resourceNames);
for (ResourceReference resourceReference : outputResourceReferencesSeen) {
final Set<String> interimTypeStringSet = typeStringSetFn.apply(outputArgResourceNames);
outputArgResourceNames.addAll(
ResourceReferenceParser.parseResourceNames(
resourceReference, servicePackage, null, resourceNames, patternsToResourceNames)
.stream()
.filter(r -> !interimTypeStringSet.contains(typeNameFn.apply(r)))
.collect(Collectors.toSet()));
}
}
return GapicContext.builder()
.setServices(services)
.setMixinServices(mixinServices)
.setMessages(messages)
.setResourceNames(resourceNames)
.setHelperResourceNames(outputArgResourceNames)
.setServiceConfig(serviceConfigOpt.isPresent() ? serviceConfigOpt.get() : null)
.setGapicMetadataEnabled(willGenerateMetadata)
.setServiceYamlProto(serviceYamlProtoOpt.isPresent() ? serviceYamlProtoOpt.get() : null)
.setTransport(transport)
.build();
}
public static List<Service> parseServices(
CodeGeneratorRequest request,
Map<String, Message> messageTypes,
Map<String, ResourceName> resourceNames,
Set<ResourceName> outputArgResourceNames,
Optional<com.google.api.Service> serviceYamlProtoOpt,
Optional<GapicServiceConfig> serviceConfigOpt,
List<Service> outputMixinServices,
Transport transport) {
Map<String, FileDescriptor> fileDescriptors = getFilesToGenerate(request);
List<Service> services = new ArrayList<>();
for (String fileToGenerate : request.getFileToGenerateList()) {
FileDescriptor fileDescriptor =
Preconditions.checkNotNull(
fileDescriptors.get(fileToGenerate),
"Missing file descriptor for [%s]",
fileToGenerate);
services.addAll(
parseService(
fileDescriptor,
messageTypes,
resourceNames,
serviceYamlProtoOpt,
serviceConfigOpt,
outputArgResourceNames,
transport));
}
// Prevent codegen for mixed-in services if there are other services present, since that is an
// indicator that we are not generating a GAPIC client for the mixed-in service on its own.
Function<Service, String> serviceFullNameFn =
s -> String.format("%s.%s", s.protoPakkage(), s.name());
Set<Service> blockedCodegenMixinApis = new HashSet<>();
Set<Service> definedServices = new HashSet<>();
for (Service s : services) {
if (MIXIN_ALLOWLIST.contains(serviceFullNameFn.apply(s))) {
blockedCodegenMixinApis.add(s);
} else {
definedServices.add(s);
}
}
// It's very unlikely the blocklisted APIs will contain the other, or any other service.
boolean servicesContainBlocklistedApi =
!blockedCodegenMixinApis.isEmpty() && !definedServices.isEmpty();
// Service names that are stated in the YAML file (as mixins). Used to filter
// blockedCodegenMixinApis.
Set<String> mixedInApis =
!serviceYamlProtoOpt.isPresent()
? Collections.emptySet()
: serviceYamlProtoOpt.get().getApisList().stream()
.filter(a -> MIXIN_ALLOWLIST.contains(a.getName()))
.map(a -> a.getName())
.collect(Collectors.toSet());
// Holds the methods to be mixed in.
// Key: proto_package.ServiceName.RpcName.
// Value: HTTP rules, which clobber those in the proto.
// Assumes that http.rules.selector always specifies RPC names in the above format.
Map<String, HttpBindings> mixedInMethodsToHttpRules = new HashMap<>();
Map<String, String> mixedInMethodsToDocs = new HashMap<>();
// Parse HTTP rules and documentation, which will override the proto.
if (serviceYamlProtoOpt.isPresent()) {
for (HttpRule httpRule : serviceYamlProtoOpt.get().getHttp().getRulesList()) {
HttpBindings httpBindings = HttpRuleParser.parseHttpRule(httpRule);
if (httpBindings == null) {
continue;
}
for (String rpcFullNameRaw : httpRule.getSelector().split(",")) {
String rpcFullName = rpcFullNameRaw.trim();
mixedInMethodsToHttpRules.put(rpcFullName, httpBindings);
}
}
for (DocumentationRule docRule :
serviceYamlProtoOpt.get().getDocumentation().getRulesList()) {
for (String rpcFullNameRaw : docRule.getSelector().split(",")) {
String rpcFullName = rpcFullNameRaw.trim();
mixedInMethodsToDocs.put(rpcFullName, docRule.getDescription());
}
}
}
// Sort potential mixin services alphabetically.
List<Service> orderedBlockedCodegenMixinApis =
blockedCodegenMixinApis.stream()
.sorted((s1, s2) -> s2.name().compareTo(s1.name()))
.collect(Collectors.toList());
Set<String> apiDefinedRpcs = new HashSet<>();
for (Service service : services) {
if (orderedBlockedCodegenMixinApis.contains(service)) {
continue;
}
apiDefinedRpcs.addAll(
service.methods().stream().map(m -> m.name()).collect(Collectors.toSet()));
}
// Mix-in APIs only if the protos are present and they're defined in the service.yaml file.
Set<Service> outputMixinServiceSet = new HashSet<>();
if (servicesContainBlocklistedApi && !mixedInApis.isEmpty()) {
for (int i = 0; i < services.size(); i++) {
Service originalService = services.get(i);
List<Method> updatedOriginalServiceMethods = new ArrayList<>(originalService.methods());
// If mixin APIs are present, add the methods to all other services.
for (Service mixinService : orderedBlockedCodegenMixinApis) {
final String mixinServiceFullName = serviceFullNameFn.apply(mixinService);
if (!mixedInApis.contains(mixinServiceFullName)) {
continue;
}
Function<Method, String> methodToFullProtoNameFn =
m -> String.format("%s.%s", mixinServiceFullName, m.name());
// Filter mixed-in methods based on those listed in the HTTP rules section of
// service.yaml.
List<Method> updatedMixinMethods =
mixinService.methods().stream()
// Mixin method inclusion is based on the HTTP rules list in service.yaml.
.filter(
m -> mixedInMethodsToHttpRules.containsKey(methodToFullProtoNameFn.apply(m)))
.map(
m -> {
// HTTP rules and RPC documentation in the service.yaml file take
// precedence.
String fullMethodName = methodToFullProtoNameFn.apply(m);
HttpBindings httpBindings =
mixedInMethodsToHttpRules.containsKey(fullMethodName)
? mixedInMethodsToHttpRules.get(fullMethodName)
: m.httpBindings();
String docs =
mixedInMethodsToDocs.containsKey(fullMethodName)
? mixedInMethodsToDocs.get(fullMethodName)
: m.description();
return m.toBuilder()
.setHttpBindings(httpBindings)
.setDescription(docs)
.build();
})
.collect(Collectors.toList());
// Overridden RPCs defined in the protos take precedence.
updatedMixinMethods.stream()
.filter(m -> !apiDefinedRpcs.contains(m.name()))
.forEach(
m ->
updatedOriginalServiceMethods.add(
m.toBuilder()
.setMixedInApiName(serviceFullNameFn.apply(mixinService))
.build()));
// Sort by method name, to ensure a deterministic method ordering (for tests).
updatedMixinMethods =
updatedMixinMethods.stream()
.sorted((m1, m2) -> m2.name().compareTo(m1.name()))
.collect(Collectors.toList());
outputMixinServiceSet.add(
mixinService.toBuilder().setMethods(updatedMixinMethods).build());
}
services.set(
i, originalService.toBuilder().setMethods(updatedOriginalServiceMethods).build());
}
}
if (servicesContainBlocklistedApi) {
services =
services.stream()
.filter(s -> !MIXIN_ALLOWLIST.contains(serviceFullNameFn.apply(s)))
.collect(Collectors.toList());
}
// Use a list to ensure ordering for deterministic tests.
outputMixinServices.addAll(
outputMixinServiceSet.stream()
.sorted((s1, s2) -> s2.name().compareTo(s1.name()))
.collect(Collectors.toSet()));
return services;
}
@VisibleForTesting
public static List<Service> parseService(
FileDescriptor fileDescriptor,
Map<String, Message> messageTypes,
Map<String, ResourceName> resourceNames,
Optional<com.google.api.Service> serviceYamlProtoOpt,
Set<ResourceName> outputArgResourceNames) {
return parseService(
fileDescriptor,
messageTypes,
resourceNames,
serviceYamlProtoOpt,
Optional.empty(),
outputArgResourceNames,
Transport.GRPC);
}
public static List<Service> parseService(
FileDescriptor fileDescriptor,
Map<String, Message> messageTypes,
Map<String, ResourceName> resourceNames,
Optional<com.google.api.Service> serviceYamlProtoOpt,
Optional<GapicServiceConfig> serviceConfigOpt,
Set<ResourceName> outputArgResourceNames,
Transport transport) {
return fileDescriptor.getServices().stream()
.map(
s -> {
// Workaround for a missing default_host and oauth_scopes annotation from a service
// definition. This can happen for protos that bypass the publishing process.
// TODO(miraleung): Remove this workaround later?
ServiceOptions serviceOptions = s.getOptions();
String defaultHost = null;
if (serviceOptions.hasExtension(ClientProto.defaultHost)) {
defaultHost =
sanitizeDefaultHost(serviceOptions.getExtension(ClientProto.defaultHost));
} else if (serviceYamlProtoOpt.isPresent()) {
// Fall back to the DNS name supplied in the service .yaml config.
defaultHost = serviceYamlProtoOpt.get().getName();
}
Preconditions.checkState(
!Strings.isNullOrEmpty(defaultHost),
String.format(
"Default host not found in service YAML config file or annotation for %s",
s.getName()));
List<String> oauthScopes = Collections.emptyList();
if (serviceOptions.hasExtension(ClientProto.oauthScopes)) {
oauthScopes =
Arrays.asList(
serviceOptions.getExtension(ClientProto.oauthScopes).split(COMMA));
}
boolean isDeprecated = false;
if (serviceOptions.hasDeprecated()) {
isDeprecated = serviceOptions.getDeprecated();
}
Service.Builder serviceBuilder = Service.builder();
if (fileDescriptor.toProto().hasSourceCodeInfo()) {
SourceCodeInfoLocation protoServiceLocation =
SOURCE_CODE_INFO_PARSER.getLocation(s);
if (!Objects.isNull(protoServiceLocation)
&& !Strings.isNullOrEmpty(protoServiceLocation.getLeadingComments())) {
serviceBuilder.setDescription(protoServiceLocation.getLeadingComments());
}
}
String serviceName = s.getName();
String overriddenServiceName = serviceName;
String pakkage = TypeParser.getPackage(fileDescriptor);
String originalJavaPackage = pakkage;
// Override Java package with that specified in gapic.yaml.
if (serviceConfigOpt.isPresent()
&& serviceConfigOpt.get().getLanguageSettingsOpt().isPresent()) {
GapicLanguageSettings languageSettings =
serviceConfigOpt.get().getLanguageSettingsOpt().get();
pakkage = languageSettings.pakkage();
overriddenServiceName =
languageSettings.getJavaServiceName(fileDescriptor.getPackage(), s.getName());
}
return serviceBuilder
.setName(serviceName)
.setOverriddenName(overriddenServiceName)
.setDefaultHost(defaultHost)
.setOauthScopes(oauthScopes)
.setPakkage(pakkage)
.setOriginalJavaPackage(originalJavaPackage)
.setProtoPakkage(fileDescriptor.getPackage())
.setIsDeprecated(isDeprecated)
.setMethods(
parseMethods(
s,
pakkage,
messageTypes,
resourceNames,
serviceConfigOpt,
outputArgResourceNames,
transport))
.build();
})
.collect(Collectors.toList());
}
public static Map<String, Message> parseMessages(
CodeGeneratorRequest request, Set<ResourceReference> outputResourceReferencesSeen) {
Map<String, FileDescriptor> fileDescriptors = getFilesToGenerate(request);
Map<String, Message> messages = new HashMap<>();
// Look for message types amongst all the protos, not just the ones to generate. This will
// ensure we track commonly-used protos like Empty.
for (FileDescriptor fileDescriptor : fileDescriptors.values()) {
messages.putAll(parseMessages(fileDescriptor, outputResourceReferencesSeen));
}
return messages;
}
// TODO(miraleung): Propagate the internal method to all tests, and remove this wrapper.
public static Map<String, Message> parseMessages(FileDescriptor fileDescriptor) {
return parseMessages(fileDescriptor, new HashSet<>());
}
public static Map<String, Message> parseMessages(
FileDescriptor fileDescriptor, Set<ResourceReference> outputResourceReferencesSeen) {
// TODO(miraleung): Preserve nested type and package data in the type key.
Map<String, Message> messages = new HashMap<>();
for (Descriptor messageDescriptor : fileDescriptor.getMessageTypes()) {
messages.putAll(parseMessages(messageDescriptor, outputResourceReferencesSeen));
}
// We treat enums as messages since we primarily care only about the type representation.
for (EnumDescriptor enumDescriptor : fileDescriptor.getEnumTypes()) {
String name = enumDescriptor.getName();
List<EnumValueDescriptor> valueDescriptors = enumDescriptor.getValues();
TypeNode enumType = TypeParser.parseType(enumDescriptor);
messages.put(
enumType.reference().fullName(),
Message.builder()
.setType(enumType)
.setName(name)
.setFullProtoName(enumDescriptor.getFullName())
.setEnumValues(
valueDescriptors.stream().map(v -> v.getName()).collect(Collectors.toList()),
valueDescriptors.stream().map(v -> v.getNumber()).collect(Collectors.toList()))
.build());
}
return messages;
}
private static Map<String, Message> parseMessages(
Descriptor messageDescriptor, Set<ResourceReference> outputResourceReferencesSeen) {
return parseMessages(messageDescriptor, outputResourceReferencesSeen, new ArrayList<String>());
}
private static Map<String, Message> parseMessages(
Descriptor messageDescriptor,
Set<ResourceReference> outputResourceReferencesSeen,
List<String> outerNestedTypes) {
Map<String, Message> messages = new HashMap<>();
String messageName = messageDescriptor.getName();
if (!messageDescriptor.getNestedTypes().isEmpty()) {
for (Descriptor nestedMessage : messageDescriptor.getNestedTypes()) {
if (isMapType(nestedMessage)) {
continue;
}
List<String> currentNestedTypes = new ArrayList<>(outerNestedTypes);
currentNestedTypes.add(messageName);
messages.putAll(
parseMessages(nestedMessage, outputResourceReferencesSeen, currentNestedTypes));
}
}
TypeNode messageType = TypeParser.parseType(messageDescriptor);
List<FieldDescriptor> fields = messageDescriptor.getFields();
HashMap<String, String> operationRequestFields = new HashMap<String, String>();
BiMap<String, String> operationResponseFields = HashBiMap.create();
OperationResponse.Builder operationResponse = null;
for (FieldDescriptor fd : fields) {
if (fd.getOptions().hasExtension(ExtendedOperationsProto.operationRequestField)) {
String orf = fd.getOptions().getExtension(ExtendedOperationsProto.operationRequestField);
operationRequestFields.put(orf, fd.getName());
}
if (fd.getOptions().hasExtension(ExtendedOperationsProto.operationResponseField)) {
String orf = fd.getOptions().getExtension(ExtendedOperationsProto.operationResponseField);
operationResponseFields.put(orf, fd.getName());
}
if (fd.getOptions().hasExtension(ExtendedOperationsProto.operationField)) {
OperationResponseMapping orm =
fd.getOptions().getExtension(ExtendedOperationsProto.operationField);
if (operationResponse == null) {
operationResponse = OperationResponse.builder();
}
if (orm.equals(OperationResponseMapping.NAME)) {
operationResponse.setNameFieldName(fd.getName());
} else if (orm.equals(OperationResponseMapping.STATUS)) {
operationResponse.setStatusFieldName(fd.getName());
operationResponse.setStatusFieldTypeName(fd.toProto().getTypeName());
} else if (orm.equals(OperationResponseMapping.ERROR_CODE)) {
operationResponse.setErrorCodeFieldName(fd.getName());
} else if (orm.equals(OperationResponseMapping.ERROR_MESSAGE)) {
operationResponse.setErrorMessageFieldName(fd.getName());
}
}
}
messages.put(
messageType.reference().fullName(),
Message.builder()
.setType(messageType)
.setName(messageName)
.setFullProtoName(messageDescriptor.getFullName())
.setFields(parseFields(messageDescriptor, outputResourceReferencesSeen))
.setOuterNestedTypes(outerNestedTypes)
.setOperationRequestFields(operationRequestFields)
.setOperationResponseFields(operationResponseFields)
.setOperationResponse(operationResponse != null ? operationResponse.build() : null)
.build());
return messages;
}
private static boolean isMapType(Descriptor messageDescriptor) {
List<String> fieldNames =
messageDescriptor.getFields().stream().map(f -> f.getName()).collect(Collectors.toList());
// Ends in "Entry" and has exactly two fields, named "key" and "value".
return messageDescriptor.getName().endsWith("Entry")
&& fieldNames.size() == 2
&& fieldNames.get(0).equals("key")
&& fieldNames.get(1).equals("value");
}
/**
* Populates ResourceName objects in Message POJOs.
*
* @param messageTypes A map of the message type name (as in the protobuf) to Message POJOs.
* @param resources A list of ResourceName POJOs.
* @return The updated messageTypes map.
*/
public static Map<String, Message> updateResourceNamesInMessages(
Map<String, Message> messageTypes, Collection<ResourceName> resources) {
Map<String, Message> updatedMessages = new HashMap<>(messageTypes);
for (ResourceName resource : resources) {
if (!resource.hasParentMessageName()) {
continue;
}
String messageKey = resource.parentMessageName();
Message messageToUpdate = updatedMessages.get(messageKey);
updatedMessages.put(messageKey, messageToUpdate.toBuilder().setResource(resource).build());
}
return updatedMessages;
}
public static Map<String, ResourceName> parseResourceNames(CodeGeneratorRequest request) {
String javaPackage = parseServiceJavaPackage(request);
Map<String, FileDescriptor> fileDescriptors = getFilesToGenerate(request);
Map<String, ResourceName> resourceNames = new HashMap<>();
for (String fileToGenerate : request.getFileToGenerateList()) {
FileDescriptor fileDescriptor =
Preconditions.checkNotNull(
fileDescriptors.get(fileToGenerate),
"Missing file descriptor for [%s]",
fileToGenerate);
resourceNames.putAll(parseResourceNames(fileDescriptor, javaPackage));
}
return resourceNames;
}
// Convenience wrapper for package-external unit tests. DO NOT ADD NEW FUNCTIONALITY HERE.
public static Map<String, ResourceName> parseResourceNames(FileDescriptor fileDescriptor) {
return parseResourceNames(fileDescriptor, TypeParser.getPackage(fileDescriptor));
}
public static Map<String, ResourceName> parseResourceNames(
FileDescriptor fileDescriptor, String javaPackage) {
return ResourceNameParser.parseResourceNames(fileDescriptor, javaPackage);
}
@VisibleForTesting
static List<Method> parseMethods(
ServiceDescriptor serviceDescriptor,
String servicePackage,
Map<String, Message> messageTypes,
Map<String, ResourceName> resourceNames,
Optional<GapicServiceConfig> serviceConfigOpt,
Set<ResourceName> outputArgResourceNames,
Transport transport) {
List<Method> methods = new ArrayList<>();
for (MethodDescriptor protoMethod : serviceDescriptor.getMethods()) {
// Parse the method.
TypeNode inputType = TypeParser.parseType(protoMethod.getInputType());
Method.Builder methodBuilder = Method.builder();
if (protoMethod.getFile().toProto().hasSourceCodeInfo()) {
SourceCodeInfoLocation protoMethodLocation =
SOURCE_CODE_INFO_PARSER.getLocation(protoMethod);
if (!Objects.isNull(protoMethodLocation)
&& !Strings.isNullOrEmpty(protoMethodLocation.getLeadingComments())) {
methodBuilder.setDescription(protoMethodLocation.getLeadingComments());
}
}
boolean isDeprecated = false;
if (protoMethod.getOptions().hasDeprecated()) {
isDeprecated = protoMethod.getOptions().getDeprecated();
}
Message inputMessage = messageTypes.get(inputType.reference().fullName());
Preconditions.checkNotNull(
inputMessage, String.format("No message found for %s", inputType.reference().fullName()));
HttpBindings httpBindings = HttpRuleParser.parse(protoMethod, inputMessage, messageTypes);
boolean isBatching =
!serviceConfigOpt.isPresent()
? false
: serviceConfigOpt
.get()
.hasBatchingSetting(
/* protoPakkage */ protoMethod.getFile().getPackage(),
serviceDescriptor.getName(),
protoMethod.getName());
boolean operationPollingMethod =
protoMethod.getOptions().hasExtension(ExtendedOperationsProto.operationPollingMethod)
? protoMethod
.getOptions()
.getExtension(ExtendedOperationsProto.operationPollingMethod)
: false;
methods.add(
methodBuilder
.setName(protoMethod.getName())
.setInputType(inputType)
.setOutputType(TypeParser.parseType(protoMethod.getOutputType()))
.setStream(
Method.toStream(protoMethod.isClientStreaming(), protoMethod.isServerStreaming()))
.setLro(parseLro(servicePackage, protoMethod, messageTypes))
.setMethodSignatures(
MethodSignatureParser.parseMethodSignatures(
protoMethod,
servicePackage,
inputType,
messageTypes,
resourceNames,
outputArgResourceNames))
.setHttpBindings(httpBindings)
.setIsBatching(isBatching)
.setPageSizeFieldName(parsePageSizeFieldName(protoMethod, messageTypes, transport))
.setIsDeprecated(isDeprecated)
.setOperationPollingMethod(operationPollingMethod)
.build());
// Any input type that has a resource reference will need a resource name helper class.
for (Field field : inputMessage.fields()) {
if (field.hasResourceReference()) {
String resourceTypeString = field.resourceReference().resourceTypeString();
ResourceName resourceName = null;
// Support older resource_references that specify only the final typename, e.g. FooBar
// versus example.com/FooBar.
if (resourceTypeString.indexOf(SLASH) < 0) {
Optional<String> actualResourceTypeNameOpt =
resourceNames.keySet().stream()
.filter(k -> k.substring(k.lastIndexOf(SLASH) + 1).equals(resourceTypeString))
.findFirst();
if (actualResourceTypeNameOpt.isPresent()) {
resourceName = resourceNames.get(actualResourceTypeNameOpt.get());
}
} else {
resourceName = resourceNames.get(resourceTypeString);
}
if (ResourceNameConstants.WILDCARD_PATTERN.equals(resourceTypeString)) {
resourceName = WILDCARD_RESOURCE_NAME;
} else {
Preconditions.checkNotNull(
resourceName,
String.format(
"Resource name %s not found; parsing field %s in message %s in method %s",
resourceTypeString, field.name(), inputMessage.name(), protoMethod.getName()));
}
outputArgResourceNames.add(resourceName);
}
}
}
return methods;
}
@VisibleForTesting
static LongrunningOperation parseLro(
String servicePackage, MethodDescriptor methodDescriptor, Map<String, Message> messageTypes) {
MethodOptions methodOptions = methodDescriptor.getOptions();
TypeNode operationServiceStubType = null;
String responseTypeName = null;
String metadataTypeName = null;
if (methodOptions.hasExtension(OperationsProto.operationInfo)) {
OperationInfo lroInfo =
methodDescriptor.getOptions().getExtension(OperationsProto.operationInfo);
responseTypeName = lroInfo.getResponseType();
metadataTypeName = lroInfo.getMetadataType();
}
if (methodOptions.hasExtension(ExtendedOperationsProto.operationService)) {
// TODO: support full package name for operations_service annotation value
String opServiceName = methodOptions.getExtension(ExtendedOperationsProto.operationService);
operationServiceStubType =
TypeNode.withReference(
VaporReference.builder()
.setName(opServiceName + "Stub")
.setPakkage(servicePackage + ".stub")
.build());
if (responseTypeName == null) {
responseTypeName = methodDescriptor.getOutputType().getFullName();
}
if (metadataTypeName == null) {
metadataTypeName = methodDescriptor.getOutputType().getFullName();
}
}
if (responseTypeName == null || metadataTypeName == null) {
return null;
}
Message responseMessage = null;
Message metadataMessage = null;
int lastDotIndex = responseTypeName.lastIndexOf('.');
boolean isResponseTypeNameShortOnly = lastDotIndex < 0;
String responseTypeShortName =
lastDotIndex >= 0 ? responseTypeName.substring(lastDotIndex + 1) : responseTypeName;
lastDotIndex = metadataTypeName.lastIndexOf('.');
boolean isMetadataTypeNameShortOnly = lastDotIndex < 0;
String metadataTypeShortName =
lastDotIndex >= 0 ? metadataTypeName.substring(lastDotIndex + 1) : metadataTypeName;
// The messageTypes map keys to the Java fully-qualified name.
for (Map.Entry<String, Message> messageEntry : messageTypes.entrySet()) {
String messageKey = messageEntry.getKey();
int messageLastDotIndex = messageEntry.getKey().lastIndexOf('.');
String messageShortName =
messageLastDotIndex >= 0 ? messageKey.substring(messageLastDotIndex + 1) : messageKey;
if (responseMessage == null) {
if (isResponseTypeNameShortOnly && responseTypeName.equals(messageShortName)) {
responseMessage = messageEntry.getValue();
} else if (!isResponseTypeNameShortOnly && responseTypeShortName.equals(messageShortName)) {
// Ensure that the full proto name matches.
Message candidateMessage = messageEntry.getValue();
if (candidateMessage.fullProtoName().equals(responseTypeName)) {
responseMessage = candidateMessage;
}
}
}
if (metadataMessage == null) {
if (isMetadataTypeNameShortOnly && metadataTypeName.equals(messageShortName)) {
metadataMessage = messageEntry.getValue();
} else if (!isMetadataTypeNameShortOnly && metadataTypeShortName.equals(messageShortName)) {
// Ensure that the full proto name matches.
Message candidateMessage = messageEntry.getValue();
if (candidateMessage.fullProtoName().equals(metadataTypeName)) {
metadataMessage = candidateMessage;
}
}
}
}
Preconditions.checkNotNull(
responseMessage,
String.format(
"LRO response message %s not found on method %s",
responseTypeName, methodDescriptor.getName()));
// TODO(miraleung): Check that the packages are equal if those strings are not empty.
Preconditions.checkNotNull(
metadataMessage,
String.format(
"LRO metadata message %s not found in method %s",
metadataTypeName, methodDescriptor.getName()));
return LongrunningOperation.builder()
.setResponseType(responseMessage.type())
.setMetadataType(metadataMessage.type())
.setOperationServiceStubType(operationServiceStubType)
.build();
}
@VisibleForTesting
static String parsePageSizeFieldName(
MethodDescriptor methodDescriptor, Map<String, Message> messageTypes, Transport transport) {
TypeNode inputMessageType = TypeParser.parseType(methodDescriptor.getInputType());
TypeNode outputMessageType = TypeParser.parseType(methodDescriptor.getOutputType());
Message inputMessage = messageTypes.get(inputMessageType.reference().fullName());
Message outputMessage = messageTypes.get(outputMessageType.reference().fullName());
// This should technically handle the absence of either of these fields (aip.dev/158), but we
// gate on their collective presence to ensure the generated surface is backawrds-compatible
// with monolith-gnerated libraries.
String pagedFieldName = null;
if (inputMessage.fieldMap().containsKey("page_token")
&& outputMessage.fieldMap().containsKey("next_page_token")) {
// List of potential field names representing page size.
// page_size gets priority over max_results if both are present
List<String> fieldNames = new ArrayList<>();
fieldNames.add("page_size");
if (transport == Transport.REST) {
fieldNames.add("max_results");
}
for (String fieldName : fieldNames) {
if (pagedFieldName == null && inputMessage.fieldMap().containsKey(fieldName)) {
pagedFieldName = fieldName;
}
}
}
return pagedFieldName;
}
@VisibleForTesting
static String sanitizeDefaultHost(String rawDefaultHost) {
if (rawDefaultHost.indexOf(COLON) >= 0) {
// A port is already present, just return the existing string.
return rawDefaultHost;
}
return String.format("%s:%s", rawDefaultHost, DEFAULT_PORT);
}
private static List<Field> parseFields(
Descriptor messageDescriptor, Set<ResourceReference> outputResourceReferencesSeen) {
List<FieldDescriptor> fields = new ArrayList<>(messageDescriptor.getFields());
// Sort by ascending field index order. This is important for paged responses, where the first
// repeated type is taken.
fields.sort((f1, f2) -> f1.getIndex() - f2.getIndex());
// Mirror protoc's name conflict resolution behavior for fields.
// If a singular field's name equals that of a repeated field with "Count" or "List" suffixed,
// append the protobuf's field number to both fields' names.
// See:
// https://github.com/protocolbuffers/protobuf/blob/9df42757f97da9f748a464deeda96427a8f7ade0/src/google/protobuf/compiler/java/java_context.cc#L60
Map<String, Integer> repeatedFieldNamesToNumber =
fields.stream()
.filter(f -> f.isRepeated())
.collect(Collectors.toMap(f -> f.getName(), f -> f.getNumber()));
Set<Integer> fieldNumbersWithConflicts = new HashSet<>();
for (FieldDescriptor field : fields) {
Set<String> conflictingRepeatedFieldNames =
repeatedFieldNamesToNumber.keySet().stream()
.filter(
n -> field.getName().equals(n + "_count") || field.getName().equals(n + "_list"))
.collect(Collectors.toSet());
if (!conflictingRepeatedFieldNames.isEmpty()) {
fieldNumbersWithConflicts.addAll(
conflictingRepeatedFieldNames.stream()
.map(n -> repeatedFieldNamesToNumber.get(n))
.collect(Collectors.toSet()));
fieldNumbersWithConflicts.add(field.getNumber());
}
}
return fields.stream()
.map(
f ->
parseField(
f,
messageDescriptor,
fieldNumbersWithConflicts.contains(f.getNumber()),
outputResourceReferencesSeen))
.collect(Collectors.toList());
}
private static Field parseField(
FieldDescriptor fieldDescriptor,
Descriptor messageDescriptor,
boolean hasFieldNameConflict,
Set<ResourceReference> outputResourceReferencesSeen) {
FieldOptions fieldOptions = fieldDescriptor.getOptions();
MessageOptions messageOptions = messageDescriptor.getOptions();
ResourceReference resourceReference = null;
if (fieldOptions.hasExtension(ResourceProto.resourceReference)) {
com.google.api.ResourceReference protoResourceReference =
fieldOptions.getExtension(ResourceProto.resourceReference);
// Assumes only one of type or child_type is set.
String typeString = protoResourceReference.getType();
String childTypeString = protoResourceReference.getChildType();
Preconditions.checkState(
!Strings.isNullOrEmpty(typeString) ^ !Strings.isNullOrEmpty(childTypeString),
String.format(
"Exactly one of type or child_type must be set for resource_reference in field %s",
fieldDescriptor.getName()));
boolean isChildType = !Strings.isNullOrEmpty(childTypeString);
resourceReference =
isChildType
? ResourceReference.withChildType(childTypeString)
: ResourceReference.withType(typeString);
outputResourceReferencesSeen.add(resourceReference);
} else if (messageOptions.hasExtension(ResourceProto.resource)) {
ResourceDescriptor protoResource = messageOptions.getExtension(ResourceProto.resource);
// aip.dev/4231.
String resourceFieldNameValue = ResourceNameConstants.NAME_FIELD_NAME;
if (!Strings.isNullOrEmpty(protoResource.getNameField())) {
resourceFieldNameValue = protoResource.getNameField();
}
if (fieldDescriptor.getName().equals(resourceFieldNameValue)) {
resourceReference = ResourceReference.withType(protoResource.getType());
}
}
Field.Builder fieldBuilder = Field.builder();
if (fieldDescriptor.getFile().toProto().hasSourceCodeInfo()) {
SourceCodeInfoLocation protoFieldLocation =
SOURCE_CODE_INFO_PARSER.getLocation(fieldDescriptor);
if (!Objects.isNull(protoFieldLocation)
&& !Strings.isNullOrEmpty(protoFieldLocation.getLeadingComments())) {
fieldBuilder.setDescription(protoFieldLocation.getLeadingComments());