File size: 12,027 Bytes
684a962
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
"""Telegram ITSELF failing (timeouts, internal errors) while the sync reads a channel: the read is repeated, a post Telegram
won't hand over is left exactly as saved (never taken for deleted), and when everything fails the look is given up quietly."""
import asyncio
import datetime
import logging
from types import SimpleNamespace

import pytest
from telethon import errors, types

from app import replace_engine, sync_engine, syncer
from app.replace_engine import TelegramStuck, fetch_messages, is_stuck
from app.sync_engine import MAX_FAILS, Fails, SyncOptions, SyncReport, _compare_saved, read_ids, sync_channel, sync_ids
from app.syncer import Syncer

UNSUCCESSFUL = "Request was unsuccessful 6 time(s)"  # what Telethon raises when all its tries failed


def run(coro):
    return asyncio.run(coro)


class Flaky:
    """get_messages like Telethon's after it gave up on a request: it raises when `bad(ids)` says so."""

    def __init__(self, bad=lambda ids: False, exc=lambda: ValueError(UNSUCCESSFUL), msgs=None):
        self.bad, self.exc, self.msgs, self.calls = bad, exc, msgs or {}, []

    async def get_messages(self, peer, ids=None):
        self.calls.append(list(ids))
        if self.bad(list(ids)):
            raise self.exc()
        return [self.msgs.get(i) for i in ids]


class Db:
    def __init__(self, ids):
        self.posts = [SimpleNamespace(message_id=i, updated_at=None, sent_at=None, text="") for i in ids]
        self.forgotten = []

    async def sent_posts(self, cid):
        return list(self.posts)

    async def posts_at(self, cid, ids):
        return [p for p in self.posts if p.message_id in set(ids)]

    async def forget_posts(self, cid, ids):
        self.forgotten.extend(ids)
        return len(ids)

    async def get_sync(self, cid):
        return None


CH = SimpleNamespace(id=-1001, title="Channel")


@pytest.fixture(autouse=True)
def quick(monkeypatch):
    monkeypatch.setattr(replace_engine, "STUCK_WAITS", (0, 0))  # no real pauses
    monkeypatch.setattr(sync_engine, "peer_of", lambda ch: "peer")

    async def probe(client, peer):
        return 100, None, None

    monkeypatch.setattr(sync_engine, "probe_channel", probe)


# ----------------------------------------------------------------------------------------------- fetch_messages
def test_a_read_that_fails_is_repeated_and_works_later():
    n = {"left": 2}

    def bad(ids):
        n["left"] -= 1
        return n["left"] >= 0

    client = Flaky(bad=bad, msgs={5: "five"})
    assert run(fetch_messages(client, "peer", [5, 6])) == ["five", None]
    assert len(client.calls) == 3  # two failures, then the answer


def test_a_read_that_never_works_ends_as_telegram_stuck():
    client = Flaky(bad=lambda ids: True)
    with pytest.raises(TelegramStuck) as info:
        run(fetch_messages(client, "peer", list(range(100, 200))))
    assert isinstance(info.value, ValueError)  # handlers that caught Telethon's own ValueError still catch it
    assert "100-199" in str(info.value) and UNSUCCESSFUL in str(info.value)
    assert len(client.calls) == 3  # the first try + one per pause


def test_a_refusal_is_not_repeated():
    client = Flaky(bad=lambda ids: True, exc=lambda: errors.ChannelPrivateError(request=None))
    with pytest.raises(errors.ChannelPrivateError):
        run(fetch_messages(client, "peer", [1]))
    assert len(client.calls) == 1


def test_waits_can_be_switched_off():
    client = Flaky(bad=lambda ids: True)
    with pytest.raises(TelegramStuck):
        run(fetch_messages(client, "peer", [1, 2], waits=()))
    assert len(client.calls) == 1


@pytest.mark.parametrize(
    "exc, stuck",
    [
        (ValueError(UNSUCCESSFUL), True),
        (errors.RpcMcgetFailError(request=None), True),
        (errors.ServerError(request=None, message="INTERNAL"), True),
        (errors.TimedOutError(None, "Timeout"), True),
        (TelegramStuck("x"), True),
        (ValueError("something else"), False),
        (errors.ChannelPrivateError(request=None), False),
        (errors.FloodWaitError(request=None, capture=5), False),
        (RuntimeError(UNSUCCESSFUL), False),
    ],
)
def test_what_counts_as_telegram_failing(exc, stuck):
    assert is_stuck(exc) is stuck


