Search in sources :

Example 21 with GapicServiceConfig

use of com.google.api.generator.gapic.model.GapicServiceConfig in project gapic-generator-java by googleapis.

the class Parser method parse.

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);
    Optional<GapicServiceConfig> serviceConfigOpt = ServiceConfigParser.parse(serviceConfigPathOpt.orElse(null));
    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.flatMap(ServiceYamlParser::parse);
    // 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");
    // 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(typeNameFn).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.orElse(null)).setGapicMetadataEnabled(willGenerateMetadata).setServiceYamlProto(serviceYamlProtoOpt.orElse(null)).setTransport(transport).build();
}
Also used : HttpBindings(com.google.api.generator.gapic.model.HttpBindings) CodeGeneratorRequest(com.google.protobuf.compiler.PluginProtos.CodeGeneratorRequest) Arrays(java.util.Arrays) RoutingHeaderRule(com.google.api.generator.gapic.model.RoutingHeaderRule) OperationInfo(com.google.longrunning.OperationInfo) GapicServiceConfig(com.google.api.generator.gapic.model.GapicServiceConfig) DescriptorValidationException(com.google.protobuf.Descriptors.DescriptorValidationException) Field(com.google.api.generator.gapic.model.Field) Method(com.google.api.generator.gapic.model.Method) HttpRule(com.google.api.HttpRule) LongrunningOperation(com.google.api.generator.gapic.model.LongrunningOperation) Map(java.util.Map) ResourceProto(com.google.api.ResourceProto) FieldOptions(com.google.protobuf.DescriptorProtos.FieldOptions) FileDescriptor(com.google.protobuf.Descriptors.FileDescriptor) BiMap(com.google.common.collect.BiMap) ResourceDescriptor(com.google.api.ResourceDescriptor) ImmutableSet(com.google.common.collect.ImmutableSet) ResourceReference(com.google.api.generator.gapic.model.ResourceReference) Collection(java.util.Collection) Set(java.util.Set) FieldDescriptor(com.google.protobuf.Descriptors.FieldDescriptor) OperationsProto(com.google.longrunning.OperationsProto) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ResourceNameConstants(com.google.api.generator.gapic.utils.ResourceNameConstants) List(java.util.List) FileDescriptorProto(com.google.protobuf.DescriptorProtos.FileDescriptorProto) EnumDescriptor(com.google.protobuf.Descriptors.EnumDescriptor) DocumentationRule(com.google.api.DocumentationRule) Optional(java.util.Optional) Transport(com.google.api.generator.gapic.model.Transport) GapicContext(com.google.api.generator.gapic.model.GapicContext) GapicLanguageSettings(com.google.api.generator.gapic.model.GapicLanguageSettings) IntStream(java.util.stream.IntStream) VaporReference(com.google.api.generator.engine.ast.VaporReference) TypeNode(com.google.api.generator.engine.ast.TypeNode) GapicLroRetrySettings(com.google.api.generator.gapic.model.GapicLroRetrySettings) Descriptor(com.google.protobuf.Descriptors.Descriptor) HashMap(java.util.HashMap) Function(java.util.function.Function) OperationResponseMapping(com.google.cloud.OperationResponseMapping) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) MethodDescriptor(com.google.protobuf.Descriptors.MethodDescriptor) GapicBatchingSettings(com.google.api.generator.gapic.model.GapicBatchingSettings) Maps(com.google.common.collect.Maps) ResourceName(com.google.api.generator.gapic.model.ResourceName) Service(com.google.api.generator.gapic.model.Service) HashBiMap(com.google.common.collect.HashBiMap) ServiceOptions(com.google.protobuf.DescriptorProtos.ServiceOptions) ExtendedOperationsProto(com.google.cloud.ExtendedOperationsProto) EnumValueDescriptor(com.google.protobuf.Descriptors.EnumValueDescriptor) Preconditions(com.google.common.base.Preconditions) ServiceDescriptor(com.google.protobuf.Descriptors.ServiceDescriptor) OperationResponse(com.google.api.generator.gapic.model.OperationResponse) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Message(com.google.api.generator.gapic.model.Message) MethodOptions(com.google.protobuf.DescriptorProtos.MethodOptions) Collections(java.util.Collections) ClientProto(com.google.api.ClientProto) MessageOptions(com.google.protobuf.DescriptorProtos.MessageOptions) SourceCodeInfoLocation(com.google.api.generator.gapic.model.SourceCodeInfoLocation) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) HashSet(java.util.HashSet) Message(com.google.api.generator.gapic.model.Message) ResourceName(com.google.api.generator.gapic.model.ResourceName) ArrayList(java.util.ArrayList) GapicLanguageSettings(com.google.api.generator.gapic.model.GapicLanguageSettings) List(java.util.List) ArrayList(java.util.ArrayList) ResourceReference(com.google.api.generator.gapic.model.ResourceReference) HashSet(java.util.HashSet) Service(com.google.api.generator.gapic.model.Service) GapicServiceConfig(com.google.api.generator.gapic.model.GapicServiceConfig) Transport(com.google.api.generator.gapic.model.Transport)

