Skip to content

Commit 57edba1

Browse files
committed
database: try cache first
Try the cache first before hitting the cloud, as the cloud request can block for many seconds if there is not network connectivity. Signed-off-by: Jordan Yates <jordan@embeint.com>
1 parent 0098f88 commit 57edba1

1 file changed

Lines changed: 11 additions & 12 deletions

File tree

src/infuse_iot/database.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -158,21 +158,20 @@ def observe_security_state(
158158
self.devices[infuse_id].network_id = network_id
159159
self.devices[infuse_id].device_public_key = device_pub_key
160160

161-
client = Client(base_url="https://api.infuse-iot.com").with_headers({"x-api-key": f"Bearer {get_api_key()}"})
161+
# Try the cache first
162+
cache_key = self._from_cache(infuse_id, device_pub_key)
163+
if cache_key is not None:
164+
self.devices[infuse_id].shared_key = cache_key
165+
return
162166

167+
client = Client(base_url="https://api.infuse-iot.com").with_headers({"x-api-key": f"Bearer {get_api_key()}"})
163168
with client as client:
164169
body = Key(base64.b64encode(device_pub_key).decode("utf-8"))
165-
try:
166-
response = get_shared_secret.sync(client=client, body=body)
167-
if response is not None:
168-
key = base64.b64decode(response.key)
169-
self.devices[infuse_id].shared_key = key
170-
self._update_cache(infuse_id, device_pub_key, key)
171-
except Exception as e:
172-
cache_key = self._from_cache(infuse_id, device_pub_key)
173-
if cache_key is None:
174-
raise e
175-
self.devices[infuse_id].shared_key = cache_key
170+
response = get_shared_secret.sync(client=client, body=body)
171+
if response is not None:
172+
key = base64.b64decode(response.key)
173+
self.devices[infuse_id].shared_key = key
174+
self._update_cache(infuse_id, device_pub_key, key)
176175

177176
def _network_key(self, network_id: int, interface: bytes, gps_time: int) -> bytes:
178177
if network_id not in self._network_keys:

0 commit comments

Comments
 (0)