# ----------------------------------------------------------------------------------------------- read_ids
def test_one_post_that_breaks_the_request_is_found_and_the_rest_is_read():
    client = Flaky(bad=lambda ids: 57 in ids)
    fails, lost = Fails(), []
    got = run(read_ids(client, "peer", list(range(1, 101)), fails, lost, pause=0))
    assert sorted(got) == [i for i in range(1, 101) if i != 57]
    assert lost == [57]  # noted, to be left as saved
    assert fails.n == 3  # the batch, the piece of ten, the post alone


def test_two_bad_posts_in_different_places():
    client = Flaky(bad=lambda ids: 5 in ids or 77 in ids)
    lost = []
    got = run(read_ids(client, "peer", list(range(1, 101)), Fails(), lost, pause=0))
    assert sorted(got) == [i for i in range(1, 101) if i not in (5, 77)]
    assert sorted(lost) == [5, 77]


def test_a_batch_that_is_only_too_heavy_is_read_in_pieces():
    client = Flaky(bad=lambda ids: len(ids) > 30)  # times out whenever many posts are asked for at once
    lost = []
    got = run(read_ids(client, "peer", list(range(1, 101)), Fails(), lost, pause=0))
    assert sorted(got) == list(range(1, 101))
    assert not lost  # every post was read after all


def test_when_telegram_fails_for_everything_the_look_is_given_up():
    client = Flaky(bad=lambda ids: True)
    fails = Fails()
    with pytest.raises(TelegramStuck):
        run(read_ids(client, "peer", list(range(1, 101)), fails, [], pause=0))
    assert fails.n == MAX_FAILS + 1
    assert len(client.calls) == 3 + MAX_FAILS  # the batch is tried 3 times, then each failing piece once: it ends soon


# ----------------------------------------------------------------------------------------------- the comparison
def compare(db, client, **kw):
    rep = SyncReport(channel=CH)
    run(_compare_saved(client, db, CH, rep, SyncOptions(pause=0), lambda: False, None, **kw))
    return rep


def test_a_post_telegram_wont_hand_over_is_kept_while_the_deleted_ones_leave():
    db = Db([1, 2, 3, 4])
    rep = compare(db, Flaky(bad=lambda ids: 2 in ids))  # 1, 3, 4 are gone from the channel; 2 can't be read
    assert db.forgotten == [1, 3, 4]
    assert rep.deleted == [1, 3, 4]
    assert 2 in rep.restricted and not rep.error and not rep.anomaly


def test_unreadable_posts_do_not_switch_off_the_everything_was_deleted_check():
    db = Db(range(1, 8))  # seven saved posts: six look deleted, the seventh can't be read - the bot may be blind
    rep = compare(db, Flaky(bad=lambda ids: 7 in ids))
    assert db.forgotten == []
    assert rep.anomaly and "All 6 saved posts look deleted" in rep.anomaly


def service(i):
    return types.MessageService(id=i, peer_id=types.PeerChannel(1), date=datetime.datetime.now(datetime.timezone.utc), action=types.MessageActionEmpty())


def test_one_bad_post_alone_in_the_last_batch_does_not_block_the_channel():
    db = Db(range(1, 102))  # a hundred posts and one more
    client = Flaky(bad=lambda ids: 101 in ids, msgs={i: service(i) for i in range(1, 101)})
    rep = compare(db, client)
    assert 101 in rep.restricted and not rep.error and not rep.anomaly
    assert db.forgotten == []


def test_a_small_channel_where_nothing_can_be_read_is_an_outage_not_many_bad_posts():
    db = Db([1, 2, 3])
    with pytest.raises(TelegramStuck):
        compare(db, Flaky(bad=lambda ids: True))
    assert db.forgotten == []


def test_an_outage_decides_nothing():
    db = Db(range(1, 8))
    with pytest.raises(TelegramStuck):
        compare(db, Flaky(bad=lambda ids: True))
    assert db.forgotten == []


