Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions docs/live.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@ Things to know, from testing:
- **`presence` starts with everyone's current state.** Listening doesn't publish your own status, so it
doesn't make you look online. Status changes were only seen live for the signed-in user, and someone
who was active in a chat stayed reported as `Offline`, so treat status as a hint.
- **Tokens renew by themselves.** The feed reconnects shortly before its session token expires, which can
leave a short gap. Catch up on `connected`.
- **Sessions renew by themselves.** The Teams session lasts about 75 minutes. Shortly before it expires,
the feed signs in again and reconnects straight away, even with `reconnect=False`, and yields
`connected`. Events in that short gap are missed, so catch up on `connected`.

## Showing that you're typing

Expand Down
16 changes: 14 additions & 2 deletions src/outnote/_live.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,17 @@ def presence_events(body, me=None):
return events


class _Renewal(Exception):
"""The session token is about to expire: a planned reconnect, not a failure."""


class LiveConnection:
"""An iterator of `LiveEvent`s that reconnects by itself, waiting longer after each failure. Stop
it with `close()`, from another thread if needed, or by leaving the `with` block."""
it with `close()`, from another thread if needed, or by leaving the `with` block.

The Teams session lasts about 75 minutes. Shortly before it expires, the feed signs in again and
reconnects straight away, even with `reconnect=False`, and yields `connected` again. Events sent
during that short gap are missed, so catch up on `connected` as usual."""

def __init__(self, client, reconnect=True, presence=()):
self.client, self.reconnect = client, reconnect
Expand Down Expand Up @@ -135,6 +143,10 @@ def __iter__(self):
yield LiveEvent("connected")
failures = 0
yield from self._frames()
except _Renewal:
log.info("live session renewed")
self._disconnect()
continue
except Exception as e: # noqa: BLE001 - network, auth or protocol: all mean reconnect
if not self.reconnect:
raise
Expand Down Expand Up @@ -270,7 +282,7 @@ def _frames(self):
while not self._closed:
if time.time() > expires - 120:
self.client._ids.pop("chatsvc", None) # so the reconnect signs in again
raise OSError("session token is about to expire")
raise _Renewal()
if time.monotonic() - beat > _HEARTBEAT:
self._send("2:::")
beat = time.monotonic()
Expand Down
13 changes: 13 additions & 0 deletions tests/test_live.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,19 @@ def sleep(seconds):
assert waits[:3] == [2, 4, 8] and max(waits) == _live._MAX_BACKOFF


def test_a_session_renewal_continues_even_without_reconnect(connected, monkeypatch):
live, sockets = connected([[], [delivery(raw())]], reconnect=False)
client = live.client
client._ids["chatsvc"]["exp"] = time.time() + 90 # inside the 120 s renewal margin
monkeypatch.setattr(client, "request", lambda *a, **k: AUTHZ)
waits = []
monkeypatch.setattr(live, "_sleep", waits.append)
events = take(live, 3)
assert [e.kind for e in events] == ["connected", "connected", "message"]
assert waits == [] # a planned renewal doesn't back off
assert sockets[0].closed and len(sockets) == 2


def test_reconnect_can_be_turned_off(connected):
live, _ = connected([[OSError("dropped")]], reconnect=False)
with pytest.raises(OSError):
Expand Down
Loading