Spaces:
Running
Running
github-actions[bot] commited on
Commit ·
684a962
1
Parent(s): de05efa
Automated sync from GitHub
Browse filesFiles changed (5)
- .gitattributes+3-3
- app/replace_engine.py+32-3
- app/sync_engine.py+68-7
- app/syncer.py+29-5
- tests/test_sync_stuck.pyAdded+323
12345678*.mp4 filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.ttf filter=lfs diff=lfs merge=lfs -text*.otf filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -text12345678*.jpeg filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.ttf filter=lfs diff=lfs merge=lfs -text*.otf filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -text*.mp4 filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text*.jpg filter=lfs diff=lfs merge=lfs -text
96 unmodified lines97989910010110210310410596 unmodified linesfailed: list = field(default_factory=list)async def fetch_messages(client, peer, ids: list) -> list:res = await flood_retry(lambda: client.get_messages(peer, ids=ids))return list(res)async def get_top_id(client, peer) -> Optional[int]:96 unmodified lines97989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313496 unmodified linesfailed: list = field(default_factory=list)STUCK_WAITS = (5.0, 20.0) # seconds: Telegram itself keeps failing -> the read is repeated after these pausesclass TelegramStuck(ValueError):"""Telegram itself kept failing (timeouts, internal errors) for a read: not a refusal, and the same request may work aminute later. (A ValueError like Telethon's own "Request was unsuccessful", so handlers that caught that still do.)"""def is_stuck(e: BaseException) -> bool:"""Telegram's own trouble after Telethon gave up on a request: a server error, a timeout, or Telethon's "Request wasunsuccessful 6 time(s)" (what it raises when each of its tries met such an error or a short flood wait)."""if isinstance(e, (TelegramStuck, errors.ServerError, errors.TimedOutError)):return Truereturn isinstance(e, ValueError) and str(e).startswith("Request was unsuccessful")async def fetch_messages(client, peer, ids: list, *, waits=None) -> list:"""The messages with these ids (None / MessageEmpty where there is none). When Telegram itself keeps failing, the read isrepeated after the pauses in `waits` (default STUCK_WAITS); when it never works TelegramStuck is raised."""for pause in (*(STUCK_WAITS if waits is None else waits), None):try:res = await flood_retry(lambda: client.get_messages(peer, ids=ids))return list(res)except Exception as e:if not is_stuck(e):raisespan = f"{ids[0]}-{ids[-1]}" if ids else "-"reason = str(e) if isinstance(e, ValueError) else type(e).__name__if pause is None:raise TelegramStuck(f"Telegram kept failing ({reason}) while I read messages {span}") from elog.info("Telegram failed reading messages %s (%s): trying again in %ss", span, reason, pause)await asyncio.sleep(pause)async def get_top_id(client, peer) -> Optional[int]:
21 unmodified lines222324252627286 unmodified lines353637383940419 unmodified lines51525354555638 unmodified lines9596979899100223 unmodified lines32432532632732832914 unmodified lines34434534634734834935035135235335435535613 unmodified lines3703713723733743753763773783793803813 unmodified lines385386387388389390391125 unmodified lines51751851952052152252314 unmodified lines53853954054154254353 unmodified lines59759859960021 unmodified lines* what TELEGRAM does to a channel is not an admin's edit: a channel it restricts (a copyright strike turns every postinto "This message couldn't be displayed on your device due to copyright infringement"), a single post it holdsback, a notice shown instead of a post, or many posts that suddenly all show one and the same text are left exactlyas saved - nothing is edited, removed or added for them."""from __future__ import annotations6 unmodified linesfrom telethon import errors, typesfrom .db import as_utc, utcnowfrom .replace_engine import fetch_messagesfrom .repost_engine import delete_batchfrom .restrictions import message_restriction, norm_text, probe_channelfrom .richmsg import Rich, entry as rich_entry, is_rich_message, plain_of_message, rich_from_received, rich_of, with_fingerprint9 unmodified linesMIN_FOR_ANOMALY = 5MASS_SAME = 5 # this many posts that suddenly show the very same new text are not edits by a personMAX_PROBE = 300 # requests spent finding the newest message the first time (30 000 ids)# ----------------------------------------------------------------------------------------------- options38 unmodified linesbusy: bool = False # a long job started: the look was cut shortanomaly: Optional[str] = Noneerror: Optional[str] = Nonescanned_to: int = 0@property223 unmodified linesrep.adopted.append(m.id)async def _compare_saved(client, db, ch, rep: SyncReport, opts: SyncOptions, busy, progress, moved=None, pts: Optional[int] = None) -> None:14 unmodified linesby_id = {p.message_id: p for p in judge}ids = sorted(by_id)gone, edits = [], []for i in range(0, len(ids), CHUNK):if busy():rep.busy = Truereturnchunk = ids[i : i + CHUNK]msgs = await fetch_messages(client, peer, chunk)for mid, m in zip(chunk, msgs):p = by_id[mid]if is_gone(m):gone.append(p)13 unmodified linesif progress:await progress(rep)await asyncio.sleep(opts.pause)edits, held = split_mass_text(edits)if held:hold_back(rep, [p.message_id for p, _ in held], MASS_NOTE)if gone:really = moved is not None and moved >= len(gone) # at least one event for each post that vanishedeverything = len(ids) >= MIN_FOR_ANOMALY and len(gone) == len(ids)if everything and not really:# No earlier look to compare with (or too few events): is the bot blind, or are the posts really gone? If it# can read other messages of the channel it is not blind.3 unmodified linesreally = await sees_live_messages(client, peer, pts, pause=opts.pause)if everything and not really:rep.anomaly = (f"All {len(ids)} saved posts look deleted, and I can't read any other message of the channel either, ""so none was removed here - check that the bot is still an admin of the channel.")else:125 unmodified lines# ----------------------------------------------------------------------------------------- entry pointsasync def sync_channel(client, db, ch, opts: Optional[SyncOptions] = None, *, busy=None, progress=None) -> SyncReport:"""One full look at a channel (see the module text). Never raises Telegram's refusals: they end up in `report.error`."""opts = opts or SyncOptions()busy = busy or (lambda: False)rep = SyncReport(channel=ch)14 unmodified linesawait _import_history(client, db, ch, rep, opts, busy, progress, state)except errors.RPCError as e:rep.error = explain_rpc(e)return rep53 unmodified linesawait _adopt(db, ch, rep, fresh, opts, busy, now)except errors.RPCError as e:rep.error = explain_rpc(e)return rep21 unmodified lines22232425262728293031326 unmodified lines394041424344459 unmodified lines55565758596061626338 unmodified lines102103104105106107108223 unmodified lines33233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737814 unmodified lines39339439539639739839940040140240340440540640713 unmodified lines4214224234244254264274284294304314324334344354364373 unmodified lines441442443444445446447125 unmodified lines57357457557657757857958014 unmodified lines59559659759859960060160253 unmodified lines65665765865966066121 unmodified lines* what TELEGRAM does to a channel is not an admin's edit: a channel it restricts (a copyright strike turns every postinto "This message couldn't be displayed on your device due to copyright infringement"), a single post it holdsback, a notice shown instead of a post, or many posts that suddenly all show one and the same text are left exactlyas saved - nothing is edited, removed or added for them;* when Telegram ITSELF keeps failing (timeouts, internal errors) a read is repeated after a pause; a batch it keepsfailing on is read again in smaller pieces, and a post it won't hand over even alone is left exactly as saved (it isNOT taken for deleted); if it fails for everything the look is given up (`report.stuck`, nothing is decided on half alook) and the next one tries again."""from __future__ import annotations6 unmodified linesfrom telethon import errors, typesfrom .db import as_utc, utcnowfrom .replace_engine import TelegramStuck, fetch_messagesfrom .repost_engine import delete_batchfrom .restrictions import message_restriction, norm_text, probe_channelfrom .richmsg import Rich, entry as rich_entry, is_rich_message, plain_of_message, rich_from_received, rich_of, with_fingerprint9 unmodified linesMIN_FOR_ANOMALY = 5MASS_SAME = 5 # this many posts that suddenly show the very same new text are not edits by a personMAX_PROBE = 300 # requests spent finding the newest message the first time (30 000 ids)SPLIT = 10 # a batch of saved posts that Telegram keeps failing on is read again in pieces of this many ids, then singlyMAX_FAILS = 6 # failed requests (each costs Telethon's six tries) a look spends on finding the posts Telegram can't hand overUNREADABLE_NOTE = "Telegram keeps failing when I ask for them"# ----------------------------------------------------------------------------------------------- options38 unmodified linesbusy: bool = False # a long job started: the look was cut shortanomaly: Optional[str] = Noneerror: Optional[str] = Nonestuck: bool = False # Telegram ITSELF kept failing (timeouts, internal errors): the look was cut shortscanned_to: int = 0@property223 unmodified linesrep.adopted.append(m.id)def stuck_error(e: BaseException) -> str:"""The report's words when Telegram ITSELF kept failing (timeouts, internal errors): not a refusal - the look is cutshort, nothing is decided on half a look, and the next check tries again."""what = str(e) if isinstance(e, TelegramStuck) else f"Telegram kept failing ({type(e).__name__}: {str(e)[:80]})"return f"{what} - this look was cut short, the next check tries again."class Fails:"""How one look fared while it read the saved posts: the requests that failed, and the latest failure."""def __init__(self) -> None:self.n = 0self.last: Optional[TelegramStuck] = Noneasync def read_ids(client, peer, ids: list, fails: Fails, lost: list, *, patient: bool = True, pause: float = PAUSE) -> dict:"""{id: message} for these ids (None / MessageEmpty: the message is gone). Telegram keeps failing on a batch when oneheavy or broken message in it makes the request time out: the batch is then read again in pieces of SPLIT ids, and apiece that fails in single ids. An id that fails even alone is left out of the answer and added to `lost`: its savedpost stays exactly as it is - it is NOT taken for deleted. `fails` is shared by the whole look: past MAX_FAILSTelegram is failing for everything, and TelegramStuck is raised."""try:got = await (fetch_messages(client, peer, ids) if patient else fetch_messages(client, peer, ids, waits=()))return dict(zip(ids, got))except TelegramStuck as e:fails.n, fails.last = fails.n + 1, eif fails.n > MAX_FAILS:raiseif len(ids) == 1:lost.extend(ids)return {}step = SPLIT if len(ids) > SPLIT else 1out: dict = {}for i in range(0, len(ids), step):out.update(await read_ids(client, peer, ids[i : i + step], fails, lost, patient=False, pause=pause))await asyncio.sleep(pause)return outasync def _compare_saved(client, db, ch, rep: SyncReport, opts: SyncOptions, busy, progress, moved=None, pts: Optional[int] = None) -> None:14 unmodified linesby_id = {p.message_id: p for p in judge}ids = sorted(by_id)gone, edits = [], []fails = Fails() # the requests of this look that failed (see read_ids)lost = [] # saved posts Telegram would not hand over: they stay exactly as savedfor i in range(0, len(ids), CHUNK):if busy():rep.busy = Truereturnchunk = ids[i : i + CHUNK]got = await read_ids(client, peer, chunk, fails, lost, pause=opts.pause)for mid, m in got.items():p = by_id[mid]if is_gone(m):gone.append(p)13 unmodified linesif progress:await progress(rep)await asyncio.sleep(opts.pause)if lost:if len(lost) == len(ids): # not a single saved post could be read: Telegram is failing for everythingraise fails.lasthold_back(rep, lost, UNREADABLE_NOTE)edits, held = split_mass_text(edits)if held:hold_back(rep, [p.message_id for p, _ in held], MASS_NOTE)if gone:really = moved is not None and moved >= len(gone) # at least one event for each post that vanishedseen = len(ids) - len(lost) # (a post Telegram would not hand over proves nothing either way)everything = seen >= MIN_FOR_ANOMALY and len(gone) == seenif everything and not really:# No earlier look to compare with (or too few events): is the bot blind, or are the posts really gone? If it# can read other messages of the channel it is not blind.3 unmodified linesreally = await sees_live_messages(client, peer, pts, pause=opts.pause)if everything and not really:rep.anomaly = (f"All {seen} saved posts look deleted, and I can't read any other message of the channel either, ""so none was removed here - check that the bot is still an admin of the channel.")else:125 unmodified lines# ----------------------------------------------------------------------------------------- entry pointsasync def sync_channel(client, db, ch, opts: Optional[SyncOptions] = None, *, busy=None, progress=None) -> SyncReport:"""One full look at a channel (see the module text). Never raises Telegram's refusals or its own trouble (timeouts,internal errors): they end up in `report.error`."""opts = opts or SyncOptions()busy = busy or (lambda: False)rep = SyncReport(channel=ch)14 unmodified linesawait _import_history(client, db, ch, rep, opts, busy, progress, state)except errors.RPCError as e:rep.error = explain_rpc(e)except TelegramStuck as e:rep.error, rep.stuck = stuck_error(e), Truereturn rep53 unmodified linesawait _adopt(db, ch, rep, fresh, opts, busy, now)except errors.RPCError as e:rep.error = explain_rpc(e)except TelegramStuck as e:rep.error, rep.stuck = stuck_error(e), Truereturn rep
14 unmodified lines151617181920212214 unmodified lines3738394041424 unmodified lines47484950515287 unmodified lines14014114214314414525 unmodified lines17117217317417517630 unmodified lines20720820921021121221321491 unmodified lines30630730830931031131231314 unmodified linesimport timefrom typing import Optionalfrom .servicemsg import RIGHTS_ERRORS, action_label, removefrom .sync_engine import SyncOptions, SyncReport, sync_channel, sync_idsfrom .tgutil import esc, peer_oflog = logging.getLogger(__name__)14 unmodified linesself.tell_restricted_every = 7 * 86400.0 # ... a restriction by Telegram can last for weeks: once a weekself.max_ids = 300 # more changed ids than this in one channel: look at the whole channel insteadself.max_tries = 8 # a message that stays "too fresh" is given up after this many roundsself.history_seconds = 150.0 # a timed check reads a channel's older posts for this long, then goes on next timeself._busy = asyncio.Lock() # one look at a timeself._edits: dict = {} # channel id -> message ids edited4 unmodified linesself._tasks: list = []self._cache: dict = {}self._told: dict = {}self.last_reports: dict = {} # channel id -> its latest SyncReport# ----------------------------------------------------------------------------------------- running87 unmodified linesasync def _after(self, ch, rep: SyncReport) -> None:self.last_reports[ch.id] = repif rep.changed or rep.error or rep.anomaly:log.info("channel %s: %s removed, %s updated, %s new, %s service messages deleted%s",25 unmodified lines"Their saved copies in My posts stay exactly as they are.")@staticmethoddef _rights_text(ch, why: Optional[str]) -> str:return (30 unmodified linesexcept asyncio.CancelledError:raiseexcept Exception as e:log.exception("looking at channel %s failed", ch.id)rep = SyncReport(channel=ch, error=f"{type(e).__name__}: {str(e)[:120]}")await self._after(ch, rep)reports.append(rep)return reports91 unmodified linesexcept asyncio.CancelledError:raiseexcept Exception as e:log.exception("looking at the changes in channel %s failed", cid)rep = SyncReport(channel=ch, error=f"{type(e).__name__}: {str(e)[:120]}")await self._after(ch, rep)if rep.busy: # a long job started in the meantime: let the next timed check have itcontinue14 unmodified lines15161718192021222314 unmodified lines383940414243444 unmodified lines4950515253545587 unmodified lines14314414514614714814915015115215315425 unmodified lines18018118218318418518618718818919019119230 unmodified lines22322422522622722822923023123223323491 unmodified lines32632732832933033133233333433533633714 unmodified linesimport timefrom typing import Optionalfrom .replace_engine import is_stuckfrom .servicemsg import RIGHTS_ERRORS, action_label, removefrom .sync_engine import SyncOptions, SyncReport, stuck_error, sync_channel, sync_idsfrom .tgutil import esc, peer_oflog = logging.getLogger(__name__)14 unmodified linesself.tell_restricted_every = 7 * 86400.0 # ... a restriction by Telegram can last for weeks: once a weekself.max_ids = 300 # more changed ids than this in one channel: look at the whole channel insteadself.max_tries = 8 # a message that stays "too fresh" is given up after this many roundsself.stuck_looks = 3 # Telegram failing for this many looks at a channel in a row: the owners are toldself.history_seconds = 150.0 # a timed check reads a channel's older posts for this long, then goes on next timeself._busy = asyncio.Lock() # one look at a timeself._edits: dict = {} # channel id -> message ids edited4 unmodified linesself._tasks: list = []self._cache: dict = {}self._told: dict = {}self._stuck: dict = {} # channel id -> looks in a row that were cut short because Telegram kept failingself.last_reports: dict = {} # channel id -> its latest SyncReport# ----------------------------------------------------------------------------------------- running87 unmodified linesasync def _after(self, ch, rep: SyncReport) -> None:self.last_reports[ch.id] = repif rep.stuck: # Telegram itself keeps failing: one or two looks are a blip, a few in a row are worth tellingself._stuck[ch.id] = self._stuck.get(ch.id, 0) + 1if self._stuck[ch.id] >= self.stuck_looks:await self.tell_owners(ch, "stuck", self._stuck_text(ch))elif not rep.error and not rep.busy:self._stuck.pop(ch.id, None)if rep.changed or rep.error or rep.anomaly:log.info("channel %s: %s removed, %s updated, %s new, %s service messages deleted%s",25 unmodified lines"Their saved copies in My posts stay exactly as they are.")@staticmethoddef _stuck_text(ch) -> str:return (f"⚠️ Telegram keeps failing (timeouts / internal errors) when I read <b>{esc(ch.title)}</b>, so I can't compare ""My posts with it for now. Nothing in My posts was changed; I try again at every check.")@staticmethoddef _rights_text(ch, why: Optional[str]) -> str:return (30 unmodified linesexcept asyncio.CancelledError:raiseexcept Exception as e:if is_stuck(e): # Telegram itself kept failing (not a bug): the next look tries againlog.info("looking at channel %s: Telegram kept failing: %s", ch.id, e)rep = SyncReport(channel=ch, error=stuck_error(e), stuck=True)else:log.exception("looking at channel %s failed", ch.id)rep = SyncReport(channel=ch, error=f"{type(e).__name__}: {str(e)[:120]}")await self._after(ch, rep)reports.append(rep)return reports91 unmodified linesexcept asyncio.CancelledError:raiseexcept Exception as e:if is_stuck(e): # Telegram itself kept failing (not a bug): the next timed check looks at these againlog.info("looking at the changes in channel %s: Telegram kept failing: %s", cid, e)rep = SyncReport(channel=ch, error=stuck_error(e), stuck=True)else:log.exception("looking at the changes in channel %s failed", cid)rep = SyncReport(channel=ch, error=f"{type(e).__name__}: {str(e)[:120]}")await self._after(ch, rep)if rep.busy: # a long job started in the meantime: let the next timed check have itcontinue
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323"""Telegram ITSELF failing (timeouts, internal errors) while the sync reads a channel: the read is repeated, a post Telegramwon't hand over is left exactly as saved (never taken for deleted), and when everything fails the look is given up quietly."""import asyncioimport datetimeimport loggingfrom types import SimpleNamespace
import pytestfrom telethon import errors, types
from app import replace_engine, sync_engine, syncerfrom app.replace_engine import TelegramStuck, fetch_messages, is_stuckfrom app.sync_engine import MAX_FAILS, Fails, SyncOptions, SyncReport, _compare_saved, read_ids, sync_channel, sync_idsfrom 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_messagesdef 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_idsdef 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 comparisondef 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 pointsdef 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 Syncerclass 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].gitattributes+3-3
app/replace_engine.py+32-3
app/sync_engine.py+68-7
app/syncer.py+29-5
tests/test_sync_stuck.pyAdded+323