# ----------------------------------------------------------------------------------------------- the entry points
def test_sync_channel_reports_an_outage_instead_of_raising():
    db = Db([1, 2, 3])
    rep = run(sync_channel(Flaky(bad=lambda ids: True), db, CH, SyncOptions(pause=0)))
    assert rep.stuck and "cut short" in rep.error and UNSUCCESSFUL in rep.error
    assert db.forgotten == []


def test_sync_channel_still_reports_refusals_the_old_way():
    db = Db([1, 2, 3])
    client = Flaky(bad=lambda ids: True, exc=lambda: errors.ChannelPrivateError(request=None))
    rep = run(sync_channel(client, db, CH, SyncOptions(pause=0)))
    assert not rep.stuck and rep.error.startswith("Telegram refused")


def test_sync_ids_reports_an_outage_instead_of_raising():
    db = Db([5, 6])
    rep = run(sync_ids(Flaky(bad=lambda ids: True), db, CH, [5, 6], SyncOptions(pause=0)))
    assert rep.stuck and "cut short" in rep.error
    assert db.forgotten == []


# ----------------------------------------------------------------------------------------------- the Syncer
class Sender:
    def __init__(self):
        self.sent = []

    async def send_message(self, uid, text, link_preview=False):
        self.sent.append((uid, text))


def make_syncer():
    sender = Sender()
    cfg = SimpleNamespace(
        owners={7}, sync_interval_minutes=60, delete_service_messages=False, import_old_posts=False
    )
    ctx = SimpleNamespace(cfg=cfg, client=sender, db=None, lock=asyncio.Lock(), sync_ignore=set())
    return Syncer(ctx), sender


def stuck_report():
    return SyncReport(channel=CH, error="Telegram kept failing - cut short", stuck=True)


def test_the_owners_are_told_when_telegram_keeps_failing_look_after_look():
    async def go():
        s, sender = make_syncer()
        for _ in range(2):
            await s._after(CH, stuck_report())
        assert sender.sent == []  # one or two bad looks are a blip
        await s._after(CH, stuck_report())
        assert len(sender.sent) == 1 and sender.sent[0][0] == 7 and "Channel" in sender.sent[0][1]
        await s._after(CH, stuck_report())
        assert len(sender.sent) == 1  # once a day

    run(go())


def test_a_good_look_starts_the_count_again():
    async def go():
        s, sender = make_syncer()
        await s._after(CH, stuck_report())
        await s._after(CH, stuck_report())
        await s._after(CH, SyncReport(channel=CH))  # Telegram answers again
        await s._after(CH, stuck_report())
        await s._after(CH, stuck_report())
        assert sender.sent == []

    run(go())


def test_run_all_logs_telegram_trouble_quietly_and_real_bugs_loudly(monkeypatch, caplog):
    async def go(exc):
        s, _ = make_syncer()

        async def boom(*a, **k):
            raise exc

        monkeypatch.setattr(syncer, "sync_channel", boom)
        return (await s.run_all([CH]))[0]

    with caplog.at_level(logging.INFO):
        rep = run(go(ValueError(UNSUCCESSFUL)))
    assert rep.stuck and "cut short" in rep.error
    assert not [r for r in caplog.records if r.levelno >= logging.ERROR]  # no traceback in the log

    caplog.clear()
    with caplog.at_level(logging.INFO):
        rep = run(go(ValueError("boom")))
    assert not rep.stuck and rep.error == "ValueError: boom"
    assert [r for r in caplog.records if r.levelno >= logging.ERROR]


def test_live_changes_log_telegram_trouble_quietly_too(monkeypatch, caplog):
    async def go(exc):
        s, _ = make_syncer()

        async def channel(cid):
            return CH

        async def boom(*a, **k):
            raise exc

        monkeypatch.setattr(s, "channel", channel)
        monkeypatch.setattr(syncer, "sync_ids", boom)
        await s._process({CH.id: {5}}, {})
        return s.last_reports[CH.id]

    with caplog.at_level(logging.INFO):
        rep = run(go(errors.RpcCallFailError(request=None)))
    assert rep.stuck and "cut short" in rep.error
    assert not [r for r in caplog.records if r.levelno >= logging.ERROR]

    caplog.clear()
    with caplog.at_level(logging.INFO):
        rep = run(go(ValueError("boom")))
    assert not rep.stuck and rep.error == "ValueError: boom"
    assert [r for r in caplog.records if r.levelno >= logging.ERROR]