자바
// 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.ads.googleads.examples.misc; import com.beust.jcommander.Parameter; import com.google.ads.googleads.examples.utils.ArgumentNames; import com.google.ads.googleads.examples.utils.CodeSampleParams; import com.google.ads.googleads.lib.GoogleAdsClient; import com.google.ads.googleads.v17.errors.GoogleAdsError; import com.google.ads.googleads.v17.errors.GoogleAdsException; import com.google.ads.googleads.v17.services.GoogleAdsRow; import com.google.ads.googleads.v17.services.GoogleAdsServiceClient; import com.google.ads.googleads.v17.services.GoogleAdsServiceClient.SearchPagedResponse; import com.google.ads.googleads.v17.services.SearchGoogleAdsRequest; import com.google.ads.googleads.v17.services.SearchGoogleAdsStreamRequest; import com.google.ads.googleads.v17.services.SearchGoogleAdsStreamResponse; import com.google.api.gax.grpc.GrpcCallContext; import com.google.api.gax.rpc.ServerStream; import com.google.api.gax.rpc.StatusCode.Code; import java.io.FileNotFoundException; import java.io.IOException; import org.threeten.bp.Duration; /** * Illustrates the use of custom client timeouts in the context of server streaming and unary calls. * * <p>For more information about the concepts, see this documentation: * https://grpc.io/docs/what-is-grpc/core-concepts/#rpc-life-cycle. */ public class SetCustomClientTimeouts { private static final int CLIENT_TIMEOUT_MILLIS = 5 * 60 * 1000; // 5 minutes in milliseconds. private static class SetCustomClientTimeoutsParams extends CodeSampleParams { @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true) private Long customerId; } public static void main(String[] args) throws IOException { SetCustomClientTimeoutsParams params = new SetCustomClientTimeoutsParams(); if (!params.parseArguments(args)) { // Either pass the required parameters for this example on the command line, or insert them // into the code here. See the parameter class definition above for descriptions. params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE"); } GoogleAdsClient googleAdsClient = null; try { googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build(); } catch (FileNotFoundException fnfe) { System.err.printf( "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe); System.exit(1); } catch (IOException ioe) { System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe); System.exit(1); } try { new SetCustomClientTimeouts().runExample(googleAdsClient, params.customerId); } catch (GoogleAdsException gae) { // GoogleAdsException is the base class for most exceptions thrown by an API request. // Instances of this exception have a message and a GoogleAdsFailure that contains a // collection of GoogleAdsErrors that indicate the underlying causes of the // GoogleAdsException. System.err.printf( "Request ID %s failed due to GoogleAdsException. Underlying errors:%n", gae.getRequestId()); int i = 0; for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) { System.err.printf(" Error %d: %s%n", i++, googleAdsError); } System.exit(1); } } /** Runs the example. */ private void runExample(GoogleAdsClient googleAdsClient, Long customerId) { makeServerStreamingCall(googleAdsClient, customerId); makeUnaryCall(googleAdsClient, customerId); } /** Makes a server streaming call using a custom client timeout. */ private void makeServerStreamingCall(GoogleAdsClient googleAdsClient, Long customerId) { StringBuilder output = new StringBuilder(); try (GoogleAdsServiceClient serviceClient = googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) { // Issues a search stream request by setting a custom client timeout ServerStream<SearchGoogleAdsStreamResponse> stream = serviceClient .searchStreamCallable() .call( SearchGoogleAdsStreamRequest.newBuilder() .setCustomerId(String.valueOf(customerId)) .setQuery("SELECT campaign.id FROM campaign") .build(), // Sets the timeout to use. // Note: This overrides the default value and can lead to // RequestError.RPC_DEADLINE_TOO_SHORT errors when too small. We recommend // to do it only if necessary. GrpcCallContext.createDefault() .withTimeout(Duration.ofMillis(CLIENT_TIMEOUT_MILLIS))); // Iterates over all rows in all messages and collects the campaign IDs. for (SearchGoogleAdsStreamResponse response : stream) { for (GoogleAdsRow googleAdsRow : response.getResultsList()) { output.append(" ").append(googleAdsRow.getCampaign().getId()); } } System.out.println("The server streaming call completed before the timeout"); } catch (GoogleAdsException ex) { if (ex.getStatusCode().getCode() == Code.DEADLINE_EXCEEDED) { System.out.println("The server streaming call did not complete before the timeout."); } else { // Bubbles up if the exception is not about timeout. throw ex; } } finally { System.out.printf("All campaign IDs retrieved: %s.%n", output.toString()); } } /** Makes an unary call using a custom client timeout. */ private void makeUnaryCall(GoogleAdsClient googleAdsClient, Long customerId) { StringBuilder output = new StringBuilder(); try (GoogleAdsServiceClient serviceClient = googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) { // Issues a search paged request by setting a custom client timeout SearchPagedResponse pagedResponse = serviceClient .searchPagedCallable() .call( SearchGoogleAdsRequest.newBuilder() .setCustomerId(String.valueOf(customerId)) .setQuery("SELECT campaign.id FROM campaign") .build(), // Sets the timeout to use. GrpcCallContext.createDefault() .withTimeout(Duration.ofMillis(CLIENT_TIMEOUT_MILLIS))); // Iterates over all rows in all messages and collects the campaign IDs. for (GoogleAdsRow row : pagedResponse.iterateAll()) { output.append(" ").append(row.getCampaign().getId()); } System.out.println("The search paged call completed before the timeout"); } catch (GoogleAdsException ex) { if (ex.getStatusCode().getCode() == Code.DEADLINE_EXCEEDED) { System.out.println("The search paged call did not complete before the timeout."); } else { // Bubbles up if the exception is not about timeout. throw ex; } } finally { System.out.printf("All campaign IDs retrieved: %s.%n", output.toString()); } } }
C#
// Copyright 2021 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. using CommandLine; using Google.Ads.Gax.Examples; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V17.Errors; using Google.Ads.GoogleAds.V17.Services; using Google.Api.Gax; using Google.Api.Gax.Grpc; using Grpc.Core; using System; using System.IO; namespace Google.Ads.GoogleAds.Examples.V17 { /// <summary> /// This code example illustrates the use of custom client timeouts in the context /// of server streaming and unary calls. This is useful in Cloud environments that /// enforce an upper bound on the time available to service an HTTP request. /// /// For more information about the concepts, see this documentation: /// https://grpc.io/docs/what-is-grpc/core-concepts/#rpc-life-cycle. /// </summary> public class SetCustomClientTimeouts : ExampleBase { /// <summary> /// Command line options for running the <see cref="SetCustomClientTimeouts"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The customer ID for which the call is made. /// </summary> [Option("customerId", Required = true, HelpText = "The customer ID for which the call is made.")] public long CustomerId { get; set; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { Options options = ExampleUtilities.ParseCommandLine<Options>(args); SetCustomClientTimeouts codeExample = new SetCustomClientTimeouts(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId); } /// <summary> /// The client timeout millis to use for making API calls. /// </summary> /// <remarks>5 minutes in milliseconds.</remarks> private const int CLIENT_TIMEOUT_MILLIS = 5 * 60 * 1000; /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This code example illustrates the use of custom " + "client timeouts in the context of server streaming and unary calls. This is useful " + "in Cloud environments that enforce an upper bound on the time available to service " + "an HTTP request.For more information about the concepts, see this documentation: " + "https://grpc.io/docs/what-is-grpc/core-concepts/#rpc-life-cycle.</p>"; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> public void Run(GoogleAdsClient client, long customerId) { try { MakeServerStreamingCall(client, customerId); MakeUnaryCall(client, customerId); } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } } /// <summary> /// Makes a server streaming call using a custom client timeout. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> private void MakeServerStreamingCall(GoogleAdsClient client, long customerId) { StringWriter writer = new StringWriter(); // Set a custom timeout. // Note: This overrides the default value and can lead to // RequestError.RPC_DEADLINE_TOO_SHORT errors when too small. We recommend // to do it only if necessary. CallSettings callSettings = CallSettings.FromExpiration( Expiration.FromTimeout(TimeSpan.FromMilliseconds(CLIENT_TIMEOUT_MILLIS))); try { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V17.GoogleAdsService); string query = "SELECT campaign.id FROM campaign"; SearchGoogleAdsStreamRequest request = new SearchGoogleAdsStreamRequest() { CustomerId = customerId.ToString(), Query = query }; // Issue a search request. googleAdsService.SearchStream(request, delegate (SearchGoogleAdsStreamResponse resp) { // Iterates over all rows in all messages and collects the campaign IDs. foreach (GoogleAdsRow googleAdsRow in resp.Results) { writer.WriteLine(googleAdsRow.Campaign.Id); } }, callSettings ); Console.WriteLine("The server streaming call completed before the timeout"); } catch (GoogleAdsException ex) { if (ex.StatusCode == StatusCode.DeadlineExceeded) { Console.WriteLine("The server streaming call did not complete before the " + "timeout."); } else { throw; } } finally { Console.WriteLine($"All campaign IDs retrieved: {writer}."); } } /// <summary> /// Makes an unary call using a custom client timeout. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> private void MakeUnaryCall(GoogleAdsClient client, long customerId) { StringWriter writer = new StringWriter(); // Set a custom timeout. // Note: This overrides the default value and can lead to // RequestError.RPC_DEADLINE_TOO_SHORT errors when too small. We recommend // to do it only if necessary. CallSettings callSettings = CallSettings.FromExpiration( Expiration.FromTimeout(TimeSpan.FromMilliseconds(CLIENT_TIMEOUT_MILLIS))); try { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V17.GoogleAdsService); string query = "SELECT campaign.id FROM campaign"; SearchGoogleAdsRequest request = new SearchGoogleAdsRequest() { CustomerId = customerId.ToString(), Query = query }; // Issue a search request. var googleAdsRows = googleAdsService.Search(request, callSettings); foreach (GoogleAdsRow googleAdsRow in googleAdsRows) { // Iterates over all rows in all messages and collects the campaign IDs. writer.WriteLine(googleAdsRow.Campaign.Id); } Console.WriteLine("The search paged call completed before the timeout."); } catch (GoogleAdsException ex) { if (ex.StatusCode == StatusCode.DeadlineExceeded) { Console.WriteLine("The search paged call did not complete before the timeout."); } else { throw; } } finally { Console.WriteLine($"All campaign IDs retrieved: {writer}."); } } } }
PHP
<?php /** * 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 * * 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. */ namespace Google\Ads\GoogleAds\Examples\Misc; require __DIR__ . '/../../vendor/autoload.php'; use GetOpt\GetOpt; use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames; use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser; use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V17\GoogleAdsException; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; use Google\Ads\GoogleAds\Lib\V17\GoogleAdsServerStreamDecorator; use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V17\Services\GoogleAdsRow; use Google\Ads\GoogleAds\V17\Services\SearchGoogleAdsRequest; use Google\Ads\GoogleAds\V17\Services\SearchGoogleAdsStreamRequest; use Google\ApiCore\ApiException; use Google\ApiCore\ApiStatus; /** * This example illustrates the use of custom client timeouts in the context of server streaming and * unary calls. * * For more information about the concepts, see this documentation: * https://grpc.io/docs/what-is-grpc/core-concepts/#rpc-life-cycle. */ class SetCustomClientTimeouts { private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE'; private const CLIENT_TIMEOUT_MILLIS = 5 * 60 * 1000; // 5 minutes in millis public static function main() { // Either pass the required parameters for this example on the command line, or insert them // into the constants above. $options = (new ArgumentParser())->parseCommandArguments([ ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT ]); // Generate a refreshable OAuth2 credential for authentication. $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build(); // Construct a Google Ads client configured from a properties file and the // OAuth2 credentials above. $googleAdsClient = (new GoogleAdsClientBuilder()) ->fromFile() ->withOAuth2Credential($oAuth2Credential) // We set this value to true to show how to use GAPIC v2 source code. You can remove the // below line if you wish to use the old-style source code. Note that in that case, you // probably need to modify some parts of the code below to make it work. // For more information, see // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic. ->usingGapicV2Source(true) ->build(); try { self::runExample( $googleAdsClient, $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID ); } catch (GoogleAdsException $googleAdsException) { printf( "Request with ID '%s' has failed.%sGoogle Ads failure details:%s", $googleAdsException->getRequestId(), PHP_EOL, PHP_EOL ); foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) { /** @var GoogleAdsError $error */ printf( "\t%s: %s%s", $error->getErrorCode()->getErrorCode(), $error->getMessage(), PHP_EOL ); } exit(1); } catch (ApiException $apiException) { printf( "ApiException was thrown with message '%s'.%s", $apiException->getMessage(), PHP_EOL ); exit(1); } } /** * Runs the example. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param int $customerId the customer ID */ public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId) { self::makeServerStreamingCall($googleAdsClient, $customerId); self::makeUnaryCall($googleAdsClient, $customerId); } /** * Makes a server streaming call using a custom client timeout. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param int $customerId the customer ID */ private static function makeServerStreamingCall( GoogleAdsClient $googleAdsClient, int $customerId ) { $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient(); // Creates a query that retrieves all campaign IDs. $query = 'SELECT campaign.id FROM campaign'; $output = ''; try { // Issues a search stream request by setting a custom client timeout. /** @var GoogleAdsServerStreamDecorator $stream */ $stream = $googleAdsServiceClient->searchStream( SearchGoogleAdsStreamRequest::build($customerId, $query), [ // Any server streaming call has a default timeout setting. For this // particular call, the default setting can be found in the following file: // https://github.com/googleads/google-ads-php/blob/master/src/Google/Ads/GoogleAds/V17/Services/resources/google_ads_service_client_config.json. // // When making a server streaming call, an optional argument is provided and can // be used to override the default timeout setting with a given value. 'timeoutMillis' => self::CLIENT_TIMEOUT_MILLIS ] ); // Iterates over all rows in all messages and collects the campaign IDs. foreach ($stream->iterateAllElements() as $googleAdsRow) { /** @var GoogleAdsRow $googleAdsRow */ $output .= ' ' . $googleAdsRow->getCampaign()->getId(); } print 'The server streaming call completed before the timeout.' . PHP_EOL; } catch (ApiException $exception) { if ($exception->getStatus() === ApiStatus::DEADLINE_EXCEEDED) { print 'The server streaming call did not complete before the timeout.' . PHP_EOL; } else { // Bubbles up if the exception is not about timeout. throw $exception; } } finally { print 'All campaign IDs retrieved:' . ($output ?: ' None') . PHP_EOL; } } /** * Makes an unary call using a custom client timeout. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param int $customerId the customer ID */ private static function makeUnaryCall(GoogleAdsClient $googleAdsClient, int $customerId) { $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient(); // Creates a query that retrieves all campaign IDs. $query = 'SELECT campaign.id FROM campaign'; $output = ''; try { // Issues a search request by setting a custom client timeout. $response = $googleAdsServiceClient->search( SearchGoogleAdsRequest::build($customerId, $query), [ // Any unary call is retryable and has default retry settings. // Complete information about these settings can be found here: // https://googleapis.github.io/gax-php/master/Google/ApiCore/RetrySettings.html. // For this particular call, the default retry settings can be found in the // following file: // https://github.com/googleads/google-ads-php/blob/master/src/Google/Ads/GoogleAds/V17/Services/resources/google_ads_service_client_config.json. // // When making an unary call, an optional argument is provided and can be // used to override the default retry settings with given values. 'retrySettings' => [ // Sets the maximum accumulative timeout of the call, it includes all tries. 'totalTimeoutMillis' => self::CLIENT_TIMEOUT_MILLIS, // Sets the timeout that is used for the first try to one tenth of the // maximum accumulative timeout of the call. // Note: This overrides the default value and can lead to // RequestError.RPC_DEADLINE_TOO_SHORT errors when too small. We recommend // to do it only if necessary. 'initialRpcTimeoutMillis' => self::CLIENT_TIMEOUT_MILLIS / 10, // Sets the maximum timeout that can be used for any given try to one fifth // of the maximum accumulative timeout of the call (two times greater than // the timeout that is used for the first try). 'maxRpcTimeoutMillis' => self::CLIENT_TIMEOUT_MILLIS / 5 ] ] ); // Iterates over all rows in all messages and collects the campaign IDs. foreach ($response->iterateAllElements() as $googleAdsRow) { /** @var GoogleAdsRow $googleAdsRow */ $output .= ' ' . $googleAdsRow->getCampaign()->getId(); } print 'The unary call completed before the timeout.' . PHP_EOL; } catch (ApiException $exception) { if ($exception->getStatus() === ApiStatus::DEADLINE_EXCEEDED) { print 'The unary call did not complete before the timeout.' . PHP_EOL; } else { // Bubbles up if the exception is not about timeout. throw $exception; } } finally { print 'All campaign IDs retrieved:' . ($output ?: ' None') . PHP_EOL; } } } SetCustomClientTimeouts::main();
Python
#!/usr/bin/env python # 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 # # 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 example illustrates the use of custom client timeouts. Even though this example demonstrates custom client timeouts in the context of streaming and unary calls separately, the behavior can be applied to any request method exposed by this library. For more information about the concepts, see this documentation: https://grpc.io/docs/what-is-grpc/core-concepts/#rpc-life-cycle """ import argparse import sys from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException from google.api_core.exceptions import DeadlineExceeded from google.api_core.retry import Retry _CLIENT_TIMEOUT_SECONDS = 5 * 60 # 5 minutes. _QUERY = "SELECT campaign.id FROM campaign" def main(client, customer_id): """Main method, to run this code example as a standalone application.""" make_server_streaming_call(client, customer_id) make_unary_call(client, customer_id) def make_server_streaming_call(client, customer_id): """Makes a server streaming call using a custom client timeout. Args: client: An initialized GoogleAds client. customer_id: The str Google Ads customer ID. """ ga_service = client.get_service("GoogleAdsService") campaign_ids = [] try: search_request = client.get_type("SearchGoogleAdsStreamRequest") search_request.customer_id = customer_id search_request.query = _QUERY stream = ga_service.search_stream( request=search_request, # When making any request, an optional "timeout" parameter can be # provided to specify a client-side response deadline in seconds. # If not set, then no timeout will be enforced by the client and # the channel will remain open until the response is completed or # severed, either manually or by the server. timeout=_CLIENT_TIMEOUT_SECONDS, ) for batch in stream: for row in batch.results: campaign_ids.append(row.campaign.id) print("The server streaming call completed before the timeout.") except DeadlineExceeded as ex: print("The server streaming call did not complete before the timeout.") sys.exit(1) except GoogleAdsException as ex: print( f"Request with ID '{ex.request_id}' failed with status " f"'{ex.error.code().name}' and includes the following errors:" ) for error in ex.failure.errors: print(f"\tError with message '{error.message}'.") if error.location: for field_path_element in error.location.field_path_elements: print(f"\t\tOn field: {field_path_element.field_name}") sys.exit(1) print(f"Total # of campaign IDs retrieved: {len(campaign_ids)}") def make_unary_call(client, customer_id): """Makes a unary call using a custom client timeout. Args: client: An initialized GoogleAds client. customer_id: The Google Ads customer ID. """ ga_service = client.get_service("GoogleAdsService") campaign_ids = [] try: search_request = client.get_type("SearchGoogleAdsRequest") search_request.customer_id = customer_id search_request.query = _QUERY results = ga_service.search( request=search_request, # When making any request, an optional "retry" parameter can be # provided to specify its retry behavior. Complete information about # these settings can be found here: # https://googleapis.dev/python/google-api-core/latest/retry.html retry=Retry( # Sets the maximum accumulative timeout of the call; it # includes all tries. deadline=_CLIENT_TIMEOUT_SECONDS, # Sets the timeout that is used for the first try to one tenth # of the maximum accumulative timeout of the call. # Note: This overrides the default value and can lead to # RequestError.RPC_DEADLINE_TOO_SHORT errors when too small. We # recommend changing the value only if necessary. initial=_CLIENT_TIMEOUT_SECONDS / 10, # Sets the maximum timeout that can be used for any given try # to one fifth of the maximum accumulative timeout of the call # (two times greater than the timeout that is needed for the # first try). maximum=_CLIENT_TIMEOUT_SECONDS / 5, ), ) for row in results: campaign_ids.append(row.campaign.id) print("The unary call completed before the timeout.") except DeadlineExceeded as ex: print("The unary call did not complete before the timeout.") sys.exit(1) except GoogleAdsException as ex: print( f"Request with ID '{ex.request_id}' failed with status " f"'{ex.error.code().name}' and includes the following errors:" ) for error in ex.failure.errors: print(f"\tError with message '{error.message}'.") if error.location: for field_path_element in error.location.field_path_elements: print(f"\t\tOn field: {field_path_element.field_name}") sys.exit(1) print(f"Total # of campaign IDs retrieved: {len(campaign_ids)}") if __name__ == "__main__": parser = argparse.ArgumentParser( description="Demonstrates custom client timeouts in the context of " "server streaming and unary calls." ) # The following argument(s) should be provided to run the example. parser.add_argument( "-c", "--customer_id", type=str, required=True, help="The Google Ads customer ID.", ) args = parser.parse_args() # GoogleAdsClient will read the google-ads.yaml configuration file in the # home directory if none is specified. googleads_client = GoogleAdsClient.load_from_storage(version="v17") main(googleads_client, args.customer_id)
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # 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 # # 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 example illustrates the use of custom client timeouts in the context of # server streaming and unary calls. # # For more information about the concepts, see this documentation: # https://grpc.io/docs/what-is-grpc/core-concepts/#rpc-life-cycle. require 'optparse' require 'google/ads/google_ads' require 'open-uri' def set_custom_client_timeouts(customer_id) # GoogleAdsClient will read a config file from # ENV['HOME']/google_ads_config.rb when called without parameters client = Google::Ads::GoogleAds::GoogleAdsClient.new make_server_streaming_call(client, customer_id) make_unary_call(client, customer_id) end # Makes a server streaming call using a custom client timeout. def make_server_streaming_call(client, customer_id) # Creates a query that retrieves all campaign IDs. query = <<~EOQUERY SELECT campaign.id FROM campaign EOQUERY output = "" begin ga_service = client.service.google_ads ga_service.configure do |config| # Any server streaming call has a default timeout setting. # For this particular call, the default setting can be found in the # following file: # https://github.com/googleads/google-ads-ruby/blob/master/lib/google/ads/google_ads/v10/services/google_ads_service/client.rb # # When making a server streaming call, config.rpcs.search_stream.timeout can # be used to override the default timeout setting with a given value. config.rpcs.search_stream.timeout = CLIENT_TIMEOUT_SECONDS end # Issues a search stream request using the customized client config. stream = ga_service.search_stream( customer_id: customer_id, query: query, ) # Iterates over all rows in all messages and collects the campaign IDs. stream.each do |response| response.results.each do |row| output += " #{row.campaign.id}" end end puts "The server streaming call completed before the timeout." rescue GRPC::DeadlineExceeded => e puts "The server streaming call did not complete before the timeout." ensure puts "All campaign IDs retrieved: #{output.empty? ? "None" : output}" end end def make_unary_call(client, customer_id) # Creates a query that retrieves all campaign IDs. query = <<~EOQUERY SELECT campaign.id FROM campaign EOQUERY output = "" begin ga_service = client.service.google_ads ga_service.configure do |config| # Any unary call is retryable and has default retry settings. # For this particular call, the default setting can be found in the # following file: # https://github.com/googleads/google-ads-ruby/blob/master/lib/google/ads/google_ads/v10/services/google_ads_service/client.rb # # When making an unary call, config.retry_policy can # be used to override the default retry settings with given values. config.rpcs.search.timeout = CLIENT_TIMEOUT_SECONDS config.rpcs.search.retry_policy = { # Note: This overrides the default value and can lead to # RequestError.RPC_DEADLINE_TOO_SHORT errors when too small. We # recommend to do it only if necessary. 'initial_delay' => CLIENT_TIMEOUT_SECONDS / 10.0, 'max_delay' => CLIENT_TIMEOUT_SECONDS / 5.0, } end # Issues a stream request using the customized client config. response = ga_service.search( customer_id: customer_id, query: query, ) # Iterates over all rows and collects the campaign IDs. response.each do |row| output += " #{row.campaign.id}" end puts "The unary call completed before the timeout." rescue GRPC::DeadlineExceeded => e puts "The unary call did not complete before the timeout." ensure puts "All campaign IDs retrieved: #{output.empty? ? "None" : output}" end end if __FILE__ == $0 CLIENT_TIMEOUT_SECONDS = 5 * 60 # 5 minutes in seconds options = {} # The following parameter(s) should be provided to run the example. You can # either specify these by changing the INSERT_XXX_ID_HERE values below, or on # the command line. # # Parameters passed on the command line will override any parameters set in # code. # # Running the example with -h will print the command line usage. options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE' OptionParser.new do |opts| opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__)) opts.separator '' opts.separator 'Options:' opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v| options[:customer_id] = v end opts.separator '' opts.separator 'Help:' opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end end.parse! begin set_custom_client_timeouts(options.fetch(:customer_id).tr('-', '')) rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e e.failure.errors.each do |error| STDERR.printf('Error with message: %s\n', error.message) if error.location error.location.field_path_elements.each do |field_path_element| STDERR.printf('\tOn field: %s\n', field_path_element.field_name) end end error.error_code.to_h.each do |k, v| next if v == :UNSPECIFIED STDERR.printf('\tType: %s\n\tCode: %s\n', k, v) end end raise end end
Perl
#!/usr/bin/perl -w # # 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. # # This example illustrates the use of custom client timeouts and retry delays # in the context of server streaming and unary calls. use strict; use warnings; use utf8; use FindBin qw($Bin); use lib "$Bin/../../lib"; use Google::Ads::GoogleAds::Client; use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; use Google::Ads::GoogleAds::Utils::SearchStreamHandler; use Google::Ads::GoogleAds::Utils::SearchGoogleAdsIterator; use Google::Ads::GoogleAds::V17::Services::GoogleAdsService::SearchGoogleAdsStreamRequest; use Google::Ads::GoogleAds::V17::Services::GoogleAdsService::SearchGoogleAdsRequest; use Getopt::Long qw(:config auto_help); use Pod::Usage; use Cwd qw(abs_path); # 5 minutes in seconds. use constant CLIENT_TIMEOUT_SECONDS => 5 * 60; # The query to retrieve all campaign IDs. use constant SEARCH_QUERY => "SELECT campaign.id FROM campaign"; # The message returned in the HTTP response for request timeout. use constant HTTP_TIMEOUT_MESSAGE => "read timeout"; # Maximum number of retries. use constant MAX_RETRIES => 3; # Number of seconds to wait on the first retry. use constant RETRY_INITIAL_DELAY_SECONDS => 15; # Retry delay multiplier for exponential backoffs. use constant RETRY_DELAY_MULTIPLIER => 2; # The following parameter(s) should be provided to run the example. You can # either specify these by changing the INSERT_XXX_ID_HERE values below, or on # the command line. # # Parameters passed on the command line will override any parameters set in # code. # # Running the example with -h will print the command line usage. my $customer_id = "INSERT_CUSTOMER_ID_HERE"; sub set_custom_client_timeouts { my ($api_client, $customer_id) = @_; make_server_streaming_call($api_client, $customer_id); make_unary_call($api_client, $customer_id); return 1; } # Makes a server streaming call using a custom client timeout. sub make_server_streaming_call { my ($api_client, $customer_id) = @_; # Any server streaming call has a default timeout setting, which can be found # in the module of Google::Ads::GoogleAds::Constants. # # A new value can be provided to override the default timeout setting in the # API client. $api_client->set_http_timeout(CLIENT_TIMEOUT_SECONDS); # Create a search Google Ads stream request that will retrieve all campaign IDs. my $search_stream_request = Google::Ads::GoogleAds::V17::Services::GoogleAdsService::SearchGoogleAdsStreamRequest ->new({ customerId => $customer_id, query => SEARCH_QUERY }); # Get the GoogleAdsService. my $google_ads_service = $api_client->GoogleAdsService(); my $output = ""; eval { my $search_stream_handler = Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({ service => $google_ads_service, request => $search_stream_request }); # Iterate over all rows in all messages and collect the campaign IDs. $search_stream_handler->process_contents( sub { my $google_ads_row = shift; $output .= ' ' . $google_ads_row->{campaign}{id}; }); print "The server streaming call completed before the timeout.\n"; }; if ($@) { my $response_message = $api_client->get_last_response()->message; # The LWP::UserAgent module returns a "read timeout" message in the HTTP # response for request timeout. if ($response_message =~ m/${\HTTP_TIMEOUT_MESSAGE}/) { print "The server streaming call did not complete before the timeout.\n"; } else { # Bubble up if the exception is not about timeout. die $$response_message; } } print "All campaign IDs retrieved : " . ($output ? $output : "None") . "\n"; } # Makes an unary call using a custom client timeout. sub make_unary_call { my ($api_client, $customer_id) = @_; # Any unary call has a default timeout setting, which can be found in the # module of Google::Ads::GoogleAds::Constants. # # A new value can be provided to override the default timeout setting in the # API client. $api_client->set_http_timeout(CLIENT_TIMEOUT_SECONDS); # Override default retry setting, which can be found in the module of # Google::Ads::GoogleAds::Constants. # # This sets the retry timing based on the initial delay, the delay multiplier, # and the maximum number of retries. my $http_retry_timing = "" . RETRY_INITIAL_DELAY_SECONDS; if (MAX_RETRIES > 1) { my $delay = RETRY_INITIAL_DELAY_SECONDS; for my $i (1 .. (MAX_RETRIES - 1)) { $delay = $delay * RETRY_DELAY_MULTIPLIER; $http_retry_timing = $http_retry_timing . "," . $delay; } } $api_client->set_http_retry_timing($http_retry_timing); # Create a search Google Ads request that will retrieve all campaign IDs. my $search_request = Google::Ads::GoogleAds::V17::Services::GoogleAdsService::SearchGoogleAdsRequest ->new({ customerId => $customer_id, query => SEARCH_QUERY, }); # Get the GoogleAdsService. my $google_ads_service = $api_client->GoogleAdsService(); my $output = ""; eval { my $iterator = Google::Ads::GoogleAds::Utils::SearchGoogleAdsIterator->new({ service => $google_ads_service, request => $search_request }); # Iterate over all rows in all messages and collect the campaign IDs. while ($iterator->has_next) { my $google_ads_row = $iterator->next; $output .= ' ' . $google_ads_row->{campaign}{id}; } print "The unary call completed before the timeout.\n"; }; if ($@) { my $response_message = $api_client->get_last_response()->message; # The LWP::UserAgent module returns a "read timeout" message in the HTTP # response for request timeout. if ($response_message =~ m/${\HTTP_TIMEOUT_MESSAGE}/) { print "The unary call did not complete before the timeout.\n"; } else { # Bubble up if the exception is not about timeout. die $$response_message; } } print "All campaign IDs retrieved : " . ($output ? $output : "None") . "\n"; } # Don't run the example if the file is being included. if (abs_path($0) ne abs_path(__FILE__)) { return 1; } # Get Google Ads Client, credentials will be read from ~/googleads.properties. my $api_client = Google::Ads::GoogleAds::Client->new(); # By default examples are set to die on any server returned fault. $api_client->set_die_on_faults(1); # Parameters passed on the command line will override any parameters set in code. GetOptions("customer_id=s" => \$customer_id); # Print the help message if the parameters are not initialized in the code nor # in the command line. pod2usage(2) if not check_params($customer_id); # Call the example. set_custom_client_timeouts($api_client, $customer_id =~ s/-//gr); =pod =head1 NAME set_custom_client_timeouts =head1 DESCRIPTION This example illustrates the use of custom client timeouts and retry delays in the context of server streaming and unary calls. =head1 SYNOPSIS set_custom_client_timeouts.pl [options] -help Show the help message. -customer_id The Google Ads customer ID. =cut