Spaces:
Running
Running
github-actions[bot] commited on
Commit ·
684a962
1
Parent(s): de05efa
Automated sync from GitHub
Browse files- .gitattributes +3 -3
- app/replace_engine.py +32 -3
- app/sync_engine.py +68 -7
- app/syncer.py +29 -5
- tests/test_sync_stuck.py +323 -0
.gitattributes
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
-
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 2 |
-
*.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 3 |
-
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 4 |
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 5 |
*.png filter=lfs diff=lfs merge=lfs -text
|
| 6 |
*.ttf filter=lfs diff=lfs merge=lfs -text
|
| 7 |
*.otf filter=lfs diff=lfs merge=lfs -text
|
| 8 |
*.webp filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 2 |
*.png filter=lfs diff=lfs merge=lfs -text
|
| 3 |
*.ttf filter=lfs diff=lfs merge=lfs -text
|
| 4 |
*.otf filter=lfs diff=lfs merge=lfs -text
|
| 5 |
*.webp filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
app/replace_engine.py
CHANGED
|
@@ -97,9 +97,38 @@ class UndoResult:
|
|
| 97 |
failed: list = field(default_factory=list)
|
| 98 |
|
| 99 |
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
|
| 105 |
async def get_top_id(client, peer) -> Optional[int]:
|
|
|
|
| 97 |
failed: list = field(default_factory=list)
|
| 98 |
|
| 99 |
|
| 100 |
+
STUCK_WAITS = (5.0, 20.0) # seconds: Telegram itself keeps failing -> the read is repeated after these pauses
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class TelegramStuck(ValueError):
|
| 104 |
+
"""Telegram itself kept failing (timeouts, internal errors) for a read: not a refusal, and the same request may work a
|
| 105 |
+
minute later. (A ValueError like Telethon's own "Request was unsuccessful", so handlers that caught that still do.)"""
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def is_stuck(e: BaseException) -> bool:
|
| 109 |
+
"""Telegram's own trouble after Telethon gave up on a request: a server error, a timeout, or Telethon's "Request was
|
| 110 |
+
unsuccessful 6 time(s)" (what it raises when each of its tries met such an error or a short flood wait)."""
|
| 111 |
+
if isinstance(e, (TelegramStuck, errors.ServerError, errors.TimedOutError)):
|
| 112 |
+
return True
|
| 113 |
+
return isinstance(e, ValueError) and str(e).startswith("Request was unsuccessful")
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
async def fetch_messages(client, peer, ids: list, *, waits=None) -> list:
|
| 117 |
+
"""The messages with these ids (None / MessageEmpty where there is none). When Telegram itself keeps failing, the read is
|
| 118 |
+
repeated after the pauses in `waits` (default STUCK_WAITS); when it never works TelegramStuck is raised."""
|
| 119 |
+
for pause in (*(STUCK_WAITS if waits is None else waits), None):
|
| 120 |
+
try:
|
| 121 |
+
res = await flood_retry(lambda: client.get_messages(peer, ids=ids))
|
| 122 |
+
return list(res)
|
| 123 |
+
except Exception as e:
|
| 124 |
+
if not is_stuck(e):
|
| 125 |
+
raise
|
| 126 |
+
span = f"{ids[0]}-{ids[-1]}" if ids else "-"
|
| 127 |
+
reason = str(e) if isinstance(e, ValueError) else type(e).__name__
|
| 128 |
+
if pause is None:
|
| 129 |
+
raise TelegramStuck(f"Telegram kept failing ({reason}) while I read messages {span}") from e
|
| 130 |
+
log.info("Telegram failed reading messages %s (%s): trying again in %ss", span, reason, pause)
|
| 131 |
+
await asyncio.sleep(pause)
|
| 132 |
|
| 133 |
|
| 134 |
async def get_top_id(client, peer) -> Optional[int]:
|
app/sync_engine.py
CHANGED
|
@@ -22,7 +22,11 @@ Safety rules
|
|
| 22 |
* what TELEGRAM does to a channel is not an admin's edit: a channel it restricts (a copyright strike turns every post
|
| 23 |
into "This message couldn't be displayed on your device due to copyright infringement"), a single post it holds
|
| 24 |
back, a notice shown instead of a post, or many posts that suddenly all show one and the same text are left exactly
|
| 25 |
-
as saved - nothing is edited, removed or added for them
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
"""
|
| 27 |
from __future__ import annotations
|
| 28 |
|
|
@@ -35,7 +39,7 @@ from typing import Any, Optional
|
|
| 35 |
from telethon import errors, types
|
| 36 |
|
| 37 |
from .db import as_utc, utcnow
|
| 38 |
-
from .replace_engine import fetch_messages
|
| 39 |
from .repost_engine import delete_batch
|
| 40 |
from .restrictions import message_restriction, norm_text, probe_channel
|
| 41 |
from .richmsg import Rich, entry as rich_entry, is_rich_message, plain_of_message, rich_from_received, rich_of, with_fingerprint
|
|
@@ -51,6 +55,9 @@ DEEP_EVERY = 24 * 3600 # the automatic looks read every possible id at least th
|
|
| 51 |
MIN_FOR_ANOMALY = 5
|
| 52 |
MASS_SAME = 5 # this many posts that suddenly show the very same new text are not edits by a person
|
| 53 |
MAX_PROBE = 300 # requests spent finding the newest message the first time (30 000 ids)
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
|
| 56 |
# ----------------------------------------------------------------------------------------------- options
|
|
@@ -95,6 +102,7 @@ class SyncReport:
|
|
| 95 |
busy: bool = False # a long job started: the look was cut short
|
| 96 |
anomaly: Optional[str] = None
|
| 97 |
error: Optional[str] = None
|
|
|
|
| 98 |
scanned_to: int = 0
|
| 99 |
|
| 100 |
@property
|
|
@@ -324,6 +332,47 @@ async def _adopt(db, ch, rep: SyncReport, fresh: list, opts: SyncOptions, busy,
|
|
| 324 |
rep.adopted.append(m.id)
|
| 325 |
|
| 326 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
async def _compare_saved(
|
| 328 |
client, db, ch, rep: SyncReport, opts: SyncOptions, busy, progress, moved=None, pts: Optional[int] = None
|
| 329 |
) -> None:
|
|
@@ -344,13 +393,15 @@ async def _compare_saved(
|
|
| 344 |
by_id = {p.message_id: p for p in judge}
|
| 345 |
ids = sorted(by_id)
|
| 346 |
gone, edits = [], []
|
|
|
|
|
|
|
| 347 |
for i in range(0, len(ids), CHUNK):
|
| 348 |
if busy():
|
| 349 |
rep.busy = True
|
| 350 |
return
|
| 351 |
chunk = ids[i : i + CHUNK]
|
| 352 |
-
|
| 353 |
-
for mid, m in
|
| 354 |
p = by_id[mid]
|
| 355 |
if is_gone(m):
|
| 356 |
gone.append(p)
|
|
@@ -370,12 +421,17 @@ async def _compare_saved(
|
|
| 370 |
if progress:
|
| 371 |
await progress(rep)
|
| 372 |
await asyncio.sleep(opts.pause)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 373 |
edits, held = split_mass_text(edits)
|
| 374 |
if held:
|
| 375 |
hold_back(rep, [p.message_id for p, _ in held], MASS_NOTE)
|
| 376 |
if gone:
|
| 377 |
really = moved is not None and moved >= len(gone) # at least one event for each post that vanished
|
| 378 |
-
|
|
|
|
| 379 |
if everything and not really:
|
| 380 |
# No earlier look to compare with (or too few events): is the bot blind, or are the posts really gone? If it
|
| 381 |
# can read other messages of the channel it is not blind.
|
|
@@ -385,7 +441,7 @@ async def _compare_saved(
|
|
| 385 |
really = await sees_live_messages(client, peer, pts, pause=opts.pause)
|
| 386 |
if everything and not really:
|
| 387 |
rep.anomaly = (
|
| 388 |
-
f"All {
|
| 389 |
"so none was removed here - check that the bot is still an admin of the channel."
|
| 390 |
)
|
| 391 |
else:
|
|
@@ -517,7 +573,8 @@ async def _import_history(client, db, ch, rep: SyncReport, opts: SyncOptions, bu
|
|
| 517 |
|
| 518 |
# ----------------------------------------------------------------------------------------- entry points
|
| 519 |
async def sync_channel(client, db, ch, opts: Optional[SyncOptions] = None, *, busy=None, progress=None) -> SyncReport:
|
| 520 |
-
"""One full look at a channel (see the module text). Never raises Telegram's refusals
|
|
|
|
| 521 |
opts = opts or SyncOptions()
|
| 522 |
busy = busy or (lambda: False)
|
| 523 |
rep = SyncReport(channel=ch)
|
|
@@ -538,6 +595,8 @@ async def sync_channel(client, db, ch, opts: Optional[SyncOptions] = None, *, bu
|
|
| 538 |
await _import_history(client, db, ch, rep, opts, busy, progress, state)
|
| 539 |
except errors.RPCError as e:
|
| 540 |
rep.error = explain_rpc(e)
|
|
|
|
|
|
|
| 541 |
return rep
|
| 542 |
|
| 543 |
|
|
@@ -597,4 +656,6 @@ async def sync_ids(client, db, ch, ids, opts: Optional[SyncOptions] = None, *, a
|
|
| 597 |
await _adopt(db, ch, rep, fresh, opts, busy, now)
|
| 598 |
except errors.RPCError as e:
|
| 599 |
rep.error = explain_rpc(e)
|
|
|
|
|
|
|
| 600 |
return rep
|
|
|
|
| 22 |
* what TELEGRAM does to a channel is not an admin's edit: a channel it restricts (a copyright strike turns every post
|
| 23 |
into "This message couldn't be displayed on your device due to copyright infringement"), a single post it holds
|
| 24 |
back, a notice shown instead of a post, or many posts that suddenly all show one and the same text are left exactly
|
| 25 |
+
as saved - nothing is edited, removed or added for them;
|
| 26 |
+
* when Telegram ITSELF keeps failing (timeouts, internal errors) a read is repeated after a pause; a batch it keeps
|
| 27 |
+
failing on is read again in smaller pieces, and a post it won't hand over even alone is left exactly as saved (it is
|
| 28 |
+
NOT taken for deleted); if it fails for everything the look is given up (`report.stuck`, nothing is decided on half a
|
| 29 |
+
look) and the next one tries again.
|
| 30 |
"""
|
| 31 |
from __future__ import annotations
|
| 32 |
|
|
|
|
| 39 |
from telethon import errors, types
|
| 40 |
|
| 41 |
from .db import as_utc, utcnow
|
| 42 |
+
from .replace_engine import TelegramStuck, fetch_messages
|
| 43 |
from .repost_engine import delete_batch
|
| 44 |
from .restrictions import message_restriction, norm_text, probe_channel
|
| 45 |
from .richmsg import Rich, entry as rich_entry, is_rich_message, plain_of_message, rich_from_received, rich_of, with_fingerprint
|
|
|
|
| 55 |
MIN_FOR_ANOMALY = 5
|
| 56 |
MASS_SAME = 5 # this many posts that suddenly show the very same new text are not edits by a person
|
| 57 |
MAX_PROBE = 300 # requests spent finding the newest message the first time (30 000 ids)
|
| 58 |
+
SPLIT = 10 # a batch of saved posts that Telegram keeps failing on is read again in pieces of this many ids, then singly
|
| 59 |
+
MAX_FAILS = 6 # failed requests (each costs Telethon's six tries) a look spends on finding the posts Telegram can't hand over
|
| 60 |
+
UNREADABLE_NOTE = "Telegram keeps failing when I ask for them"
|
| 61 |
|
| 62 |
|
| 63 |
# ----------------------------------------------------------------------------------------------- options
|
|
|
|
| 102 |
busy: bool = False # a long job started: the look was cut short
|
| 103 |
anomaly: Optional[str] = None
|
| 104 |
error: Optional[str] = None
|
| 105 |
+
stuck: bool = False # Telegram ITSELF kept failing (timeouts, internal errors): the look was cut short
|
| 106 |
scanned_to: int = 0
|
| 107 |
|
| 108 |
@property
|
|
|
|
| 332 |
rep.adopted.append(m.id)
|
| 333 |
|
| 334 |
|
| 335 |
+
def stuck_error(e: BaseException) -> str:
|
| 336 |
+
"""The report's words when Telegram ITSELF kept failing (timeouts, internal errors): not a refusal - the look is cut
|
| 337 |
+
short, nothing is decided on half a look, and the next check tries again."""
|
| 338 |
+
what = str(e) if isinstance(e, TelegramStuck) else f"Telegram kept failing ({type(e).__name__}: {str(e)[:80]})"
|
| 339 |
+
return f"{what} - this look was cut short, the next check tries again."
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
class Fails:
|
| 343 |
+
"""How one look fared while it read the saved posts: the requests that failed, and the latest failure."""
|
| 344 |
+
|
| 345 |
+
def __init__(self) -> None:
|
| 346 |
+
self.n = 0
|
| 347 |
+
self.last: Optional[TelegramStuck] = None
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
async def read_ids(
|
| 351 |
+
client, peer, ids: list, fails: Fails, lost: list, *, patient: bool = True, pause: float = PAUSE
|
| 352 |
+
) -> dict:
|
| 353 |
+
"""{id: message} for these ids (None / MessageEmpty: the message is gone). Telegram keeps failing on a batch when one
|
| 354 |
+
heavy or broken message in it makes the request time out: the batch is then read again in pieces of SPLIT ids, and a
|
| 355 |
+
piece that fails in single ids. An id that fails even alone is left out of the answer and added to `lost`: its saved
|
| 356 |
+
post stays exactly as it is - it is NOT taken for deleted. `fails` is shared by the whole look: past MAX_FAILS
|
| 357 |
+
Telegram is failing for everything, and TelegramStuck is raised."""
|
| 358 |
+
try:
|
| 359 |
+
got = await (fetch_messages(client, peer, ids) if patient else fetch_messages(client, peer, ids, waits=()))
|
| 360 |
+
return dict(zip(ids, got))
|
| 361 |
+
except TelegramStuck as e:
|
| 362 |
+
fails.n, fails.last = fails.n + 1, e
|
| 363 |
+
if fails.n > MAX_FAILS:
|
| 364 |
+
raise
|
| 365 |
+
if len(ids) == 1:
|
| 366 |
+
lost.extend(ids)
|
| 367 |
+
return {}
|
| 368 |
+
step = SPLIT if len(ids) > SPLIT else 1
|
| 369 |
+
out: dict = {}
|
| 370 |
+
for i in range(0, len(ids), step):
|
| 371 |
+
out.update(await read_ids(client, peer, ids[i : i + step], fails, lost, patient=False, pause=pause))
|
| 372 |
+
await asyncio.sleep(pause)
|
| 373 |
+
return out
|
| 374 |
+
|
| 375 |
+
|
| 376 |
async def _compare_saved(
|
| 377 |
client, db, ch, rep: SyncReport, opts: SyncOptions, busy, progress, moved=None, pts: Optional[int] = None
|
| 378 |
) -> None:
|
|
|
|
| 393 |
by_id = {p.message_id: p for p in judge}
|
| 394 |
ids = sorted(by_id)
|
| 395 |
gone, edits = [], []
|
| 396 |
+
fails = Fails() # the requests of this look that failed (see read_ids)
|
| 397 |
+
lost = [] # saved posts Telegram would not hand over: they stay exactly as saved
|
| 398 |
for i in range(0, len(ids), CHUNK):
|
| 399 |
if busy():
|
| 400 |
rep.busy = True
|
| 401 |
return
|
| 402 |
chunk = ids[i : i + CHUNK]
|
| 403 |
+
got = await read_ids(client, peer, chunk, fails, lost, pause=opts.pause)
|
| 404 |
+
for mid, m in got.items():
|
| 405 |
p = by_id[mid]
|
| 406 |
if is_gone(m):
|
| 407 |
gone.append(p)
|
|
|
|
| 421 |
if progress:
|
| 422 |
await progress(rep)
|
| 423 |
await asyncio.sleep(opts.pause)
|
| 424 |
+
if lost:
|
| 425 |
+
if len(lost) == len(ids): # not a single saved post could be read: Telegram is failing for everything
|
| 426 |
+
raise fails.last
|
| 427 |
+
hold_back(rep, lost, UNREADABLE_NOTE)
|
| 428 |
edits, held = split_mass_text(edits)
|
| 429 |
if held:
|
| 430 |
hold_back(rep, [p.message_id for p, _ in held], MASS_NOTE)
|
| 431 |
if gone:
|
| 432 |
really = moved is not None and moved >= len(gone) # at least one event for each post that vanished
|
| 433 |
+
seen = len(ids) - len(lost) # (a post Telegram would not hand over proves nothing either way)
|
| 434 |
+
everything = seen >= MIN_FOR_ANOMALY and len(gone) == seen
|
| 435 |
if everything and not really:
|
| 436 |
# No earlier look to compare with (or too few events): is the bot blind, or are the posts really gone? If it
|
| 437 |
# can read other messages of the channel it is not blind.
|
|
|
|
| 441 |
really = await sees_live_messages(client, peer, pts, pause=opts.pause)
|
| 442 |
if everything and not really:
|
| 443 |
rep.anomaly = (
|
| 444 |
+
f"All {seen} saved posts look deleted, and I can't read any other message of the channel either, "
|
| 445 |
"so none was removed here - check that the bot is still an admin of the channel."
|
| 446 |
)
|
| 447 |
else:
|
|
|
|
| 573 |
|
| 574 |
# ----------------------------------------------------------------------------------------- entry points
|
| 575 |
async def sync_channel(client, db, ch, opts: Optional[SyncOptions] = None, *, busy=None, progress=None) -> SyncReport:
|
| 576 |
+
"""One full look at a channel (see the module text). Never raises Telegram's refusals or its own trouble (timeouts,
|
| 577 |
+
internal errors): they end up in `report.error`."""
|
| 578 |
opts = opts or SyncOptions()
|
| 579 |
busy = busy or (lambda: False)
|
| 580 |
rep = SyncReport(channel=ch)
|
|
|
|
| 595 |
await _import_history(client, db, ch, rep, opts, busy, progress, state)
|
| 596 |
except errors.RPCError as e:
|
| 597 |
rep.error = explain_rpc(e)
|
| 598 |
+
except TelegramStuck as e:
|
| 599 |
+
rep.error, rep.stuck = stuck_error(e), True
|
| 600 |
return rep
|
| 601 |
|
| 602 |
|
|
|
|
| 656 |
await _adopt(db, ch, rep, fresh, opts, busy, now)
|
| 657 |
except errors.RPCError as e:
|
| 658 |
rep.error = explain_rpc(e)
|
| 659 |
+
except TelegramStuck as e:
|
| 660 |
+
rep.error, rep.stuck = stuck_error(e), True
|
| 661 |
return rep
|
app/syncer.py
CHANGED
|
@@ -15,8 +15,9 @@ import logging
|
|
| 15 |
import time
|
| 16 |
from typing import Optional
|
| 17 |
|
|
|
|
| 18 |
from .servicemsg import RIGHTS_ERRORS, action_label, remove
|
| 19 |
-
from .sync_engine import SyncOptions, SyncReport, sync_channel, sync_ids
|
| 20 |
from .tgutil import esc, peer_of
|
| 21 |
|
| 22 |
log = logging.getLogger(__name__)
|
|
@@ -37,6 +38,7 @@ class Syncer:
|
|
| 37 |
self.tell_restricted_every = 7 * 86400.0 # ... a restriction by Telegram can last for weeks: once a week
|
| 38 |
self.max_ids = 300 # more changed ids than this in one channel: look at the whole channel instead
|
| 39 |
self.max_tries = 8 # a message that stays "too fresh" is given up after this many rounds
|
|
|
|
| 40 |
self.history_seconds = 150.0 # a timed check reads a channel's older posts for this long, then goes on next time
|
| 41 |
self._busy = asyncio.Lock() # one look at a time
|
| 42 |
self._edits: dict = {} # channel id -> message ids edited
|
|
@@ -47,6 +49,7 @@ class Syncer:
|
|
| 47 |
self._tasks: list = []
|
| 48 |
self._cache: dict = {}
|
| 49 |
self._told: dict = {}
|
|
|
|
| 50 |
self.last_reports: dict = {} # channel id -> its latest SyncReport
|
| 51 |
|
| 52 |
# ----------------------------------------------------------------------------------------- running
|
|
@@ -140,6 +143,12 @@ class Syncer:
|
|
| 140 |
|
| 141 |
async def _after(self, ch, rep: SyncReport) -> None:
|
| 142 |
self.last_reports[ch.id] = rep
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
if rep.changed or rep.error or rep.anomaly:
|
| 144 |
log.info(
|
| 145 |
"channel %s: %s removed, %s updated, %s new, %s service messages deleted%s",
|
|
@@ -171,6 +180,13 @@ class Syncer:
|
|
| 171 |
"Their saved copies in My posts stay exactly as they are."
|
| 172 |
)
|
| 173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
@staticmethod
|
| 175 |
def _rights_text(ch, why: Optional[str]) -> str:
|
| 176 |
return (
|
|
@@ -207,8 +223,12 @@ class Syncer:
|
|
| 207 |
except asyncio.CancelledError:
|
| 208 |
raise
|
| 209 |
except Exception as e:
|
| 210 |
-
|
| 211 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
await self._after(ch, rep)
|
| 213 |
reports.append(rep)
|
| 214 |
return reports
|
|
@@ -306,8 +326,12 @@ class Syncer:
|
|
| 306 |
except asyncio.CancelledError:
|
| 307 |
raise
|
| 308 |
except Exception as e:
|
| 309 |
-
|
| 310 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
await self._after(ch, rep)
|
| 312 |
if rep.busy: # a long job started in the meantime: let the next timed check have it
|
| 313 |
continue
|
|
|
|
| 15 |
import time
|
| 16 |
from typing import Optional
|
| 17 |
|
| 18 |
+
from .replace_engine import is_stuck
|
| 19 |
from .servicemsg import RIGHTS_ERRORS, action_label, remove
|
| 20 |
+
from .sync_engine import SyncOptions, SyncReport, stuck_error, sync_channel, sync_ids
|
| 21 |
from .tgutil import esc, peer_of
|
| 22 |
|
| 23 |
log = logging.getLogger(__name__)
|
|
|
|
| 38 |
self.tell_restricted_every = 7 * 86400.0 # ... a restriction by Telegram can last for weeks: once a week
|
| 39 |
self.max_ids = 300 # more changed ids than this in one channel: look at the whole channel instead
|
| 40 |
self.max_tries = 8 # a message that stays "too fresh" is given up after this many rounds
|
| 41 |
+
self.stuck_looks = 3 # Telegram failing for this many looks at a channel in a row: the owners are told
|
| 42 |
self.history_seconds = 150.0 # a timed check reads a channel's older posts for this long, then goes on next time
|
| 43 |
self._busy = asyncio.Lock() # one look at a time
|
| 44 |
self._edits: dict = {} # channel id -> message ids edited
|
|
|
|
| 49 |
self._tasks: list = []
|
| 50 |
self._cache: dict = {}
|
| 51 |
self._told: dict = {}
|
| 52 |
+
self._stuck: dict = {} # channel id -> looks in a row that were cut short because Telegram kept failing
|
| 53 |
self.last_reports: dict = {} # channel id -> its latest SyncReport
|
| 54 |
|
| 55 |
# ----------------------------------------------------------------------------------------- running
|
|
|
|
| 143 |
|
| 144 |
async def _after(self, ch, rep: SyncReport) -> None:
|
| 145 |
self.last_reports[ch.id] = rep
|
| 146 |
+
if rep.stuck: # Telegram itself keeps failing: one or two looks are a blip, a few in a row are worth telling
|
| 147 |
+
self._stuck[ch.id] = self._stuck.get(ch.id, 0) + 1
|
| 148 |
+
if self._stuck[ch.id] >= self.stuck_looks:
|
| 149 |
+
await self.tell_owners(ch, "stuck", self._stuck_text(ch))
|
| 150 |
+
elif not rep.error and not rep.busy:
|
| 151 |
+
self._stuck.pop(ch.id, None)
|
| 152 |
if rep.changed or rep.error or rep.anomaly:
|
| 153 |
log.info(
|
| 154 |
"channel %s: %s removed, %s updated, %s new, %s service messages deleted%s",
|
|
|
|
| 180 |
"Their saved copies in My posts stay exactly as they are."
|
| 181 |
)
|
| 182 |
|
| 183 |
+
@staticmethod
|
| 184 |
+
def _stuck_text(ch) -> str:
|
| 185 |
+
return (
|
| 186 |
+
f"⚠️ Telegram keeps failing (timeouts / internal errors) when I read <b>{esc(ch.title)}</b>, so I can't compare "
|
| 187 |
+
"My posts with it for now. Nothing in My posts was changed; I try again at every check."
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
@staticmethod
|
| 191 |
def _rights_text(ch, why: Optional[str]) -> str:
|
| 192 |
return (
|
|
|
|
| 223 |
except asyncio.CancelledError:
|
| 224 |
raise
|
| 225 |
except Exception as e:
|
| 226 |
+
if is_stuck(e): # Telegram itself kept failing (not a bug): the next look tries again
|
| 227 |
+
log.info("looking at channel %s: Telegram kept failing: %s", ch.id, e)
|
| 228 |
+
rep = SyncReport(channel=ch, error=stuck_error(e), stuck=True)
|
| 229 |
+
else:
|
| 230 |
+
log.exception("looking at channel %s failed", ch.id)
|
| 231 |
+
rep = SyncReport(channel=ch, error=f"{type(e).__name__}: {str(e)[:120]}")
|
| 232 |
await self._after(ch, rep)
|
| 233 |
reports.append(rep)
|
| 234 |
return reports
|
|
|
|
| 326 |
except asyncio.CancelledError:
|
| 327 |
raise
|
| 328 |
except Exception as e:
|
| 329 |
+
if is_stuck(e): # Telegram itself kept failing (not a bug): the next timed check looks at these again
|
| 330 |
+
log.info("looking at the changes in channel %s: Telegram kept failing: %s", cid, e)
|
| 331 |
+
rep = SyncReport(channel=ch, error=stuck_error(e), stuck=True)
|
| 332 |
+
else:
|
| 333 |
+
log.exception("looking at the changes in channel %s failed", cid)
|
| 334 |
+
rep = SyncReport(channel=ch, error=f"{type(e).__name__}: {str(e)[:120]}")
|
| 335 |
await self._after(ch, rep)
|
| 336 |
if rep.busy: # a long job started in the meantime: let the next timed check have it
|
| 337 |
continue
|
tests/test_sync_stuck.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Telegram ITSELF failing (timeouts, internal errors) while the sync reads a channel: the read is repeated, a post Telegram
|
| 2 |
+
won't hand over is left exactly as saved (never taken for deleted), and when everything fails the look is given up quietly."""
|
| 3 |
+
import asyncio
|
| 4 |
+
import datetime
|
| 5 |
+
import logging
|
| 6 |
+
from types import SimpleNamespace
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
from telethon import errors, types
|
| 10 |
+
|
| 11 |
+
from app import replace_engine, sync_engine, syncer
|
| 12 |
+
from app.replace_engine import TelegramStuck, fetch_messages, is_stuck
|
| 13 |
+
from app.sync_engine import MAX_FAILS, Fails, SyncOptions, SyncReport, _compare_saved, read_ids, sync_channel, sync_ids
|
| 14 |
+
from app.syncer import Syncer
|
| 15 |
+
|
| 16 |
+
UNSUCCESSFUL = "Request was unsuccessful 6 time(s)" # what Telethon raises when all its tries failed
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def run(coro):
|
| 20 |
+
return asyncio.run(coro)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Flaky:
|
| 24 |
+
"""get_messages like Telethon's after it gave up on a request: it raises when `bad(ids)` says so."""
|
| 25 |
+
|
| 26 |
+
def __init__(self, bad=lambda ids: False, exc=lambda: ValueError(UNSUCCESSFUL), msgs=None):
|
| 27 |
+
self.bad, self.exc, self.msgs, self.calls = bad, exc, msgs or {}, []
|
| 28 |
+
|
| 29 |
+
async def get_messages(self, peer, ids=None):
|
| 30 |
+
self.calls.append(list(ids))
|
| 31 |
+
if self.bad(list(ids)):
|
| 32 |
+
raise self.exc()
|
| 33 |
+
return [self.msgs.get(i) for i in ids]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class Db:
|
| 37 |
+
def __init__(self, ids):
|
| 38 |
+
self.posts = [SimpleNamespace(message_id=i, updated_at=None, sent_at=None, text="") for i in ids]
|
| 39 |
+
self.forgotten = []
|
| 40 |
+
|
| 41 |
+
async def sent_posts(self, cid):
|
| 42 |
+
return list(self.posts)
|
| 43 |
+
|
| 44 |
+
async def posts_at(self, cid, ids):
|
| 45 |
+
return [p for p in self.posts if p.message_id in set(ids)]
|
| 46 |
+
|
| 47 |
+
async def forget_posts(self, cid, ids):
|
| 48 |
+
self.forgotten.extend(ids)
|
| 49 |
+
return len(ids)
|
| 50 |
+
|
| 51 |
+
async def get_sync(self, cid):
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
CH = SimpleNamespace(id=-1001, title="Channel")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@pytest.fixture(autouse=True)
|
| 59 |
+
def quick(monkeypatch):
|
| 60 |
+
monkeypatch.setattr(replace_engine, "STUCK_WAITS", (0, 0)) # no real pauses
|
| 61 |
+
monkeypatch.setattr(sync_engine, "peer_of", lambda ch: "peer")
|
| 62 |
+
|
| 63 |
+
async def probe(client, peer):
|
| 64 |
+
return 100, None, None
|
| 65 |
+
|
| 66 |
+
monkeypatch.setattr(sync_engine, "probe_channel", probe)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ----------------------------------------------------------------------------------------------- fetch_messages
|
| 70 |
+
def test_a_read_that_fails_is_repeated_and_works_later():
|
| 71 |
+
n = {"left": 2}
|
| 72 |
+
|
| 73 |
+
def bad(ids):
|
| 74 |
+
n["left"] -= 1
|
| 75 |
+
return n["left"] >= 0
|
| 76 |
+
|
| 77 |
+
client = Flaky(bad=bad, msgs={5: "five"})
|
| 78 |
+
assert run(fetch_messages(client, "peer", [5, 6])) == ["five", None]
|
| 79 |
+
assert len(client.calls) == 3 # two failures, then the answer
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_a_read_that_never_works_ends_as_telegram_stuck():
|
| 83 |
+
client = Flaky(bad=lambda ids: True)
|
| 84 |
+
with pytest.raises(TelegramStuck) as info:
|
| 85 |
+
run(fetch_messages(client, "peer", list(range(100, 200))))
|
| 86 |
+
assert isinstance(info.value, ValueError) # handlers that caught Telethon's own ValueError still catch it
|
| 87 |
+
assert "100-199" in str(info.value) and UNSUCCESSFUL in str(info.value)
|
| 88 |
+
assert len(client.calls) == 3 # the first try + one per pause
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def test_a_refusal_is_not_repeated():
|
| 92 |
+
client = Flaky(bad=lambda ids: True, exc=lambda: errors.ChannelPrivateError(request=None))
|
| 93 |
+
with pytest.raises(errors.ChannelPrivateError):
|
| 94 |
+
run(fetch_messages(client, "peer", [1]))
|
| 95 |
+
assert len(client.calls) == 1
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_waits_can_be_switched_off():
|
| 99 |
+
client = Flaky(bad=lambda ids: True)
|
| 100 |
+
with pytest.raises(TelegramStuck):
|
| 101 |
+
run(fetch_messages(client, "peer", [1, 2], waits=()))
|
| 102 |
+
assert len(client.calls) == 1
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@pytest.mark.parametrize(
|
| 106 |
+
"exc, stuck",
|
| 107 |
+
[
|
| 108 |
+
(ValueError(UNSUCCESSFUL), True),
|
| 109 |
+
(errors.RpcMcgetFailError(request=None), True),
|
| 110 |
+
(errors.ServerError(request=None, message="INTERNAL"), True),
|
| 111 |
+
(errors.TimedOutError(None, "Timeout"), True),
|
| 112 |
+
(TelegramStuck("x"), True),
|
| 113 |
+
(ValueError("something else"), False),
|
| 114 |
+
(errors.ChannelPrivateError(request=None), False),
|
| 115 |
+
(errors.FloodWaitError(request=None, capture=5), False),
|
| 116 |
+
(RuntimeError(UNSUCCESSFUL), False),
|
| 117 |
+
],
|
| 118 |
+
)
|
| 119 |
+
def test_what_counts_as_telegram_failing(exc, stuck):
|
| 120 |
+
assert is_stuck(exc) is stuck
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# ----------------------------------------------------------------------------------------------- read_ids
|
| 124 |
+
def test_one_post_that_breaks_the_request_is_found_and_the_rest_is_read():
|
| 125 |
+
client = Flaky(bad=lambda ids: 57 in ids)
|
| 126 |
+
fails, lost = Fails(), []
|
| 127 |
+
got = run(read_ids(client, "peer", list(range(1, 101)), fails, lost, pause=0))
|
| 128 |
+
assert sorted(got) == [i for i in range(1, 101) if i != 57]
|
| 129 |
+
assert lost == [57] # noted, to be left as saved
|
| 130 |
+
assert fails.n == 3 # the batch, the piece of ten, the post alone
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_two_bad_posts_in_different_places():
|
| 134 |
+
client = Flaky(bad=lambda ids: 5 in ids or 77 in ids)
|
| 135 |
+
lost = []
|
| 136 |
+
got = run(read_ids(client, "peer", list(range(1, 101)), Fails(), lost, pause=0))
|
| 137 |
+
assert sorted(got) == [i for i in range(1, 101) if i not in (5, 77)]
|
| 138 |
+
assert sorted(lost) == [5, 77]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def test_a_batch_that_is_only_too_heavy_is_read_in_pieces():
|
| 142 |
+
client = Flaky(bad=lambda ids: len(ids) > 30) # times out whenever many posts are asked for at once
|
| 143 |
+
lost = []
|
| 144 |
+
got = run(read_ids(client, "peer", list(range(1, 101)), Fails(), lost, pause=0))
|
| 145 |
+
assert sorted(got) == list(range(1, 101))
|
| 146 |
+
assert not lost # every post was read after all
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def test_when_telegram_fails_for_everything_the_look_is_given_up():
|
| 150 |
+
client = Flaky(bad=lambda ids: True)
|
| 151 |
+
fails = Fails()
|
| 152 |
+
with pytest.raises(TelegramStuck):
|
| 153 |
+
run(read_ids(client, "peer", list(range(1, 101)), fails, [], pause=0))
|
| 154 |
+
assert fails.n == MAX_FAILS + 1
|
| 155 |
+
assert len(client.calls) == 3 + MAX_FAILS # the batch is tried 3 times, then each failing piece once: it ends soon
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
# ----------------------------------------------------------------------------------------------- the comparison
|
| 159 |
+
def compare(db, client, **kw):
|
| 160 |
+
rep = SyncReport(channel=CH)
|
| 161 |
+
run(_compare_saved(client, db, CH, rep, SyncOptions(pause=0), lambda: False, None, **kw))
|
| 162 |
+
return rep
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def test_a_post_telegram_wont_hand_over_is_kept_while_the_deleted_ones_leave():
|
| 166 |
+
db = Db([1, 2, 3, 4])
|
| 167 |
+
rep = compare(db, Flaky(bad=lambda ids: 2 in ids)) # 1, 3, 4 are gone from the channel; 2 can't be read
|
| 168 |
+
assert db.forgotten == [1, 3, 4]
|
| 169 |
+
assert rep.deleted == [1, 3, 4]
|
| 170 |
+
assert 2 in rep.restricted and not rep.error and not rep.anomaly
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def test_unreadable_posts_do_not_switch_off_the_everything_was_deleted_check():
|
| 174 |
+
db = Db(range(1, 8)) # seven saved posts: six look deleted, the seventh can't be read - the bot may be blind
|
| 175 |
+
rep = compare(db, Flaky(bad=lambda ids: 7 in ids))
|
| 176 |
+
assert db.forgotten == []
|
| 177 |
+
assert rep.anomaly and "All 6 saved posts look deleted" in rep.anomaly
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def service(i):
|
| 181 |
+
return types.MessageService(id=i, peer_id=types.PeerChannel(1), date=datetime.datetime.now(datetime.timezone.utc), action=types.MessageActionEmpty())
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def test_one_bad_post_alone_in_the_last_batch_does_not_block_the_channel():
|
| 185 |
+
db = Db(range(1, 102)) # a hundred posts and one more
|
| 186 |
+
client = Flaky(bad=lambda ids: 101 in ids, msgs={i: service(i) for i in range(1, 101)})
|
| 187 |
+
rep = compare(db, client)
|
| 188 |
+
assert 101 in rep.restricted and not rep.error and not rep.anomaly
|
| 189 |
+
assert db.forgotten == []
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def test_a_small_channel_where_nothing_can_be_read_is_an_outage_not_many_bad_posts():
|
| 193 |
+
db = Db([1, 2, 3])
|
| 194 |
+
with pytest.raises(TelegramStuck):
|
| 195 |
+
compare(db, Flaky(bad=lambda ids: True))
|
| 196 |
+
assert db.forgotten == []
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def test_an_outage_decides_nothing():
|
| 200 |
+
db = Db(range(1, 8))
|
| 201 |
+
with pytest.raises(TelegramStuck):
|
| 202 |
+
compare(db, Flaky(bad=lambda ids: True))
|
| 203 |
+
assert db.forgotten == []
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# ----------------------------------------------------------------------------------------------- the entry points
|
| 207 |
+
def test_sync_channel_reports_an_outage_instead_of_raising():
|
| 208 |
+
db = Db([1, 2, 3])
|
| 209 |
+
rep = run(sync_channel(Flaky(bad=lambda ids: True), db, CH, SyncOptions(pause=0)))
|
| 210 |
+
assert rep.stuck and "cut short" in rep.error and UNSUCCESSFUL in rep.error
|
| 211 |
+
assert db.forgotten == []
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def test_sync_channel_still_reports_refusals_the_old_way():
|
| 215 |
+
db = Db([1, 2, 3])
|
| 216 |
+
client = Flaky(bad=lambda ids: True, exc=lambda: errors.ChannelPrivateError(request=None))
|
| 217 |
+
rep = run(sync_channel(client, db, CH, SyncOptions(pause=0)))
|
| 218 |
+
assert not rep.stuck and rep.error.startswith("Telegram refused")
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def test_sync_ids_reports_an_outage_instead_of_raising():
|
| 222 |
+
db = Db([5, 6])
|
| 223 |
+
rep = run(sync_ids(Flaky(bad=lambda ids: True), db, CH, [5, 6], SyncOptions(pause=0)))
|
| 224 |
+
assert rep.stuck and "cut short" in rep.error
|
| 225 |
+
assert db.forgotten == []
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
# ----------------------------------------------------------------------------------------------- the Syncer
|
| 229 |
+
class Sender:
|
| 230 |
+
def __init__(self):
|
| 231 |
+
self.sent = []
|
| 232 |
+
|
| 233 |
+
async def send_message(self, uid, text, link_preview=False):
|
| 234 |
+
self.sent.append((uid, text))
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def make_syncer():
|
| 238 |
+
sender = Sender()
|
| 239 |
+
cfg = SimpleNamespace(
|
| 240 |
+
owners={7}, sync_interval_minutes=60, delete_service_messages=False, import_old_posts=False
|
| 241 |
+
)
|
| 242 |
+
ctx = SimpleNamespace(cfg=cfg, client=sender, db=None, lock=asyncio.Lock(), sync_ignore=set())
|
| 243 |
+
return Syncer(ctx), sender
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def stuck_report():
|
| 247 |
+
return SyncReport(channel=CH, error="Telegram kept failing - cut short", stuck=True)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def test_the_owners_are_told_when_telegram_keeps_failing_look_after_look():
|
| 251 |
+
async def go():
|
| 252 |
+
s, sender = make_syncer()
|
| 253 |
+
for _ in range(2):
|
| 254 |
+
await s._after(CH, stuck_report())
|
| 255 |
+
assert sender.sent == [] # one or two bad looks are a blip
|
| 256 |
+
await s._after(CH, stuck_report())
|
| 257 |
+
assert len(sender.sent) == 1 and sender.sent[0][0] == 7 and "Channel" in sender.sent[0][1]
|
| 258 |
+
await s._after(CH, stuck_report())
|
| 259 |
+
assert len(sender.sent) == 1 # once a day
|
| 260 |
+
|
| 261 |
+
run(go())
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def test_a_good_look_starts_the_count_again():
|
| 265 |
+
async def go():
|
| 266 |
+
s, sender = make_syncer()
|
| 267 |
+
await s._after(CH, stuck_report())
|
| 268 |
+
await s._after(CH, stuck_report())
|
| 269 |
+
await s._after(CH, SyncReport(channel=CH)) # Telegram answers again
|
| 270 |
+
await s._after(CH, stuck_report())
|
| 271 |
+
await s._after(CH, stuck_report())
|
| 272 |
+
assert sender.sent == []
|
| 273 |
+
|
| 274 |
+
run(go())
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def test_run_all_logs_telegram_trouble_quietly_and_real_bugs_loudly(monkeypatch, caplog):
|
| 278 |
+
async def go(exc):
|
| 279 |
+
s, _ = make_syncer()
|
| 280 |
+
|
| 281 |
+
async def boom(*a, **k):
|
| 282 |
+
raise exc
|
| 283 |
+
|
| 284 |
+
monkeypatch.setattr(syncer, "sync_channel", boom)
|
| 285 |
+
return (await s.run_all([CH]))[0]
|
| 286 |
+
|
| 287 |
+
with caplog.at_level(logging.INFO):
|
| 288 |
+
rep = run(go(ValueError(UNSUCCESSFUL)))
|
| 289 |
+
assert rep.stuck and "cut short" in rep.error
|
| 290 |
+
assert not [r for r in caplog.records if r.levelno >= logging.ERROR] # no traceback in the log
|
| 291 |
+
|
| 292 |
+
caplog.clear()
|
| 293 |
+
with caplog.at_level(logging.INFO):
|
| 294 |
+
rep = run(go(ValueError("boom")))
|
| 295 |
+
assert not rep.stuck and rep.error == "ValueError: boom"
|
| 296 |
+
assert [r for r in caplog.records if r.levelno >= logging.ERROR]
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def test_live_changes_log_telegram_trouble_quietly_too(monkeypatch, caplog):
|
| 300 |
+
async def go(exc):
|
| 301 |
+
s, _ = make_syncer()
|
| 302 |
+
|
| 303 |
+
async def channel(cid):
|
| 304 |
+
return CH
|
| 305 |
+
|
| 306 |
+
async def boom(*a, **k):
|
| 307 |
+
raise exc
|
| 308 |
+
|
| 309 |
+
monkeypatch.setattr(s, "channel", channel)
|
| 310 |
+
monkeypatch.setattr(syncer, "sync_ids", boom)
|
| 311 |
+
await s._process({CH.id: {5}}, {})
|
| 312 |
+
return s.last_reports[CH.id]
|
| 313 |
+
|
| 314 |
+
with caplog.at_level(logging.INFO):
|
| 315 |
+
rep = run(go(errors.RpcCallFailError(request=None)))
|
| 316 |
+
assert rep.stuck and "cut short" in rep.error
|
| 317 |
+
assert not [r for r in caplog.records if r.levelno >= logging.ERROR]
|
| 318 |
+
|
| 319 |
+
caplog.clear()
|
| 320 |
+
with caplog.at_level(logging.INFO):
|
| 321 |
+
rep = run(go(ValueError("boom")))
|
| 322 |
+
assert not rep.stuck and rep.error == "ValueError: boom"
|
| 323 |
+
assert [r for r in caplog.records if r.levelno >= logging.ERROR]
|