Example 22 with GapicServiceConfig

use of com.google.api.generator.gapic.model.GapicServiceConfig in project gapic-generator-java by googleapis.

the class Parser method parseServices.

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().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.toList()));
    return services;
}
Also used : HttpBindings(com.google.api.generator.gapic.model.HttpBindings) CodeGeneratorRequest(com.google.protobuf.compiler.PluginProtos.CodeGeneratorRequest) Arrays(java.util.Arrays) RoutingHeaderRule(com.google.api.generator.gapic.model.RoutingHeaderRule) OperationInfo(com.google.longrunning.OperationInfo) GapicServiceConfig(com.google.api.generator.gapic.model.GapicServiceConfig) DescriptorValidationException(com.google.protobuf.Descriptors.DescriptorValidationException) Field(com.google.api.generator.gapic.model.Field) Method(com.google.api.generator.gapic.model.Method) HttpRule(com.google.api.HttpRule) LongrunningOperation(com.google.api.generator.gapic.model.LongrunningOperation) Map(java.util.Map) ResourceProto(com.google.api.ResourceProto) FieldOptions(com.google.protobuf.DescriptorProtos.FieldOptions) FileDescriptor(com.google.protobuf.Descriptors.FileDescriptor) BiMap(com.google.common.collect.BiMap) ResourceDescriptor(com.google.api.ResourceDescriptor) ImmutableSet(com.google.common.collect.ImmutableSet) ResourceReference(com.google.api.generator.gapic.model.ResourceReference) Collection(java.util.Collection) Set(java.util.Set) FieldDescriptor(com.google.protobuf.Descriptors.FieldDescriptor) OperationsProto(com.google.longrunning.OperationsProto) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ResourceNameConstants(com.google.api.generator.gapic.utils.ResourceNameConstants) List(java.util.List) FileDescriptorProto(com.google.protobuf.DescriptorProtos.FileDescriptorProto) EnumDescriptor(com.google.protobuf.Descriptors.EnumDescriptor) DocumentationRule(com.google.api.DocumentationRule) Optional(java.util.Optional) Transport(com.google.api.generator.gapic.model.Transport) GapicContext(com.google.api.generator.gapic.model.GapicContext) GapicLanguageSettings(com.google.api.generator.gapic.model.GapicLanguageSettings) IntStream(java.util.stream.IntStream) VaporReference(com.google.api.generator.engine.ast.VaporReference) TypeNode(com.google.api.generator.engine.ast.TypeNode) GapicLroRetrySettings(com.google.api.generator.gapic.model.GapicLroRetrySettings) Descriptor(com.google.protobuf.Descriptors.Descriptor) HashMap(java.util.HashMap) Function(java.util.function.Function) OperationResponseMapping(com.google.cloud.OperationResponseMapping) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) MethodDescriptor(com.google.protobuf.Descriptors.MethodDescriptor) GapicBatchingSettings(com.google.api.generator.gapic.model.GapicBatchingSettings) Maps(com.google.common.collect.Maps) ResourceName(com.google.api.generator.gapic.model.ResourceName) Service(com.google.api.generator.gapic.model.Service) HashBiMap(com.google.common.collect.HashBiMap) ServiceOptions(com.google.protobuf.DescriptorProtos.ServiceOptions) ExtendedOperationsProto(com.google.cloud.ExtendedOperationsProto) EnumValueDescriptor(com.google.protobuf.Descriptors.EnumValueDescriptor) Preconditions(com.google.common.base.Preconditions) ServiceDescriptor(com.google.protobuf.Descriptors.ServiceDescriptor) OperationResponse(com.google.api.generator.gapic.model.OperationResponse) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Message(com.google.api.generator.gapic.model.Message) MethodOptions(com.google.protobuf.DescriptorProtos.MethodOptions) Collections(java.util.Collections) ClientProto(com.google.api.ClientProto) MessageOptions(com.google.protobuf.DescriptorProtos.MessageOptions) SourceCodeInfoLocation(com.google.api.generator.gapic.model.SourceCodeInfoLocation) HttpBindings(com.google.api.generator.gapic.model.HttpBindings) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Service(com.google.api.generator.gapic.model.Service) Method(com.google.api.generator.gapic.model.Method) FileDescriptor(com.google.protobuf.Descriptors.FileDescriptor) HttpRule(com.google.api.HttpRule) DocumentationRule(com.google.api.DocumentationRule) HashSet(java.util.HashSet)

