Spaces:
Running

File size: 4,926 Bytes
6235836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
"""Live agent observations. Records are replaced, never mutated, so snapshots stay stable."""

from __future__ import annotations

import threading

PRESENCE_FLUSH_SECONDS = 30.0
ACTIVE_SECONDS = 60.0
FIELDS = ("last_seen_at", "last_poll_at", "listens", "cursor", "cursor_since", "waiting", "waiting_since")


def unknown() -> dict:
    return dict.fromkeys(FIELDS)


class Presence:
    def __init__(self, records: dict[int, dict] | None = None):
        self._records = records or {}
        self._dirty: dict[int, int] = {}
        self._version = 0
        self._poll_sequence = 0
        self._latest_poll: dict[int, int] = {}
        self._history: dict[int, tuple[float, int]] = {}
        self._last_sample_minute: int | None = None
        self._lock = threading.Lock()

    def _put(self, pid: int, record: dict) -> None:
        self._version += 1
        self._records[pid] = record
        self._dirty[pid] = self._version

    def seen(self, principal, now: float) -> None:
        if principal.is_human:
            return
        with self._lock:
            record = dict(self._records.get(principal.id, unknown()))
            record["last_seen_at"] = max(now, record["last_seen_at"] or now)
            self._put(principal.id, record)

    def next_poll(self) -> int:
        with self._lock:
            self._poll_sequence += 1
            return self._poll_sequence

    def polled(self, principal, token: int, now: float, cursor: int | None,
               mode: str, channel_ids: list[int], waiting: bool) -> None:
        if principal.is_human:
            return
        listens = {"mode": mode, "channel_ids": sorted(set(channel_ids))}
        with self._lock:
            if token < self._latest_poll.get(principal.id, 0):
                return
            self._latest_poll[principal.id] = token
            record = dict(self._records.get(principal.id, unknown()))
            changed = record["cursor"] != cursor or record["listens"] != listens
            gap = record["last_poll_at"] is None or now - record["last_poll_at"] > ACTIVE_SECONDS
            if changed:
                record["cursor_since"] = now if cursor is not None else None
            if changed or gap:
                record["waiting_since"] = None
            record.update(last_poll_at=now, listens=listens, cursor=cursor)
            self._set_waiting(record, waiting if cursor is not None else None, now)
            self._put(principal.id, record)

    @staticmethod
    def _set_waiting(record: dict, waiting: bool | None, now: float) -> None:
        record["waiting"] = waiting
        if waiting:
            if record["waiting_since"] is None:
                record["waiting_since"] = now
        else:
            record["waiting_since"] = None

    def observed(self, principal, token: int, waiting: bool, now: float) -> None:
        """A held poll can discover new work; older concurrent polls cannot overwrite newer ones."""
        if principal.is_human:
            return
        with self._lock:
            if token != self._latest_poll.get(principal.id):
                return
            record = dict(self._records[principal.id])
            self._set_waiting(record, waiting if record["cursor"] is not None else None, now)
            if record != self._records[principal.id]:
                self._put(principal.id, record)

    def snapshot(self) -> dict[int, dict]:
        with self._lock:
            return dict(self._records)

    def pending(self) -> tuple[dict[int, int], dict[int, dict]]:
        with self._lock:
            versions = dict(self._dirty)
            return versions, {pid: self._records[pid] for pid in versions}

    def saved(self, versions: dict[int, int]) -> None:
        with self._lock:
            for pid, version in versions.items():
                if self._dirty.get(pid) == version:
                    del self._dirty[pid]

    def listening_now(self, now: float) -> int:
        with self._lock:
            return self._listening_now(now)

    def _listening_now(self, now: float) -> int:
        return sum(record["last_poll_at"] is not None and 0 <= now - record["last_poll_at"] <= ACTIVE_SECONDS
                   for record in self._records.values())

    def sample(self, now: float) -> None:
        minute = int(now // 60) * 60
        with self._lock:
            if self._last_sample_minute is None or minute > self._last_sample_minute:
                self._last_sample_minute = minute
                self._history[minute] = (now, self._listening_now(now))

    def pending_history(self) -> dict[int, tuple[float, int]]:
        with self._lock:
            return dict(self._history)

    def history_saved(self, history: dict[int, tuple[float, int]]) -> None:
        with self._lock:
            for minute, sample in history.items():
                if self._history.get(minute) == sample:
                    del self._history[minute]