Skip to content

Commit 9bcc066

Browse files
authored
fix: surface the streaming allowance refusal, drop the refused config, add listen_config_refused (#63)
* fix: surface the streaming allowance refusal and drop the refused config * feat: add listen_config_refused for config updates the server refuses * fix: give each config-refused listener its own identity and an idempotent remover
1 parent 8f5b73a commit 9bcc066

2 files changed

Lines changed: 151 additions & 2 deletions

File tree

‎teslemetry_stream/vehicle.py‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,10 @@ def __init__(self, stream: TeslemetryStream, vin: str):
9898
# listeners (e.g. HA integration setup) discovering an unpopulated
9999
# vehicle joins one GET instead of each starting its own.
100100
self._populate_flight = None
101+
# Callbacks told when the server refuses a config update.
102+
self._config_refused_listeners: dict[
103+
object, Callable[[str, str | None], None]
104+
] = {}
101105
# Registered from birth, not lazily, so no connection can ever
102106
# predate this listener and miss a config event. Safe outside a
103107
# running loop: `internal=True` makes async_add_listener's
@@ -254,8 +258,16 @@ async def _flush(self) -> None:
254258

255259
if error := data.get("error"):
256260
LOGGER.error(
257-
"Error updating streaming config for %s: %s", self.vin, error
261+
"Error updating streaming config for %s: %s",
262+
self.vin,
263+
data.get("error_description") or error,
258264
)
265+
description = data.get("error_description")
266+
if error == "streaming_allowance_exceeded":
267+
# The account is over its streaming allowance, so replaying
268+
# this config on the next trigger would be refused again.
269+
self._config.clear()
270+
self._notify_config_refused(str(error), description)
259271
return
260272

261273
ignored = data.get("ignoredFields") or []
@@ -279,6 +291,36 @@ async def _flush(self) -> None:
279291
self.fields = {**self.fields, **applied}
280292
self._config.clear()
281293

294+
def _notify_config_refused(self, error: str, description: str | None) -> None:
295+
"""Tell each config-refused listener; one failing must not stop the rest."""
296+
for callback in list(self._config_refused_listeners.values()):
297+
try:
298+
callback(error, description)
299+
except Exception:
300+
LOGGER.exception(
301+
"Config refused listener failed for %s", self.vin
302+
)
303+
304+
def listen_config_refused(
305+
self, callback: Callable[[str, str | None], None]
306+
) -> Callable[[], None]:
307+
"""Call back with (error, description) when the server refuses a config.
308+
309+
Fires for every error-shaped response to a config update, for example
310+
``streaming_allowance_exceeded``; the caller filters on ``error``.
311+
Returns a function that removes the listener.
312+
"""
313+
# Each registration has its own identity, so registering the same
314+
# callback twice gives two independent removers, and a repeated
315+
# remove() only ever removes its own registration.
316+
key = object()
317+
self._config_refused_listeners[key] = callback
318+
319+
def remove() -> None:
320+
self._config_refused_listeners.pop(key, None)
321+
322+
return remove
323+
282324
async def _patch_with_bounded_retry(
283325
self, config: dict[str, Any]
284326
) -> dict[str, Any] | None:

‎tests/test_config_update.py‎

Lines changed: 108 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import logging
1111
from typing import Any
1212

13-
from teslemetry_stream.vehicle import TeslemetryStreamVehicle
13+
from teslemetry_stream.vehicle import LOGGER, TeslemetryStreamVehicle
1414

1515
VIN_A = "TESTVIN0000000001"
1616
VIN_B = "TESTVIN0000000002"
@@ -67,6 +67,17 @@ def emit(self, record: logging.LogRecord) -> None:
6767
self.messages.append(record.getMessage())
6868

6969

70+
class CaptureErrors(logging.Handler):
71+
"""Collect formatted ERROR records emitted by the library."""
72+
73+
def __init__(self) -> None:
74+
super().__init__(level=logging.ERROR)
75+
self.messages: list[str] = []
76+
77+
def emit(self, record: logging.LogRecord) -> None:
78+
self.messages.append(record.getMessage())
79+
80+
7081
def check(label: str, ok: bool, detail: str = "") -> bool:
7182
print(f"{label:<56} {'PASS' if ok else 'FAIL'}{' ' + detail if detail else ''}")
7283
return ok
@@ -191,6 +202,102 @@ async def main() -> None:
191202
)
192203
)
193204

