From 52ee408860a7ea254f6998948f1d3d7123e0b56b Mon Sep 17 00:00:00 2001 From: "Brett Adams (Firstmate)" Date: Sat, 7 Nov 2026 21:39:51 +1000 Subject: [PATCH 1/2] feat: resume the SSE cache snapshot from the last cursor on reconnect --- README.md | 2 +- teslemetry_stream/stream.py | 13 +++ tests/test_sse_cursor.py | 166 ++++++++++++++++++++++++++++++++++++ 3 files changed, 180 insertions(+), 1 deletion(-) create mode 100644 tests/test_sse_cursor.py diff --git a/README.md b/README.md index 10351be..882d5f5 100644 --- a/README.md +++ b/README.md @@ -343,7 +343,7 @@ Listen for vehicle error events. The callback receives a list of dictionaries co The alerts in the vehicle's latest alerts batch, newest first. An alert without `endedAt` is active. The vehicle sends its window of recent alerts (up to 100, reaching back days) and drops old ones off it, active ones included, so this is what the vehicle currently reports, not a lifetime history. ### `listen_AlertChanges(callback: Callable[[str, dict], None]) -> Callable[[],None]` -Listen for alerts starting and ending. The callback receives `"started"` or `"ended"` and the alert. Each alerts event carries the vehicle's recent alerts, ended ones included, and is resent unchanged, including as the snapshot on every reconnect, so only an alert not seen before that comes ahead of every alert already seen (batches are newest first; position is used rather than `startedAt`, which the vehicle's clock can skew) is a start, and only a known active alert that now has `endedAt` is an end. The first batch only seeds `alerts`. An alert that started and ended between two batches calls back with both. The lifecycle rules are based on [purcell-lab/teslemetry-alerts](https://github.com/purcell-lab/teslemetry-alerts). +Listen for alerts starting and ending. The callback receives `"started"` or `"ended"` and the alert. Each alerts event carries the vehicle's recent alerts, ended ones included, and is resent unchanged, including as the connect snapshot, so only an alert not seen before that comes ahead of every alert already seen (batches are newest first; position is used rather than `startedAt`, which the vehicle's clock can skew) is a start, and only a known active alert that now has `endedAt` is an end. The first batch only seeds `alerts`. An alert that started and ended between two batches calls back with both. The lifecycle rules are based on [purcell-lab/teslemetry-alerts](https://github.com/purcell-lab/teslemetry-alerts). ### `listen_ChargerPower(callback: Callable[[float | None], None]) -> Callable[[],None]` Listen for charger power whether the vehicle is AC or DC charging. Combines `ACChargingPower` and `DCChargingPower` (DC preferred), gated by `DetailedChargeState`: the value drops to `0` when charging ends, since neither source is reliably reset then, and a lone zero while charging is held until both sources have reported. Enables all three fields; the returned function removes all three listeners. diff --git a/teslemetry_stream/stream.py b/teslemetry_stream/stream.py index 8a1c4b8..3173005 100644 --- a/teslemetry_stream/stream.py +++ b/teslemetry_stream/stream.py @@ -87,6 +87,10 @@ def __init__( self.parse_timestamp = parse_timestamp self.manual = manual self.retries: int = 0 + # Last cache position received, and the (url, topics) it belongs to - + # only a reconnect asking for the same vehicles and topics may resume from it. + self._cursor: Any = None + self._cursor_scope: tuple[str, str | None] | None = None self.vehicles: dict[str, TeslemetryStreamVehicle] = {} self.energysites: dict[int, TeslemetryStreamEnergySite] = {} self.fields: dict[str, Any] = {} @@ -267,6 +271,12 @@ async def connect(self) -> None: params = {"cache": "true"} if self.topics: params["topics"] = ",".join(self.topics) + scope = (url, params.get("topics")) + if scope != self._cursor_scope: + self._cursor = None + self._cursor_scope = scope + elif self._cursor is not None: + params["cursor"] = str(self._cursor) response = await self._session.get( url, headers=headers, @@ -362,6 +372,9 @@ async def __anext__(self) -> dict[str, Any]: field, _, value = line_in_bytes.decode("utf8").partition(": ") if field == "data": data = json.loads(value) + # An event without a cursor keeps the last one received. + if data.get("cursor") is not None: + self._cursor = data["cursor"] if self.parse_timestamp: data["timestamp"] = _parse_created_at(data["createdAt"]) return cast(dict[str, Any], data) diff --git a/tests/test_sse_cursor.py b/tests/test_sse_cursor.py new file mode 100644 index 0000000..67f20df --- /dev/null +++ b/tests/test_sse_cursor.py @@ -0,0 +1,166 @@ +"""Checks the SSE `cursor` resume: the stream keeps the last `cursor` an event +carried and sends it back on a reconnect asking for the same vehicles and +topics, so the connect snapshot starts after it. A first connect, or one +whose vehicles or topics changed, omits it and takes a full snapshot. +""" +from __future__ import annotations + +import asyncio +import json +from typing import Any + +from teslemetry_stream.stream import TeslemetryStream + +VIN = "LRW3F7EK4NC000001" + + +def line(event: dict[str, Any]) -> bytes: + return f"data: {json.dumps(event)}\n".encode() + + +def event(cursor: int | None = None) -> dict[str, Any]: + ev: dict[str, Any] = { + "vin": VIN, + "createdAt": "2026-11-07T10:00:00.000Z", + "data": {"Odometer": 1}, + } + if cursor is not None: + ev["cursor"] = cursor + return ev + + +class FakeContent: + """Response body that yields its lines once, then ends cleanly.""" + + def __init__(self, lines: list[bytes]) -> None: + self._lines = list(lines) + + def __aiter__(self) -> FakeContent: + return self + + async def __anext__(self) -> bytes: + if not self._lines: + raise StopAsyncIteration + return self._lines.pop(0) + + +class FakeResponse: + def __init__(self, events: list[dict[str, Any]]) -> None: + self.url = "https://fake.teslemetry.com/sse" + self.status = 200 + self.content = FakeContent([line(e) for e in events]) + + def close(self) -> None: + pass + + +class FakeSession: + def __init__(self, responses: list[FakeResponse]) -> None: + self._responses = list(responses) + self.calls: list[dict[str, Any]] = [] + + async def get(self, url: str, **kwargs: Any) -> FakeResponse: + self.calls.append({"url": url, **kwargs}) + return self._responses.pop(0) + + +def make_stream(session: FakeSession, **kwargs: Any) -> TeslemetryStream: + return TeslemetryStream( + session=session, # type: ignore[arg-type] + access_token="test-token", + server="api.teslemetry.com", + manual=True, + **kwargs, + ) + + +def sent_cursor(session: FakeSession, index: int) -> str | None: + return session.calls[index]["params"].get("cursor") + + +def check(label: str, ok: bool, detail: str = "") -> bool: + print(f"{label:<72} {'PASS' if ok else 'FAIL'}{' ' + detail if detail else ''}") + return ok + + +async def test_resume(results: list[bool]) -> None: + session = FakeSession( + [ + FakeResponse([event(5), event()]), + FakeResponse([event(9)]), + FakeResponse([event()]), + ] + ) + stream = make_stream(session, topics=["data"]) + stream.active = True + + await stream.__anext__() + results.append( + check("first connect omits cursor", sent_cursor(session, 0) is None) + ) + results.append(check("cursor tracked from an event", stream._cursor == 5)) + + await stream.__anext__() + results.append( + check("an event without cursor keeps the last value", stream._cursor == 5) + ) + + await stream.__anext__() # body ends, reconnects + results.append( + check( + "reconnect sends the last cursor", + sent_cursor(session, 1) == "5", + f"got {sent_cursor(session, 1)!r}", + ) + ) + results.append( + check( + "cursor sent next to cache=true", + session.calls[1]["params"].get("cache") == "true", + ) + ) + + stream.topics = ["data", "alerts"] + await stream.__anext__() # body ends, reconnects with new topics + results.append( + check( + "reconnect after a topic change omits cursor", + sent_cursor(session, 2) is None, + f"got {sent_cursor(session, 2)!r}", + ) + ) + results.append( + check("topic change discards the old cursor", stream._cursor is None) + ) + + +async def test_vehicle_change(results: list[bool]) -> None: + session = FakeSession( + [FakeResponse([event(5)]), FakeResponse([event()])] + ) + stream = make_stream(session, vin=VIN) + stream.active = True + + await stream.__anext__() + stream.vin = "LRW3F7EK4NC000002" + await stream.__anext__() # body ends, reconnects for another vehicle + results.append( + check( + "reconnect after a vehicle change omits cursor", + sent_cursor(session, 1) is None, + f"got {sent_cursor(session, 1)!r}", + ) + ) + + +async def main() -> int: + results: list[bool] = [] + await test_resume(results) + await test_vehicle_change(results) + passed = sum(results) + print(f"\n{passed}/{len(results)} checks passed") + return 0 if passed == len(results) else 1 + + +if __name__ == "__main__": + raise SystemExit(asyncio.run(main())) From e134f4194bf8d4c5fba6cb603cd5fc8906b29af0 Mon Sep 17 00:00:00 2001 From: "Brett Adams (Firstmate)" Date: Sat, 7 Nov 2026 21:46:25 +1000 Subject: [PATCH 2/2] fix: tie the cursor scope to the response that supplied it --- teslemetry_stream/stream.py | 9 +++++---- tests/test_sse_cursor.py | 37 +++++++++++++++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/teslemetry_stream/stream.py b/teslemetry_stream/stream.py index 3173005..b077b62 100644 --- a/teslemetry_stream/stream.py +++ b/teslemetry_stream/stream.py @@ -272,10 +272,7 @@ async def connect(self) -> None: if self.topics: params["topics"] = ",".join(self.topics) scope = (url, params.get("topics")) - if scope != self._cursor_scope: - self._cursor = None - self._cursor_scope = scope - elif self._cursor is not None: + if scope == self._cursor_scope and self._cursor is not None: params["cursor"] = str(self._cursor) response = await self._session.get( url, @@ -295,6 +292,10 @@ async def connect(self) -> None: if self._response is not None: self._response.close() self._response = response + # Only now, so a failed GET leaves the cursor tied to the response still supplying it. + if scope != self._cursor_scope: + self._cursor = None + self._cursor_scope = scope LOGGER.debug( "Connected to %s with status %s", self._response.url, self._response.status ) diff --git a/tests/test_sse_cursor.py b/tests/test_sse_cursor.py index 67f20df..7f11e25 100644 --- a/tests/test_sse_cursor.py +++ b/tests/test_sse_cursor.py @@ -6,9 +6,12 @@ from __future__ import annotations import asyncio +import contextlib import json from typing import Any +import aiohttp + from teslemetry_stream.stream import TeslemetryStream VIN = "LRW3F7EK4NC000001" @@ -55,13 +58,16 @@ def close(self) -> None: class FakeSession: - def __init__(self, responses: list[FakeResponse]) -> None: + def __init__(self, responses: list[FakeResponse | Exception]) -> None: self._responses = list(responses) self.calls: list[dict[str, Any]] = [] async def get(self, url: str, **kwargs: Any) -> FakeResponse: self.calls.append({"url": url, **kwargs}) - return self._responses.pop(0) + response = self._responses.pop(0) + if isinstance(response, Exception): + raise response + return response def make_stream(session: FakeSession, **kwargs: Any) -> TeslemetryStream: @@ -153,10 +159,37 @@ async def test_vehicle_change(results: list[bool]) -> None: ) +async def test_failed_connect_after_topic_change(results: list[bool]) -> None: + session = FakeSession( + [ + FakeResponse([event(5), event(7)]), + aiohttp.ClientError("refused"), + FakeResponse([event()]), + ] + ) + stream = make_stream(session, topics=["data"]) + stream.active = True + + await stream.__anext__() + stream.topics = ["data", "alerts"] + with contextlib.suppress(aiohttp.ClientError): + await stream.connect() # GET with the new topics fails + await stream.__anext__() # the old response is still supplying cursors + await stream.__anext__() # old body ends, reconnects with the new topics + results.append( + check( + "old response's cursor is not sent for the new topics", + sent_cursor(session, 2) is None, + f"got {sent_cursor(session, 2)!r}", + ) + ) + + async def main() -> int: results: list[bool] = [] await test_resume(results) await test_vehicle_change(results) + await test_failed_connect_after_topic_change(results) passed = sum(results) print(f"\n{passed}/{len(results)} checks passed") return 0 if passed == len(results) else 1