Example 23 with GapicServiceConfig

use of com.google.api.generator.gapic.model.GapicServiceConfig in project gapic-generator-java by googleapis.

the class RetrySettingsComposerTest method lroBuilderExpr.

@Test
public void lroBuilderExpr() {
    FileDescriptor echoFileDescriptor = EchoOuterClass.getDescriptor();
    Map<String, Message> messageTypes = Parser.parseMessages(echoFileDescriptor);
    Map<String, ResourceName> resourceNames = Parser.parseResourceNames(echoFileDescriptor);
    Set<ResourceName> outputResourceNames = new HashSet<>();
    List<Service> services = Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames);
    assertEquals(1, services.size());
    Service service = services.get(0);
    String jsonFilename = "showcase_grpc_service_config.json";
    Path jsonPath = Paths.get(TestProtoLoader.instance().getTestFilesDirectory(), jsonFilename);
    Optional<GapicServiceConfig> serviceConfigOpt = ServiceConfigParser.parse(jsonPath.toString());
    assertTrue(serviceConfigOpt.isPresent());
    GapicServiceConfig serviceConfig = serviceConfigOpt.get();
    // LRO method.
    Method waitMethod = findMethod(service, "Wait");
    assertThat(waitMethod).isNotNull();
    VariableExpr builderVarExpr = createBuilderVarExpr(service);
    Expr builderExpr = RetrySettingsComposer.createLroSettingsBuilderExpr(service, serviceConfig, waitMethod, builderVarExpr, RETRY_CODES_DEFINITIONS_VAR_EXPR, RETRY_PARAM_DEFINITIONS_VAR_EXPR, GrpcContext.instance().operationResponseTransformerType(), GrpcContext.instance().operationMetadataTransformerType());
    builderExpr.accept(writerVisitor);
    String expected = LineFormatter.lines("builder.waitOperationSettings()" + ".setInitialCallSettings(UnaryCallSettings.<WaitRequest," + " OperationSnapshot>newUnaryCallSettingsBuilder()" + ".setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"no_retry_0_codes\"))" + ".setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"no_retry_0_params\")).build())" + ".setResponseTransformer(ProtoOperationTransformers.ResponseTransformer.create(" + "WaitResponse.class))" + ".setMetadataTransformer(ProtoOperationTransformers.MetadataTransformer.create(" + "WaitMetadata.class)).setPollingAlgorithm(OperationTimedPollAlgorithm.create(" + "RetrySettings.newBuilder().setInitialRetryDelay(Duration.ofMillis(5000L))" + ".setRetryDelayMultiplier(1.5).setMaxRetryDelay(Duration.ofMillis(45000L))" + ".setInitialRpcTimeout(Duration.ZERO).setRpcTimeoutMultiplier(1.0)" + ".setMaxRpcTimeout(Duration.ZERO).setTotalTimeout(Duration.ofMillis(300000L))" + ".build()))");
    assertEquals(expected, writerVisitor.write());
}
Also used : Path(java.nio.file.Path) Message(com.google.api.generator.gapic.model.Message) ResourceName(com.google.api.generator.gapic.model.ResourceName) Service(com.google.api.generator.gapic.model.Service) Method(com.google.api.generator.gapic.model.Method) GapicServiceConfig(com.google.api.generator.gapic.model.GapicServiceConfig) FileDescriptor(com.google.protobuf.Descriptors.FileDescriptor) Expr(com.google.api.generator.engine.ast.Expr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 24 with GapicServiceConfig

use of com.google.api.generator.gapic.model.GapicServiceConfig in project gapic-generator-java by googleapis.

the class RetrySettingsComposerTest method paramDefinitionsBlock_basic.

@Test
public void paramDefinitionsBlock_basic() {
    GapicContext context = TestProtoLoader.instance().parseShowcaseEcho();
    Service service = context.services().get(0);
    String jsonFilename = "showcase_grpc_service_config.json";
    Path jsonPath = Paths.get(TestProtoLoader.instance().getTestFilesDirectory(), jsonFilename);
    Optional<GapicServiceConfig> serviceConfigOpt = ServiceConfigParser.parse(jsonPath.toString());
    assertTrue(serviceConfigOpt.isPresent());
    GapicServiceConfig serviceConfig = serviceConfigOpt.get();
    BlockStatement paramDefinitionsBlock = RetrySettingsComposer.createRetryParamDefinitionsBlock(service, serviceConfig, RETRY_PARAM_DEFINITIONS_VAR_EXPR);
    paramDefinitionsBlock.accept(writerVisitor);
    String expected = LineFormatter.lines("static {\n", "ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();\n", "RetrySettings settings = null;\n", "settings =" + " RetrySettings.newBuilder().setInitialRetryDelay(" + "Duration.ofMillis(100L)).setRetryDelayMultiplier(2.0)" + ".setMaxRetryDelay(Duration.ofMillis(3000L))" + ".setInitialRpcTimeout(Duration.ofMillis(10000L))" + ".setRpcTimeoutMultiplier(1.0)" + ".setMaxRpcTimeout(Duration.ofMillis(10000L))" + ".setTotalTimeout(Duration.ofMillis(10000L)).build();\n", "definitions.put(\"retry_policy_1_params\", settings);\n", "settings =" + " RetrySettings.newBuilder()" + ".setInitialRpcTimeout(Duration.ofMillis(5000L))" + ".setRpcTimeoutMultiplier(1.0)" + ".setMaxRpcTimeout(Duration.ofMillis(5000L))" + ".setTotalTimeout(Duration.ofMillis(5000L)).build();\n", "definitions.put(\"no_retry_0_params\", settings);\n", "RETRY_PARAM_DEFINITIONS = definitions.build();\n", "}\n");
    assertEquals(expected, writerVisitor.write());
}
Also used : Path(java.nio.file.Path) Service(com.google.api.generator.gapic.model.Service) BlockStatement(com.google.api.generator.engine.ast.BlockStatement) GapicContext(com.google.api.generator.gapic.model.GapicContext) GapicServiceConfig(com.google.api.generator.gapic.model.GapicServiceConfig) Test(org.junit.Test)

Example 25 with GapicServiceConfig

use of com.google.api.generator.gapic.model.GapicServiceConfig in project gapic-generator-java by googleapis.

the class RetrySettingsComposerTest method simpleBuilderExpr_basic.

@Test
public void simpleBuilderExpr_basic() {
    FileDescriptor echoFileDescriptor = EchoOuterClass.getDescriptor();
    Map<String, Message> messageTypes = Parser.parseMessages(echoFileDescriptor);
    Map<String, ResourceName> resourceNames = Parser.parseResourceNames(echoFileDescriptor);
    Set<ResourceName> outputResourceNames = new HashSet<>();
    List<Service> services = Parser.parseService(echoFileDescriptor, messageTypes, resourceNames, Optional.empty(), outputResourceNames);
    assertEquals(1, services.size());
    Service service = services.get(0);
    String jsonFilename = "showcase_grpc_service_config.json";
    Path jsonPath = Paths.get(TestProtoLoader.instance().getTestFilesDirectory(), jsonFilename);
    Optional<GapicServiceConfig> serviceConfigOpt = ServiceConfigParser.parse(jsonPath.toString());
    assertTrue(serviceConfigOpt.isPresent());
    GapicServiceConfig serviceConfig = serviceConfigOpt.get();
    // Regular method.
    Method echoMethod = findMethod(service, "Echo");
    assertThat(echoMethod).isNotNull();
    VariableExpr builderVarExpr = createBuilderVarExpr(service);
    Expr builderExpr = RetrySettingsComposer.createSimpleBuilderSettingsExpr(service, serviceConfig, echoMethod, builderVarExpr, RETRY_CODES_DEFINITIONS_VAR_EXPR, RETRY_PARAM_DEFINITIONS_VAR_EXPR);
    builderExpr.accept(writerVisitor);
    String expected = LineFormatter.lines("builder.echoSettings()" + ".setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_1_codes\"))" + ".setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_1_params\"))");
    assertEquals(expected, writerVisitor.write());
    // Server-streaming method.
    Method expandMethod = findMethod(service, "Expand");
    assertThat(expandMethod).isNotNull();
    builderExpr = RetrySettingsComposer.createSimpleBuilderSettingsExpr(service, serviceConfig, expandMethod, builderVarExpr, RETRY_CODES_DEFINITIONS_VAR_EXPR, RETRY_PARAM_DEFINITIONS_VAR_EXPR);
    writerVisitor.clear();
    builderExpr.accept(writerVisitor);
    expected = LineFormatter.lines("builder.expandSettings()" + ".setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"retry_policy_1_codes\"))" + ".setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"retry_policy_1_params\"))");
    assertEquals(expected, writerVisitor.write());
    // LRO method.
    Method waitMethod = findMethod(service, "Wait");
    assertThat(waitMethod).isNotNull();
    builderExpr = RetrySettingsComposer.createSimpleBuilderSettingsExpr(service, serviceConfig, waitMethod, builderVarExpr, RETRY_CODES_DEFINITIONS_VAR_EXPR, RETRY_PARAM_DEFINITIONS_VAR_EXPR);
    writerVisitor.clear();
    builderExpr.accept(writerVisitor);
    expected = LineFormatter.lines("builder.waitSettings()" + ".setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get(\"no_retry_0_codes\"))" + ".setRetrySettings(RETRY_PARAM_DEFINITIONS.get(\"no_retry_0_params\"))");
    assertEquals(expected, writerVisitor.write());
}
Also used : Path(java.nio.file.Path) Message(com.google.api.generator.gapic.model.Message) ResourceName(com.google.api.generator.gapic.model.ResourceName) Service(com.google.api.generator.gapic.model.Service) Method(com.google.api.generator.gapic.model.Method) GapicServiceConfig(com.google.api.generator.gapic.model.GapicServiceConfig) FileDescriptor(com.google.protobuf.Descriptors.FileDescriptor) Expr(com.google.api.generator.engine.ast.Expr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) VariableExpr(com.google.api.generator.engine.ast.VariableExpr) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

GapicServiceConfig (com.google.api.generator.gapic.model.GapicServiceConfig)28 Service (com.google.api.generator.gapic.model.Service)26 Message (com.google.api.generator.gapic.model.Message)19 HashSet (java.util.HashSet)19 Path (java.nio.file.Path)17 ResourceName (com.google.api.generator.gapic.model.ResourceName)16 FileDescriptor (com.google.protobuf.Descriptors.FileDescriptor)16 List (java.util.List)15 GapicBatchingSettings (com.google.api.generator.gapic.model.GapicBatchingSettings)13 Method (com.google.api.generator.gapic.model.Method)13 Expr (com.google.api.generator.engine.ast.Expr)12 ServiceDescriptor (com.google.protobuf.Descriptors.ServiceDescriptor)12 VariableExpr (com.google.api.generator.engine.ast.VariableExpr)11 ArrayList (java.util.ArrayList)10 Test (org.junit.Test)10 TypeNode (com.google.api.generator.engine.ast.TypeNode)9 GapicContext (com.google.api.generator.gapic.model.GapicContext)9 Preconditions (com.google.common.base.Preconditions)9 ImmutableSet (com.google.common.collect.ImmutableSet)9 Arrays (java.util.Arrays)9