205+
# A streaming allowance refusal logs the description and drops the batch.
206+
over = {
207+
"response": None,
208+
"error": "streaming_allowance_exceeded",
209+
"error_description": "This streaming configuration uses 120% of your allowance",
210+
}
211+
vehicle = make_vehicle(VIN_A, [over])
212+
captured = CaptureErrors()
213+
LOGGER.addHandler(captured)
214+
try:
215+
await vehicle.update_config({"fields": {"BatteryLevel": None}})
216+
finally:
217+
LOGGER.removeHandler(captured)
218+
results.append(
219+
check(
220+
"allowance refusal logs the error description",
221+
any("120% of your allowance" in m for m in captured.messages)
222+
and not any("streaming_allowance_exceeded" in m for m in captured.messages),
223+
f"logged {captured.messages}",
224+
)
225+
)
226+
results.append(
227+
check(
228+
"allowance refusal clears the pending config",
229+
vehicle._config == {} and vehicle.fields == {},
230+
f"pending {vehicle._config}, fields {sorted(vehicle.fields)}",
231+
)
232+
)
233+
234+
# The config-refused listener gets (error, description) once; a removed
235+
# listener is not called; a raising listener does not block the others.
236+
vehicle = make_vehicle(VIN_A, [over, FAILED, over])
237+
calls: list[tuple[str, str | None]] = []
238+
later: list[tuple[str, str | None]] = []
239+
240+
def boom(error: str, description: str | None) -> None:
241+
raise RuntimeError("listener bug")
242+
243+
vehicle.listen_config_refused(boom)
244+
vehicle.listen_config_refused(lambda e, d: calls.append((e, d)))
245+
remove_later = vehicle.listen_config_refused(lambda e, d: later.append((e, d)))
246+
await vehicle.update_config({"fields": {"BatteryLevel": None}})
247+
results.append(
248+
check(
249+
"config-refused listener called once with error and description",
250+
calls == [(over["error"], over["error_description"])]
251+
and later == calls,
252+
f"calls {calls}",
253+
)
254+
)
255+
remove_later()
256+
await vehicle.update_config({"fields": {"BatteryLevel": None}})
257+
results.append(
258+
check(
259+
"removed listener not called; other errors reach listeners",
260+
len(later) == 1 and calls[-1] == ("upstream internal error", None),
261+
f"calls {calls}, later {later}",
262+
)
263+
)
264+
vehicle = make_vehicle(VIN_A, [ACCEPTED])
265+
seen: list[Any] = []
266+
vehicle.listen_config_refused(lambda e, d: seen.append(e))
267+
await vehicle.update_config({"fields": {"BatteryLevel": None}})
268+
results.append(check("success does not call the listener", seen == []))
269+
270+
# The same callback registered twice has independent, idempotent removers.
271+
vehicle = make_vehicle(VIN_A, [over, over])
272+
twice: list[str] = []
273+
274+
def same(error: str, description: str | None) -> None:
275+
twice.append(error)
276+
277+
remove_first = vehicle.listen_config_refused(same)
278+
vehicle.listen_config_refused(same)
279+
remove_first()
280+
remove_first()
281+
await vehicle.update_config({"fields": {"BatteryLevel": None}})
282+
results.append(
283+
check(
284+
"repeated remove only removes its own registration",
285+
len(twice) == 1,
286+
f"calls {twice}",
287+
)
288+
)
289+
290+
# Any other error keeps the pending config for the next explicit trigger.
291+
vehicle = make_vehicle(VIN_A, [FAILED])
292+
await vehicle.update_config({"fields": {"BatteryLevel": None}})
293+
results.append(
294+
check(
295+
"other errors keep the pending config",
296+
vehicle._config == {"fields": {"BatteryLevel": None}},
297+
f"pending {vehicle._config}",
298+
)
299+
)
300+
194301
# Pending config must not be shared between vehicles.
195302
first = make_vehicle(VIN_A, [FAILED])
196303
second = make_vehicle(VIN_B, [ACCEPTED])

0 commit comments

Comments
 (0)