Skip to content

Commit c3f20cd

Browse files
gguussJon Wayne Parrott
authored and
Jon Wayne Parrott
committed
Use exponential backoff in HTTP methods. (GoogleCloudPlatform#1279)
* Use exponential backoff in HTTP methods. * Small change in import order, also increases backoff duration.
1 parent 20b94f1 commit c3f20cd

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

iot/api-client/http_example/cloudiot_http_example.py

+16-1
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,12 @@
2727
import json
2828
import time
2929

30+
from google.api_core import retry
3031
import jwt
3132
import requests
3233

33-
3434
_BASE_URL = 'https://cloudiot-device.googleapis.com/v1beta1'
35+
_BACKOFF_DURATION = 60
3536

3637

3738
def create_jwt(project_id, private_key_file, algorithm):
@@ -54,6 +55,9 @@ def create_jwt(project_id, private_key_file, algorithm):
5455
return jwt.encode(token, private_key, algorithm=algorithm).decode('ascii')
5556

5657

58+
@retry.Retry(
59+
predicate=retry.if_exception_type(AssertionError),
60+
deadline=_BACKOFF_DURATION)
5761
def publish_message(
5862
message, message_type, base_url, project_id, cloud_region, registry_id,
5963
device_id, jwt_token):
@@ -83,9 +87,16 @@ def publish_message(
8387
resp = requests.post(
8488
publish_url, data=json.dumps(body), headers=headers)
8589

90+
if (resp.status_code != 200):
91+
print('Response came back {}, retrying'.format(resp.status_code))
92+
raise AssertionError('Not OK response: {}'.format(resp.status_code))
93+
8694
return resp
8795

8896

97+
@retry.Retry(
98+
predicate=retry.if_exception_type(AssertionError),
99+
deadline=_BACKOFF_DURATION)
89100
def get_config(
90101
version, message_type, base_url, project_id, cloud_region, registry_id,
91102
device_id, jwt_token):
@@ -102,6 +113,10 @@ def get_config(
102113

103114
resp = requests.get(config_url, headers=headers)
104115

116+
if (resp.status_code != 200):
117+
print('Error getting config: {}, retrying'.format(resp.status_code))
118+
raise AssertionError('Not OK response: {}'.format(resp.status_code))
119+
105120
return resp
106121

107122

0 commit comments

Comments
 (0)