python-hotspring 4.0.0__py3-none-any.whl → 4.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hotspring/hotspring.py CHANGED
@@ -5,6 +5,8 @@ from __future__ import annotations
5
5
  import asyncio
6
6
  import contextlib
7
7
  import json
8
+ import logging
9
+ import time
8
10
  from dataclasses import dataclass
9
11
  from typing import Self
10
12
 
@@ -36,6 +38,15 @@ from .models import (
36
38
  SpaInfo,
37
39
  )
38
40
 
41
+ _LOGGER = logging.getLogger(__name__)
42
+
43
+
44
+ def _describe_exception(exception: BaseException) -> str:
45
+ """Return the exception type, plus its message when it has one."""
46
+ if detail := str(exception):
47
+ return f"{type(exception).__name__}: {detail}"
48
+ return type(exception).__name__
49
+
39
50
 
40
51
  @dataclass
41
52
  class HotSpring: # pylint: disable=too-many-public-methods
@@ -97,8 +108,11 @@ class HotSpring: # pylint: disable=too-many-public-methods
97
108
  """
98
109
  url = URL.build(scheme="http", host=self.host, port=80, path=uri)
99
110
 
111
+ # The HNA's single HTTP worker should not be left holding an idle pooled
112
+ # socket from a shared session between polls.
100
113
  headers = {
101
114
  "Accept": "application/json, text/plain, */*",
115
+ "Connection": "close",
102
116
  }
103
117
 
104
118
  if self.session is None:
@@ -107,62 +121,90 @@ class HotSpring: # pylint: disable=too-many-public-methods
107
121
 
108
122
  attempts = 0
109
123
  while True:
124
+ started = time.monotonic()
110
125
  try:
111
- async with asyncio.timeout(self.request_timeout):
112
- response = await self.session.request(
126
+ # Bound the body read too: a stalled body would otherwise hold
127
+ # the HNA's single HTTP worker until the caller's session
128
+ # timeout. Exiting mid-body closes the connection, never pools it.
129
+ async with (
130
+ asyncio.timeout(self.request_timeout),
131
+ self.session.request(
113
132
  method,
114
133
  url,
115
134
  json=data,
116
135
  headers=headers,
117
- )
136
+ ) as response,
137
+ ):
138
+ if response.status // 100 in [4, 5]:
139
+ contents = await response.read()
140
+
141
+ try:
142
+ raise HotSpringError(
143
+ response.status,
144
+ json.loads(contents.decode("utf8")),
145
+ )
146
+ except json.JSONDecodeError:
147
+ raise HotSpringError(
148
+ response.status,
149
+ {"message": contents.decode("utf8")},
150
+ ) from None
151
+
152
+ # The spa returns JSON with text/html Content-Type,
153
+ # so always try JSON parsing first.
154
+ body = await response.text()
118
155
 
119
- if response.status // 100 in [4, 5]:
120
- contents = await response.read()
121
- response.close()
122
-
123
- try:
124
- raise HotSpringError(
125
- response.status,
126
- json.loads(contents.decode("utf8")),
127
- )
128
- except json.JSONDecodeError:
129
- raise HotSpringError(
130
- response.status,
131
- {"message": contents.decode("utf8")},
132
- ) from None
133
-
134
- # The spa returns JSON with text/html Content-Type,
135
- # so always try JSON parsing first.
136
- body = await response.text()
137
156
  try:
138
157
  response_data = json.loads(body)
139
- except json.JSONDecodeError as exc:
158
+ except json.JSONDecodeError as exception:
140
159
  msg = f"Invalid JSON response from {uri}: {body[:200]}"
141
- raise HotSpringError(msg) from exc
160
+ raise HotSpringError(msg) from exception
142
161
 
143
162
  if not isinstance(response_data, dict):
144
163
  msg = f"Unexpected response type from {uri}"
145
164
  raise HotSpringError(msg)
146
165
 
147
- except asyncio.TimeoutError as exception: # noqa: PERF203
166
+ except asyncio.TimeoutError as exception:
148
167
  attempts += 1
168
+ _LOGGER.debug(
169
+ "%s %s attempt %d timed out after %.2fs",
170
+ method,
171
+ uri,
172
+ attempts,
173
+ time.monotonic() - started,
174
+ )
149
175
  if attempts > self.request_retries:
150
176
  msg = (
151
177
  f"Timeout occurred while connecting to Hot Spring HNA at "
152
- f"{self.host}"
178
+ f"{self.host}: no response within {self.request_timeout}s"
153
179
  )
154
180
  raise HotSpringConnectionTimeoutError(msg) from exception
155
181
  await asyncio.sleep(0.5 * (2 ** (attempts - 1)))
156
182
  except aiohttp.ClientError as exception:
157
183
  attempts += 1
184
+ cause = _describe_exception(exception)
185
+ _LOGGER.debug(
186
+ "%s %s attempt %d failed after %.2fs: %s",
187
+ method,
188
+ uri,
189
+ attempts,
190
+ time.monotonic() - started,
191
+ cause,
192
+ )
158
193
  if attempts > self.request_retries:
159
194
  msg = (
160
195
  f"Error occurred while communicating with Hot Spring HNA at "
161
- f"{self.host}"
196
+ f"{self.host}: {cause}"
162
197
  )
163
198
  raise HotSpringConnectionError(msg) from exception
164
199
  await asyncio.sleep(0.5 * (2 ** (attempts - 1)))
165
200
  else:
201
+ _LOGGER.debug(
202
+ "%s %s -> %d in %.2fs",
203
+ method,
204
+ uri,
205
+ response.status,
206
+ time.monotonic() - started,
207
+ )
166
208
  return response_data
167
209
 
168
210
  async def _safe_request(self, uri: str) -> dict[str, object] | None:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-hotspring
3
- Version: 4.0.0
3
+ Version: 4.0.1
4
4
  Summary: Asynchronous Python client for Hot Spring Connected Spa Kit 2.
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -1,10 +1,10 @@
1
1
  hotspring/__init__.py,sha256=wV3giZmeCl0qdz6zStvbQAYOBc6d5qdAFzEaHViYKkA,1560
2
2
  hotspring/const.py,sha256=f1iopXr4KVgOAr67dKzI0ra5k965zbEcOzicGu_VzuA,14466
3
3
  hotspring/exceptions.py,sha256=R8YwGfi6mXZ5DcHw4_fmtrRuvgkfOrLRCH-d3x6OUIw,1184
4
- hotspring/hotspring.py,sha256=uQHNk5hTxHGRIxmiWzn-eGv7DVd0wiGrLouXahIIqaE,28896
4
+ hotspring/hotspring.py,sha256=-sJT9dTmxIzYeJCvpHe8DDOXwPm4WHJr6FEbYL8WJ-Q,30568
5
5
  hotspring/models.py,sha256=dCSZEL-GmnKIBk-u6Z-S-tivrMCUS6cP-06wBGDSy8A,56648
6
6
  hotspring/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
- python_hotspring-4.0.0.dist-info/METADATA,sha256=rzVurtvJSzG6pkJwDbJ7oh3QaXQNbKRba-1P8DKeebQ,8037
8
- python_hotspring-4.0.0.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
9
- python_hotspring-4.0.0.dist-info/licenses/LICENSE,sha256=4n3vNP1aJ5r8xLfzCCjo5l0EK5-k2-7w9rgucn7WVFM,1080
10
- python_hotspring-4.0.0.dist-info/RECORD,,
7
+ python_hotspring-4.0.1.dist-info/METADATA,sha256=iky-CKQzfQylRKqZ6YnwZVCrGEN5DYbHLAtA2zXSur0,8037
8
+ python_hotspring-4.0.1.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
9
+ python_hotspring-4.0.1.dist-info/licenses/LICENSE,sha256=4n3vNP1aJ5r8xLfzCCjo5l0EK5-k2-7w9rgucn7WVFM,1080
10
+ python_hotspring-4.0.1.dist-info/RECORD,,