diff --git a/README.md b/README.md index 882d5f5..829d483 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,10 @@ async def main(): await stream.close() ``` +## Reconnects + +After a reconnect the stream resumes the connect-time snapshot from the last event `cursor` it received, so you are not resent what you already have. `server`, `vin` and `topics` are fixed for a stream object's lifetime; to use different ones, create a new `TeslemetryStream`, which starts with a full snapshot. + ## Energy Site Streaming Energy sites stream two events, `live_status` and `site_info`. Unlike vehicle diff --git a/teslemetry_stream/stream.py b/teslemetry_stream/stream.py index b077b62..22ef6de 100644 --- a/teslemetry_stream/stream.py +++ b/teslemetry_stream/stream.py @@ -87,10 +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. + # Last cache position received, sent back on every reconnect. server, vin + # and topics are fixed for the object's lifetime; a caller wanting + # different ones creates a new stream rather than reusing this cursor. 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] = {} @@ -271,8 +271,7 @@ 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 and self._cursor is not None: + if self._cursor is not None: params["cursor"] = str(self._cursor) response = await self._session.get( url, @@ -292,10 +291,6 @@ 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 7f11e25..dfe2c48 100644 --- a/tests/test_sse_cursor.py +++ b/tests/test_sse_cursor.py @@ -1,17 +1,13 @@ """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. +carried and sends it back on every reconnect, so the connect snapshot starts +after it. A first connect omits it and takes a full snapshot. """ from __future__ import annotations import asyncio -import contextlib import json from typing import Any -import aiohttp - from teslemetry_stream.stream import TeslemetryStream VIN = "LRW3F7EK4NC000001" @@ -126,70 +122,10 @@ async def test_resume(results: list[bool]) -> None: ) ) - 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 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