From 32e290aec1908090608c6f6b75de1dc2a2c888e1 Mon Sep 17 00:00:00 2001 From: Louise Date: Sun, 22 Nov 2026 00:53:22 +0000 Subject: [PATCH] fix(irc): fix concurrent irc searches and downloads failing (#1734) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Searches and downloads share one IRC connection and run side by side, which broke in three ways: - wait_for_dcc took the first search-results file to arrive, so a late file for an earlier query was cached under the current one. It now skips a results file whose name is for a different query. - A download failing on the shared socket closed it under a search in flight. The search then cached an empty answer, hiding the book for a day. Searches and downloads now hold one lock for the whole exchange. - A search that lost its connection returned [] and counted as a no-match pass, pushing the request into backoff. It now raises SourceUnavailableError, which auto-download already treats as an error, and caches nothing. This was written with AI assistance. I reviewed the changes and ran the tests above and verified that this fixed my issues with searching and downloading using IRC. *Generated with Claude Sonnet 5.5* ## Summary by CodeRabbit * **Bug Fixes** * Search results are matched against the requested title, ignoring punctuation and accents while rejecting partial-title matches. Filenames without the usual suffix are also recognized. * Results and “no results” notices from earlier searches are skipped, and denied searches report an error. * Connection drops and DCC read errors are reported as failures rather than empty results or timeouts. * Repeated identical searches are rate-limited before sending, and search time limits apply while waiting for results or downloads. --------- Co-authored-by: Claude Sonnet 5.5 Co-authored-by: CaliBrain --- shelfmark/release_sources/irc/client.py | 87 +++- .../release_sources/irc/connection_manager.py | 4 + shelfmark/release_sources/irc/dcc.py | 4 +- shelfmark/release_sources/irc/handler.py | 30 +- shelfmark/release_sources/irc/source.py | 145 +++++-- tests/irc/test_client_dcc_security.py | 184 +++++++- tests/irc/test_dcc_security.py | 18 + tests/irc/test_handler.py | 63 +++ tests/irc/test_search_query.py | 1 + tests/irc/test_source.py | 409 +++++++++++++++++- 10 files changed, 893 insertions(+), 52 deletions(-) diff --git a/shelfmark/release_sources/irc/client.py b/shelfmark/release_sources/irc/client.py index 8a7bd1de..ad229046 100644 --- a/shelfmark/release_sources/irc/client.py +++ b/shelfmark/release_sources/irc/client.py @@ -7,6 +7,7 @@ import re import socket import ssl import time +import unicodedata from contextlib import suppress from dataclasses import dataclass, field from enum import Enum, auto @@ -40,6 +41,7 @@ class IRCEvent(Enum): SEARCH_RESULT = auto() # DCC SEND with "_results_for" BOOK_RESULT = auto() # DCC SEND for actual book NO_RESULTS = auto() # "Sorry" notice + SEARCH_DENIED = auto() # "Search denied" notice: an earlier results file is unreceived BAD_SERVER = auto() # "try another server" notice SEARCH_ACCEPTED = auto() # "has been accepted" notice MATCHES_FOUND = auto() # "X matches" notice @@ -86,6 +88,39 @@ class IRCConnectionError(IRCError): """Connection failed.""" +def _alnum(value: str) -> str: + # NFKD + dropping combining marks makes "é" equal "e" however the bot encoded it. + decomposed = unicodedata.normalize("NFKD", value.casefold()) + return "".join(c for c in decomposed if c.isalnum() and not unicodedata.combining(c)) + + +def results_file_matches_query(filename: str, query: str) -> bool: + """Return whether a search bot's results file was made for this query. + + The bot names it ``_results_for__.txt.zip``, with punctuation turned into + underscores, so the two are compared on letters and digits only (any script). They must + be equal: a prefix match would take the results for "Emma Austen" as the answer to + "Emma". A name without ``_results_for`` is accepted: its naming is + unknown, so there is nothing to compare against. + """ + _, found, rest = filename.partition("_results_for") + if not found: + return True + got = _alnum(re.sub(r"(\.(txt|zip|rar|7z))+$", "", rest, flags=re.IGNORECASE)) + # The bot turns a non-ASCII letter into "_" ("Les_Mis_rables"), so also try without them. + ascii_only = query.encode("ascii", "ignore").decode() + return bool(got) and got in {_alnum(query), _alnum(ascii_only)} + + +_IRC_FORMATTING = re.compile(r"\x03(\d{1,2}(,\d{1,2})?)?|[\x02\x0f\x16\x1d\x1f]") + + +def notice_query(text: str) -> str | None: + """The query a search bot's notice names: ``... your search for "" ...``.""" + match = re.search(r'search for "([^"]*)"', _IRC_FORMATTING.sub("", text)) + return match.group(1) if match else None + + class IRCClient: """Minimal IRC client for per-request IRC release searches.""" @@ -117,6 +152,11 @@ class IRCClient: self._socket: socket.socket | None = None self._buffer = "" self._connected = False + # Queries whose wait timed out: a late answer to one of them may still arrive. + self._stale_queries: set[str] = set() + # Whether the last wait_for_dcc returned None because its timeout ran out, + # rather than on an answer such as a "Sorry" notice. + self.last_wait_timed_out = False # Track online servers (elevated users in channel) self.online_servers: set[str] = set() @@ -364,12 +404,14 @@ class IRCClient: try: data = sock.recv(RECV_BUFFER) if not data: + self._connected = False return # Connection closed self._buffer += data.decode("utf-8", errors="replace") except TimeoutError: continue # Keep waiting (the deadline is re-checked above) except OSError as e: logger.warning("Socket error: %s", e) + self._connected = False return # Connection error finally: if deadline is not None: @@ -420,6 +462,8 @@ class IRCClient: # NOTICE messages if msg.command == "NOTICE" or "NOTICE" in raw: + if "Search denied" in trailing: + return IRCEvent.SEARCH_DENIED if "Sorry" in trailing: return IRCEvent.NO_RESULTS if "try another server" in trailing: @@ -513,10 +557,18 @@ class IRCClient: *, result_type: bool = False, expected_senders: set[str] | None = None, + expected_query: str | None = None, ) -> DCCOffer | None: - """Wait for a DCC SEND offer. Returns None on timeout or no results.""" + """Wait for a DCC SEND offer. Returns None on timeout or no results. + + With ``expected_query``, a results file or "Sorry" notice that belongs to an earlier + query whose wait timed out is skipped, so a late answer is not cached under this + one. Anything else is accepted: the bot's naming is not known well enough to + reject a file on a mismatch alone. + """ target_event = IRCEvent.SEARCH_RESULT if result_type else IRCEvent.BOOK_RESULT deadline = time.time() + timeout + self.last_wait_timed_out = False for msg in self.read_messages(deadline=deadline): if msg.event == target_event: @@ -529,11 +581,37 @@ class IRCClient: except DCCError: logger.exception("Rejected DCC offer") continue - else: - return offer + if ( + result_type + and expected_query + and not results_file_matches_query(offer.filename, expected_query) + and any( + results_file_matches_query(offer.filename, q) for q in self._stale_queries + ) + ): + logger.warning( + "Ignoring results file for another query: %s (waiting for %r)", + offer.filename, + expected_query, + ) + continue + return offer # Log other events for debugging + if msg.event == IRCEvent.SEARCH_DENIED and result_type: + # The bot refused to search at all, so this is not "no results". + raise IRCError(_IRC_FORMATTING.sub("", msg.trailing or "Search denied")) if msg.event == IRCEvent.NO_RESULTS: + named = notice_query(msg.trailing or "") + if ( + result_type + and expected_query + and named is not None + and _alnum(named) != _alnum(expected_query) + and any(_alnum(named) == _alnum(q) for q in self._stale_queries) + ): + logger.warning("Ignoring a late no-results notice for another query") + continue logger.info("Server reports no results") return None if msg.event == IRCEvent.BAD_SERVER: @@ -552,6 +630,9 @@ class IRCClient: if time.time() >= deadline: logger.warning("Timeout waiting for DCC offer") + self.last_wait_timed_out = True + if result_type and expected_query: + self._stale_queries.add(expected_query) return None @property diff --git a/shelfmark/release_sources/irc/connection_manager.py b/shelfmark/release_sources/irc/connection_manager.py index 4c709e2a..58f7e424 100644 --- a/shelfmark/release_sources/irc/connection_manager.py +++ b/shelfmark/release_sources/irc/connection_manager.py @@ -49,6 +49,10 @@ class IRCConnectionManager: self._channels: dict[str, str] = {} # connection_key -> joined channel self._connecting: dict[str, bool] = {} # Track keys currently being connected self._conn_lock = threading.Lock() + # Searches and downloads share one socket. Two readers on it take each other's + # replies, and a failure in one closes it under the other, so a search or a + # download holds this for its whole exchange. + self.io_lock = threading.Lock() self._cleanup_thread: threading.Thread | None = None self._running = True self._initialized = True diff --git a/shelfmark/release_sources/irc/dcc.py b/shelfmark/release_sources/irc/dcc.py index d8e2002a..7ff6d52f 100644 --- a/shelfmark/release_sources/irc/dcc.py +++ b/shelfmark/release_sources/irc/dcc.py @@ -162,8 +162,8 @@ def download_dcc( # Read chunk try: chunk = sock.recv(BUFFER_SIZE) - except TimeoutError as e: - msg = f"Timeout reading from {offer.ip}:{offer.port}" + except OSError as e: # timeouts and resets alike: the DCC peer, not IRC + msg = f"Failed reading from {offer.ip}:{offer.port}: {e}" raise DCCError(msg) from e if not chunk: diff --git a/shelfmark/release_sources/irc/handler.py b/shelfmark/release_sources/irc/handler.py index 1e54ba1f..f0267ae5 100644 --- a/shelfmark/release_sources/irc/handler.py +++ b/shelfmark/release_sources/irc/handler.py @@ -111,6 +111,8 @@ class IRCDownloadHandler(DownloadHandler): status_callback("cancelled", "Cancelled") return True + lock_held = True + connection_manager.io_lock.acquire() try: # Phase 1: Get or reuse IRC connection status_callback("resolving", f"Connecting to {server}") @@ -138,15 +140,24 @@ class IRCDownloadHandler(DownloadHandler): # Phase 3: Wait for DCC offer status_callback("resolving", "Waiting for bot response") - wait_kwargs = {"expected_senders": {expected_server}} if expected_server else {} - offer = client.wait_for_dcc(timeout=120.0, result_type=False, **wait_kwargs) + offer = client.wait_for_dcc( + timeout=120.0, + result_type=False, + expected_senders={expected_server} if expected_server else None, + ) if not offer: status_callback("error", "No response from bot") connection_manager.release_connection(client) return None - if check_cancelled(): + # The transfer runs on its own DCC socket, so the IRC connection is free again. + connection_manager.release_connection(client) + connection_manager.io_lock.release() + lock_held = False + + if cancel_flag.is_set(): + status_callback("cancelled", "Cancelled") return None # Phase 4: Download via DCC @@ -170,9 +181,6 @@ class IRCDownloadHandler(DownloadHandler): timeout=60.0, ) - # Release connection for reuse (don't close it) - connection_manager.release_connection(client) - if cancel_flag.is_set(): # Clean up partial download staging_path.unlink(missing_ok=True) @@ -183,19 +191,23 @@ class IRCDownloadHandler(DownloadHandler): return str(staging_path) except DCCError as e: + # The DCC socket failed, not the IRC one. logger.exception("DCC error") status_callback("error", str(e)) - if client: - connection_manager.close_connection(client) return None except Exception as e: logger.exception("Download failed") status_callback("error", f"Download failed: {e}") - if client: + # Only drop a connection we still own; after the offer it was already released. + if client and lock_held: connection_manager.close_connection(client) return None + finally: + if lock_held: + connection_manager.io_lock.release() + def cancel(self, task_id: str) -> bool: """Cancel an in-progress download (cleanup if cancel_flag fails).""" logger.debug("Cancel requested for IRC task: %s", task_id) diff --git a/shelfmark/release_sources/irc/source.py b/shelfmark/release_sources/irc/source.py index 760e5f7e..0e504090 100644 --- a/shelfmark/release_sources/irc/source.py +++ b/shelfmark/release_sources/irc/source.py @@ -6,13 +6,14 @@ Searches IRC channels for ebook and audiobook releases. import tempfile import time from pathlib import Path -from typing import TYPE_CHECKING, ClassVar +from typing import TYPE_CHECKING, ClassVar, NoReturn if TYPE_CHECKING: from shelfmark.core.search_plan import ReleaseSearchPlan from shelfmark.metadata_providers import BookMetadata from shelfmark.api.websocket import ws_manager +from shelfmark.core import search_deadline from shelfmark.core.author_match import author_affinity, search_surname from shelfmark.core.config import config from shelfmark.core.logger import setup_logger @@ -28,10 +29,11 @@ from shelfmark.release_sources import ( ReleaseProtocol, ReleaseSource, SourceActionButton, + SourceUnavailableError, register_source, ) -from .client import bare_channel_name, has_control_characters +from .client import IRCError, bare_channel_name, has_control_characters from .connection_manager import connection_manager from .dcc import DCCError, download_dcc, safe_dcc_filename from .parser import SearchResult, extract_results_from_zip, parse_results_file @@ -120,6 +122,36 @@ IDENTICAL_SEND_WINDOW_SECONDS = 24 * 60 * 60 # 24 hours _recent_message_sends: dict[str, list[float]] = {} +def _raise_connection_dropped() -> NoReturn: + msg = "IRC connection dropped during the search" + raise SourceUnavailableError(msg) + + +def _deadline_left() -> float | None: + """Seconds the search deadline has left, or None outside a search.""" + deadline = search_deadline.current() + return deadline.remaining if deadline else None + + +def _raise_out_of_time() -> NoReturn: + msg = "The IRC search ran out of time; try again shortly" + raise SourceUnavailableError(msg) + + +def _within_deadline(seconds: float) -> float: + """``seconds``, cut to what the search deadline has left. Raises once it is spent. + + The API waits on the search, so a phase that outlives the deadline turns into a + gateway timeout for the user. + """ + left = _deadline_left() + if left is None: + return seconds + if left < 1.0: # too little left to start another phase + _raise_out_of_time() + return min(seconds, left) + + def _enforce_rate_limit() -> None: """Ensure minimum time between searches.""" global _last_search_time @@ -306,33 +338,47 @@ class IRCReleaseSource(ReleaseSource): self._filter_by_content_type(cached["releases"], requested), wanted_author ) - # Anti-spam cap: the exact same query may only be POSTED a limited number of times - # per window, even via refresh. Beyond that, serve whatever is cached rather than - # re-posting the identical message to the channel. - if _recent_send_count(query_key) >= MAX_IDENTICAL_SENDS: - logger.info( - "IRC query hit %s-send limit in window, not re-posting: %s", - MAX_IDENTICAL_SENDS, - query, - ) - _emit_status( - "Search limit reached for this query — showing latest results", phase="complete" - ) - cached = get_cached_results(query_key) - if cached: - self._online_servers = set(cached.get("online_servers", [])) - return self._rank_by_author( - self._filter_by_content_type(cached["releases"], requested), wanted_author - ) - return [] - - logger.info("IRC search: %s", query) - - # Enforce rate limit - _enforce_rate_limit() - client = None + if not connection_manager.io_lock.acquire(blocking=False): + _emit_status("Waiting for the IRC connection...", phase="searching") + deadline = search_deadline.current() + timeout = deadline.remaining if deadline else 180.0 + if not connection_manager.io_lock.acquire(timeout=timeout): + msg = "IRC is busy, try again shortly" + raise SourceUnavailableError(msg) try: + # An identical search queued ahead of us may have just cached the answer. + if not expand_search: + cached = get_cached_results(query_key) + if cached: + _emit_status("Using cached results", phase="complete") + self._online_servers = set(cached.get("online_servers", [])) + return self._rank_by_author( + self._filter_by_content_type(cached["releases"], requested), wanted_author + ) + + # Anti-spam cap: the exact same query may only be POSTED a limited number of times + # per window, even via refresh. Beyond that, serve whatever is cached rather than + # re-posting the identical message to the channel. + if _recent_send_count(query_key) >= MAX_IDENTICAL_SENDS: + logger.info( + "IRC query hit %s-send limit in window, not re-posting: %s", + MAX_IDENTICAL_SENDS, + query, + ) + _emit_status( + "Search limit reached for this query — showing latest results", phase="complete" + ) + cached = get_cached_results(query_key) + if cached: + self._online_servers = set(cached.get("online_servers", [])) + return self._rank_by_author( + self._filter_by_content_type(cached["releases"], requested), wanted_author + ) + return [] + + logger.info("IRC search: %s", query) + # Get or reuse IRC connection _emit_status(f"Connecting to {server}...", phase="connecting") client = connection_manager.get_connection( @@ -346,6 +392,10 @@ class IRCReleaseSource(ReleaseSource): # Capture online servers (elevated users in channel) self._online_servers = client.online_servers + # Space real sends, not lock-queue entries (the lock may have been held a while). + _enforce_rate_limit() + wait_timeout = _within_deadline(60.0) # nothing is sent once the time is spent + # Send search request (always addressed to the search bot, never bare) client.send_message(f"#{channel}", f"@{search_bot} {query}") _record_message_sent(query_key) @@ -355,10 +405,26 @@ class IRCReleaseSource(ReleaseSource): # "@search" from a differently-named results bot. The DCC endpoint/filename are # still validated, and wait_for_dcc falls back to the channel's server list. _emit_status(f"Connected to #{channel} - Waiting for results...", phase="searching") - offer = client.wait_for_dcc(timeout=60.0, result_type=True) + offer = client.wait_for_dcc( + timeout=wait_timeout, result_type=True, expected_query=query + ) online_servers = list(self._online_servers) if self._online_servers else None + if not offer and not client.is_connected: + # The server dropped the link mid-search. That says nothing about the + # book, so it is neither cached as "no results" nor counted as one; the + # request is searched again on the next pass. + connection_manager.close_connection(client) + _raise_connection_dropped() + + if not offer and wait_timeout < 60.0 and client.last_wait_timed_out: + # The deadline cut the wait short and the bot may still answer, so this is + # not "no results". The client marks the query timed out, so a late answer + # is skipped by the next search. + connection_manager.release_connection(client) + _raise_out_of_time() + if not offer: logger.info("No search results received") _emit_status("No results found", phase="complete") @@ -373,7 +439,7 @@ class IRCReleaseSource(ReleaseSource): _emit_status(f"Connected to #{channel} - Downloading results...", phase="downloading") with tempfile.TemporaryDirectory() as tmpdir: result_path = Path(tmpdir) / safe_dcc_filename(offer.filename) - download_dcc(offer, result_path, timeout=30.0) + download_dcc(offer, result_path, timeout=_within_deadline(30.0)) # Parse results if result_path.suffix.lower() == ".zip": @@ -406,12 +472,22 @@ class IRCReleaseSource(ReleaseSource): audiobook_releases if requested == "audiobook" else ebook_releases, wanted_author ) - except DCCError as e: - logger.exception("DCC error during search") - _emit_status(f"DCC error: {e}", phase="error") + except SourceUnavailableError: + raise + except (IRCError, OSError) as e: + logger.warning("IRC search failed: %s", e) if client: connection_manager.close_connection(client) - return [] + msg = f"IRC search unavailable: {e}" + raise SourceUnavailableError(msg) from e + except DCCError as e: + # The results transfer failed, which says nothing about the book. The DCC + # socket failed, not the IRC one, so the connection is handed back. + logger.warning("DCC error during search: %s", e) + if client: + connection_manager.release_connection(client) + msg = f"IRC results transfer failed: {e}" + raise SourceUnavailableError(msg) from e except Exception as e: logger.exception("IRC search failed") _emit_status(f"Search failed: {e}", phase="error") @@ -422,6 +498,9 @@ class IRCReleaseSource(ReleaseSource): else: return releases + finally: + connection_manager.io_lock.release() + def _build_query(self, book: BookMetadata, plan: ReleaseSearchPlan) -> str: """Build the line posted to the channel: a title, plus a surname. diff --git a/tests/irc/test_client_dcc_security.py b/tests/irc/test_client_dcc_security.py index 316f70a6..8fc2f3b1 100644 --- a/tests/irc/test_client_dcc_security.py +++ b/tests/irc/test_client_dcc_security.py @@ -1,6 +1,12 @@ from ipaddress import IPv4Address -from shelfmark.release_sources.irc.client import IRCClient, IRCEvent, IRCMessage +from shelfmark.release_sources.irc.client import ( + IRCClient, + IRCEvent, + IRCMessage, + notice_query, + results_file_matches_query, +) def _dcc_raw(sender: str, filename: str, ip: str, port: int = 443) -> str: @@ -82,3 +88,179 @@ def test_wait_for_dcc_ignores_unsafe_offer_and_keeps_waiting(monkeypatch) -> Non assert offer is not None assert offer.filename == "book.epub" + + +def _results_offer(filename: str) -> IRCMessage: + return IRCMessage( + raw=_dcc_raw("SearchBot", filename, "8.8.8.8"), + prefix="SearchBot!user@example.test", + event=IRCEvent.SEARCH_RESULT, + ) + + +def test_wait_for_dcc_skips_a_results_file_made_for_another_query(monkeypatch) -> None: + """A late file for an earlier search must not be taken as this search's answer.""" + client = IRCClient(nick="reader", server="irc.example.test", port=6697) + client.online_servers = {"SearchBot"} + client._stale_queries.add("Anne of Green Gables Montgomery") # its wait timed out + messages = [ + _results_offer("SearchBot_results_for__Anne_of_Green_Gables_Montgomery.txt.zip"), + _results_offer("SearchBot_results_for__Anne_of_Avonlea_Montgomery.txt.zip"), + ] + monkeypatch.setattr(client, "read_messages", lambda **_: iter(messages)) + + offer = client.wait_for_dcc( + timeout=1.0, + result_type=True, + expected_query="Anne of Avonlea Montgomery", + ) + + assert offer is not None + assert "Avonlea" in offer.filename + + +def test_wait_for_dcc_accepts_a_results_file_named_differently_from_the_query(monkeypatch) -> None: + """An accent the bot dropped or replaced is not a late answer to anything.""" + client = IRCClient(nick="reader", server="irc.example.test", port=6697) + client.online_servers = {"SearchBot"} + messages = [_results_offer("SearchBot_results_for__Les_Mis_rables_Hugo.txt.zip")] + monkeypatch.setattr(client, "read_messages", lambda **_: iter(messages)) + + offer = client.wait_for_dcc(timeout=1.0, result_type=True, expected_query="Les Misérables Hugo") + + assert offer is not None + + +def test_wait_for_dcc_skips_a_late_no_results_notice_for_an_earlier_query(monkeypatch) -> None: + client = IRCClient(nick="reader", server="irc.example.test", port=6697) + client.online_servers = {"SearchBot"} + client._stale_queries.add("Old Title") + messages = [ + IRCMessage( + raw="", + prefix="SearchBot!x@y", + command="NOTICE", + params=["reader"], + trailing='\x031,9\x02<>\x02 Sorry, your search for "\x0312,09Old Title\x0301,09" returned \x02no\x02 matches.', + event=IRCEvent.NO_RESULTS, + ), + _results_offer("SearchBot_results_for__New_Title.txt.zip"), + ] + monkeypatch.setattr(client, "read_messages", lambda **_: iter(messages)) + + offer = client.wait_for_dcc(timeout=1.0, result_type=True, expected_query="New Title") + + assert offer is not None + + +def test_wait_for_dcc_skips_a_late_notice_for_a_query_containing_this_one(monkeypatch) -> None: + """A late "Sorry" for "Emma Austen" is not the answer to "Emma", though one contains the other.""" + client = IRCClient(nick="reader", server="irc.example.test", port=6697) + client.online_servers = {"SearchBot"} + client._stale_queries.add("Emma Austen") + messages = [ + IRCMessage( + raw="", + prefix="SearchBot!x@y", + command="NOTICE", + params=["reader"], + trailing='Sorry, your search for "\x0312,09Emma Austen\x0301,09" returned no matches.', + event=IRCEvent.NO_RESULTS, + ), + _results_offer("SearchBot_results_for__Emma.txt.zip"), + ] + monkeypatch.setattr(client, "read_messages", lambda **_: iter(messages)) + + offer = client.wait_for_dcc(timeout=1.0, result_type=True, expected_query="Emma") + + assert offer is not None + + +def test_wait_for_dcc_raises_when_the_bot_denies_the_search(monkeypatch) -> None: + """A denied search was never run, so it must not come back as "no results".""" + import pytest + + from shelfmark.release_sources.irc.client import IRCError + + client = IRCClient(nick="reader", server="irc.example.test", port=6697) + denied = IRCMessage( + raw=":Search!Search@host NOTICE reader :x", + prefix="Search!Search@host", + command="NOTICE", + params=["reader"], + # Seen on irchighway, typo included. + trailing="Search results already waiting to be recieved. Search denied.", + ) + denied.event = client._classify_event(denied) + monkeypatch.setattr(client, "read_messages", lambda **_: iter([denied])) + + with pytest.raises(IRCError, match="Search denied"): + client.wait_for_dcc(timeout=1.0, result_type=True, expected_query="Q") + + +def test_notice_query_reads_the_query_through_colour_codes() -> None: + real = ( + "\x031,9\x16\x02<>\x02\x16 Sorry, your search for " + '"\x0312,091984 Orwell\x0301,09" returned \x02no\x02 matches. Search took 1.25 seconds.' + ) + assert notice_query(real) == "1984 Orwell" + assert notice_query("Sorry, the bot is busy") is None + + +def test_wait_for_dcc_timeout_marks_the_query_stale(monkeypatch) -> None: + client = IRCClient(nick="reader", server="irc.example.test", port=6697) + monkeypatch.setattr(client, "read_messages", lambda **_: iter([])) + + assert client.wait_for_dcc(timeout=0, result_type=True, expected_query="Q") is None + assert client.last_wait_timed_out + assert "Q" in client._stale_queries + + +def test_wait_for_dcc_without_an_expected_query_takes_the_first_results_file(monkeypatch) -> None: + client = IRCClient(nick="reader", server="irc.example.test", port=6697) + client.online_servers = {"SearchBot"} + messages = [_results_offer("SearchBot_results_for__Anything.txt.zip")] + monkeypatch.setattr(client, "read_messages", lambda **_: iter(messages)) + + offer = client.wait_for_dcc(timeout=1.0, result_type=True) + + assert offer is not None + + +def test_results_file_matches_query() -> None: + def name(query: str) -> str: + return f"SearchBot_results_for__{query.replace(' ', '_')}.txt.zip" + + short = "The Secret Garden Burnett" + long = "The Secret Garden: Centenary Edition Burnett" + assert results_file_matches_query(name(short), short) + assert results_file_matches_query(name(long), long) # punctuation does not matter + assert not results_file_matches_query(name(short), long) + assert not results_file_matches_query(name(long), short) + # Results for a longer title are not the answer to a search for its start. + assert not results_file_matches_query(name("Emma Austen"), "Emma") + assert results_file_matches_query(name("三体"), "三体") # any script + # A name that is not a results file has nothing to compare against. + assert results_file_matches_query("Author - Book.epub", short) + assert results_file_matches_query(name("Les Miserables Hugo"), "Les Misérables Hugo") + # The real bot's name for this query, seen on irchighway. + assert results_file_matches_query( + "SearchBot_results_for__Les_Mis_rables_Hugo.txt.zip", "Les Misérables Hugo" + ) + assert results_file_matches_query(name("Les Mise\u0301rables Hugo"), "Les Misérables Hugo") + + +def test_recv_lines_marks_the_client_disconnected_when_the_peer_closes() -> None: + class ClosedSocket: + def gettimeout(self) -> None: + return None + + def recv(self, _size: int) -> bytes: + return b"" + + client = IRCClient(nick="reader", server="irc.example.test", port=6697) + client._socket = ClosedSocket() # type: ignore[assignment] + client._connected = True + + assert list(client._recv_lines()) == [] + assert not client.is_connected diff --git a/tests/irc/test_dcc_security.py b/tests/irc/test_dcc_security.py index 250955a4..41b50522 100644 --- a/tests/irc/test_dcc_security.py +++ b/tests/irc/test_dcc_security.py @@ -80,3 +80,21 @@ def test_download_dcc_rejects_private_endpoint_before_socket_connect( DCCOffer(filename="book.epub", ip="127.0.0.1", port=1234, size=1), tmp_path / "book.epub", ) + + +def test_download_dcc_turns_a_reset_mid_transfer_into_a_dcc_error(monkeypatch, tmp_path) -> None: + """A reset on the DCC socket must not look like the IRC connection failing.""" + from shelfmark.release_sources.irc.dcc import DCCError + + class ResetSocket: + def settimeout(self, _t: float) -> None: ... + def connect(self, _addr: object) -> None: ... + def close(self) -> None: ... + def recv(self, _n: int) -> bytes: + raise ConnectionResetError + + monkeypatch.setattr(socket, "socket", lambda *_a: ResetSocket()) + offer = DCCOffer(filename="a.epub", ip="8.8.8.8", port=443, size=10) + + with pytest.raises(DCCError): + download_dcc(offer, tmp_path / "a.epub", timeout=1.0) diff --git a/tests/irc/test_handler.py b/tests/irc/test_handler.py index c010e0cd..d4b1b1e5 100644 --- a/tests/irc/test_handler.py +++ b/tests/irc/test_handler.py @@ -25,3 +25,66 @@ def test_download_with_hash_prefixed_channel_setting_uses_the_bare_channel(monke assert manager.get_connection.call_args.kwargs["channel"] == "ebooks" client.send_message.assert_called_once_with("#ebooks", "!bot Author - Title.epub") + + +def test_download_holds_the_connection_lock_while_requesting_the_file(monkeypatch): + """A search and a download on one socket steal each other's replies, so they take turns.""" + from shelfmark.release_sources.irc.connection_manager import connection_manager + + held: list[bool] = [] + client = MagicMock() + client.wait_for_dcc.return_value = None + + def get_connection(**_kwargs): + held.append(connection_manager.io_lock.locked()) + return client + + monkeypatch.setattr(connection_manager, "get_connection", get_connection) + monkeypatch.setattr(connection_manager, "release_connection", lambda _client: None) + values = {"IRC_SERVER": "irc.example.test", "IRC_CHANNEL": "ebooks", "IRC_NICK": "reader"} + monkeypatch.setattr(irc_handler.config, "get", lambda key, default="": values.get(key, default)) + task = DownloadTask(task_id="!bot Author - Title.epub", source="irc", title="t") + + irc_handler.IRCDownloadHandler().download(task, Event(), lambda _p: None, lambda _s, _m: None) + + assert held == [True] + assert not connection_manager.io_lock.locked() + + +def test_download_releases_the_connection_lock_when_it_fails(monkeypatch): + from shelfmark.release_sources.irc.connection_manager import connection_manager + + def get_connection(**_kwargs): + msg = "connection refused" + raise OSError(msg) + + monkeypatch.setattr(connection_manager, "get_connection", get_connection) + values = {"IRC_SERVER": "irc.example.test", "IRC_CHANNEL": "ebooks", "IRC_NICK": "reader"} + monkeypatch.setattr(irc_handler.config, "get", lambda key, default="": values.get(key, default)) + task = DownloadTask(task_id="!bot Author - Title.epub", source="irc", title="t") + + irc_handler.IRCDownloadHandler().download(task, Event(), lambda _p: None, lambda _s, _m: None) + + assert not connection_manager.io_lock.locked() + + +def test_download_frees_the_connection_lock_before_the_transfer(monkeypatch): + from shelfmark.release_sources.irc.connection_manager import connection_manager + + held: list[bool] = [] + client = MagicMock() + offer = MagicMock(filename="Book.epub") + client.wait_for_dcc.return_value = offer + monkeypatch.setattr(connection_manager, "get_connection", lambda **_: client) + monkeypatch.setattr(connection_manager, "release_connection", lambda _c: None) + monkeypatch.setattr( + irc_handler, "download_dcc", lambda **_: held.append(connection_manager.io_lock.locked()) + ) + values = {"IRC_SERVER": "irc.example.test", "IRC_CHANNEL": "ebooks", "IRC_NICK": "reader"} + monkeypatch.setattr(irc_handler.config, "get", lambda key, default="": values.get(key, default)) + task = DownloadTask(task_id="!bot Author - Title.epub", source="irc", title="t") + + irc_handler.IRCDownloadHandler().download(task, Event(), lambda _p: None, lambda _s, _m: None) + + assert held == [False] + assert not connection_manager.io_lock.locked() diff --git a/tests/irc/test_search_query.py b/tests/irc/test_search_query.py index 4a1458f8..e4f08513 100644 --- a/tests/irc/test_search_query.py +++ b/tests/irc/test_search_query.py @@ -160,6 +160,7 @@ def test_search_posts_the_surname_and_ranks_the_cached_answer(monkeypatch): sent: list[str] = [] class FakeClient: + is_connected = True online_servers: set[str] = {"OnlineBot"} def send_message(self, _channel: str, message: str) -> None: diff --git a/tests/irc/test_source.py b/tests/irc/test_source.py index 6b4f78ed..c58a2319 100644 --- a/tests/irc/test_source.py +++ b/tests/irc/test_source.py @@ -101,6 +101,7 @@ def test_search_no_dcc_offer_releases_connection_and_caches_empty_result(monkeyp released_clients: list[object] = [] class FakeClient: + is_connected = True online_servers = {"AudioBot"} def send_message(self, channel: str, message: str) -> None: @@ -108,7 +109,12 @@ def test_search_no_dcc_offer_releases_connection_and_caches_empty_result(monkeyp self.message = message def wait_for_dcc( - self, *, timeout: float, result_type: bool, expected_senders: object = None + self, + *, + timeout: float, + result_type: bool, + expected_senders: object = None, + expected_query: object = None, ) -> None: return None @@ -182,6 +188,7 @@ def test_audiobook_search_routes_to_configured_audiobook_channel_and_bot(monkeyp cache_calls: list[dict[str, object]] = [] class FakeClient: + is_connected = True online_servers: set[str] = set() def send_message(self, channel: str, message: str) -> None: @@ -189,7 +196,12 @@ def test_audiobook_search_routes_to_configured_audiobook_channel_and_bot(monkeyp self.message = message def wait_for_dcc( - self, *, timeout: float, result_type: bool, expected_senders: object = None + self, + *, + timeout: float, + result_type: bool, + expected_senders: object = None, + expected_query: object = None, ) -> None: return None @@ -256,6 +268,7 @@ def test_audiobook_search_reuses_main_bot_when_only_channel_configured(monkeypat source = IRCReleaseSource() class FakeClient: + is_connected = True online_servers: set[str] = set() def send_message(self, channel: str, message: str) -> None: @@ -263,7 +276,12 @@ def test_audiobook_search_reuses_main_bot_when_only_channel_configured(monkeypat self.message = message def wait_for_dcc( - self, *, timeout: float, result_type: bool, expected_senders: object = None + self, + *, + timeout: float, + result_type: bool, + expected_senders: object = None, + expected_query: object = None, ) -> None: return None @@ -430,6 +448,7 @@ def _search_once(monkeypatch, settings: dict[str, str], content_type: str = "ebo cache_keys: list[str] = [] class FakeClient: + is_connected = True online_servers: set[str] = set() def send_message(self, channel: str, message: str) -> None: @@ -437,7 +456,12 @@ def _search_once(monkeypatch, settings: dict[str, str], content_type: str = "ebo self.message = message def wait_for_dcc( - self, *, timeout: float, result_type: bool, expected_senders: object = None + self, + *, + timeout: float, + result_type: bool, + expected_senders: object = None, + expected_query: object = None, ) -> None: return None @@ -505,3 +529,380 @@ def test_audiobook_channel_setting_with_hash_prefix_joins_the_same_channel(monke assert prefixed == bare assert prefixed == ("bookz", "#bookz", ["irc.example.net:bookz:some book"]) + + +def _configured_search(monkeypatch, client): + """Wire a search to a fake client, with nothing cached and nothing recorded.""" + import shelfmark.release_sources.irc.source as irc_source + + cache_calls: list[object] = [] + monkeypatch.setattr( + irc_source, + "_config_text", + lambda key: { + "IRC_SERVER": "irc.example.net", + "IRC_CHANNEL": "ebooks", + "IRC_NICK": "tester", + "IRC_SEARCH_BOT": "search", + }.get(key, ""), + ) + irc_source._recent_message_sends.clear() + monkeypatch.setattr(irc_source, "_enforce_rate_limit", lambda: None) + monkeypatch.setattr(irc_source, "_emit_status", lambda *_args, **_kwargs: None) + monkeypatch.setattr( + "shelfmark.release_sources.irc.cache.get_cached_results", lambda *_a, **_k: None + ) + monkeypatch.setattr( + "shelfmark.release_sources.irc.cache.cache_results", + lambda *args, **_kwargs: cache_calls.append(args), + ) + manager = "shelfmark.release_sources.irc.connection_manager.connection_manager" + monkeypatch.setattr(f"{manager}.get_connection", lambda **_kwargs: client) + monkeypatch.setattr(f"{manager}.release_connection", lambda _client: None) + monkeypatch.setattr(f"{manager}.close_connection", lambda _client: None) + return cache_calls + + +def test_search_waits_for_a_results_file_named_for_its_own_query(monkeypatch): + waits: list[object] = [] + + class FakeClient: + is_connected = True + online_servers = {"AudioBot"} + + def send_message(self, channel: str, message: str) -> None: + pass + + def wait_for_dcc(self, **kwargs: object) -> None: + waits.append(kwargs.get("expected_query")) + + source = IRCReleaseSource() + monkeypatch.setattr(source, "is_available", lambda: True) + _configured_search(monkeypatch, FakeClient()) + + source.search( + BookMetadata(provider="hardcover", provider_id="a", title="Some Title"), _plan("Some Title") + ) + + assert waits == ["Some Title"] + + +def test_search_on_a_dropped_connection_is_an_error_and_is_not_cached(monkeypatch): + """The server dropping the link mid-search is not "no results". + + Cached as an empty answer it hid the book for a day, and returned as an empty list it + counted towards the request's search backoff. + """ + import pytest + + from shelfmark.release_sources import SourceUnavailableError + + class FakeClient: + is_connected = False + online_servers = {"AudioBot"} + + def send_message(self, channel: str, message: str) -> None: + pass + + def wait_for_dcc(self, **_kwargs: object) -> None: + return None + + source = IRCReleaseSource() + monkeypatch.setattr(source, "is_available", lambda: True) + cache_calls = _configured_search(monkeypatch, FakeClient()) + closed: list[object] = [] + monkeypatch.setattr( + "shelfmark.release_sources.irc.connection_manager.connection_manager.close_connection", + closed.append, + ) + + with pytest.raises(SourceUnavailableError): + source.search( + BookMetadata(provider="hardcover", provider_id="a", title="Some Title"), + _plan("Some Title"), + ) + + assert cache_calls == [] + assert len(closed) == 1 # the dead client is not handed out again + + +def test_identical_searches_queued_on_the_lock_post_the_query_only_once(monkeypatch): + """The send budget is checked once the lock is held, not before waiting for it.""" + import threading + + import shelfmark.release_sources.irc.source as irc_source + + first_waiting = threading.Event() + release_first = threading.Event() + sent: list[str] = [] + + class FakeClient: + is_connected = True + online_servers = {"AudioBot"} + + def send_message(self, channel: str, message: str) -> None: + sent.append(message) + + def wait_for_dcc(self, **_kwargs: object) -> None: + return None + + client = FakeClient() + _configured_search(monkeypatch, client) + + def slow_get_connection(**_kwargs: object) -> FakeClient: + first_waiting.set() # holding the lock, nothing sent yet + release_first.wait(5) + return client + + monkeypatch.setattr( + "shelfmark.release_sources.irc.connection_manager.connection_manager.get_connection", + slow_get_connection, + ) + monkeypatch.setattr(irc_source, "MAX_IDENTICAL_SENDS", 1) + book = BookMetadata(provider="hardcover", provider_id="a", title="Some Title") + + def run() -> None: + IRCReleaseSource().search(book, _plan("Some Title")) + + first = threading.Thread(target=run) + first.start() + assert first_waiting.wait(5) + second = threading.Thread(target=run) + second.start() + time.sleep(0.2) # let it pass the pre-lock budget check and queue on the lock + release_first.set() + first.join(5) + second.join(5) + + assert not first.is_alive() + assert not second.is_alive() # a lock that was never released would leave it blocked + assert len(sent) == 1 + + +def test_search_gives_up_waiting_for_a_busy_connection_at_the_deadline(monkeypatch): + import pytest + + from shelfmark.core import search_deadline + from shelfmark.release_sources import SourceUnavailableError + from shelfmark.release_sources.irc.connection_manager import connection_manager + + _configured_search(monkeypatch, object()) + source = IRCReleaseSource() + monkeypatch.setattr(source, "is_available", lambda: True) + book = BookMetadata(provider="hardcover", provider_id="a", title="Some Title") + + connection_manager.io_lock.acquire() # a download is mid-request + try: + started = time.monotonic() + with search_deadline.search_deadline(0.3), pytest.raises(SourceUnavailableError): + source.search(book, _plan("Some Title")) + assert time.monotonic() - started < 5 + finally: + connection_manager.io_lock.release() + + +def test_search_rechecks_the_cache_once_it_has_the_lock(monkeypatch): + """A search queued behind an identical one is answered by the cache it just filled.""" + sent: list[str] = [] + + class FakeClient: + is_connected = True + online_servers: set[str] = set() + + def send_message(self, _channel: str, message: str) -> None: + sent.append(message) + + _configured_search(monkeypatch, FakeClient()) + answers = iter([None, {"releases": [], "online_servers": []}]) # miss, then filled + monkeypatch.setattr( + "shelfmark.release_sources.irc.cache.get_cached_results", lambda *_a: next(answers) + ) + source = IRCReleaseSource() + monkeypatch.setattr(source, "is_available", lambda: True) + + source.search(BookMetadata(provider="hardcover", provider_id="a", title="T"), _plan("T")) + + assert sent == [] + + +def test_a_connection_failure_is_unavailable_not_no_results(monkeypatch): + """Failing to connect or to send says nothing about the book, so it is never cached.""" + import pytest + + from shelfmark.release_sources import SourceUnavailableError + + class BrokenClient: + is_connected = True + online_servers: set[str] = set() + + def send_message(self, _channel: str, _message: str) -> None: + raise BrokenPipeError + + cache_calls = _configured_search(monkeypatch, BrokenClient()) + closed: list[object] = [] + monkeypatch.setattr( + "shelfmark.release_sources.irc.connection_manager.connection_manager.close_connection", + closed.append, + ) + source = IRCReleaseSource() + monkeypatch.setattr(source, "is_available", lambda: True) + + with pytest.raises(SourceUnavailableError): + source.search(BookMetadata(provider="hardcover", provider_id="a", title="T"), _plan("T")) + + assert cache_calls == [] + assert len(closed) == 1 + + +def test_a_denied_search_is_unavailable_not_no_results(monkeypatch): + import pytest + + from shelfmark.release_sources import SourceUnavailableError + from shelfmark.release_sources.irc.client import IRCError + + class DeniedClient: + is_connected = True + online_servers: set[str] = set() + + def send_message(self, _channel: str, _message: str) -> None: + pass + + def wait_for_dcc(self, **_kwargs: object) -> None: + msg = "Search results already waiting to be recieved. Search denied." + raise IRCError(msg) + + cache_calls = _configured_search(monkeypatch, DeniedClient()) + source = IRCReleaseSource() + monkeypatch.setattr(source, "is_available", lambda: True) + + with pytest.raises(SourceUnavailableError, match="Search denied"): + source.search(BookMetadata(provider="hardcover", provider_id="a", title="T"), _plan("T")) + + assert cache_calls == [] + + +def _search_with(monkeypatch, client): + """Run one search against `client`; return (cache calls, error or None).""" + from shelfmark.release_sources import SourceUnavailableError + + cache_calls = _configured_search(monkeypatch, client) + source = IRCReleaseSource() + monkeypatch.setattr(source, "is_available", lambda: True) + try: + source.search(BookMetadata(provider="hardcover", provider_id="a", title="T"), _plan("T")) + except SourceUnavailableError as e: + return cache_calls, e + return cache_calls, None + + +def test_a_failed_results_transfer_is_unavailable_and_keeps_the_connection(monkeypatch): + import shelfmark.release_sources.irc.source as irc_source + from shelfmark.release_sources.irc.dcc import DCCError, DCCOffer + + class OfferingClient: + is_connected = True + online_servers: set[str] = set() + + def send_message(self, _channel: str, _message: str) -> None: + pass + + def wait_for_dcc(self, **_kwargs: object) -> DCCOffer: + return DCCOffer(filename="Bot_results_for__T.txt.zip", ip="8.8.8.8", port=443, size=1) + + def reset(*_args: object, **_kwargs: object) -> None: + msg = "Failed reading from 8.8.8.8:443: connection reset" + raise DCCError(msg) + + monkeypatch.setattr(irc_source, "download_dcc", reset) + closed: list[object] = [] + manager = "shelfmark.release_sources.irc.connection_manager.connection_manager" + cache_calls = _configured_search(monkeypatch, OfferingClient()) + monkeypatch.setattr(f"{manager}.close_connection", closed.append) + source = IRCReleaseSource() + monkeypatch.setattr(source, "is_available", lambda: True) + + import pytest + + from shelfmark.release_sources import SourceUnavailableError + + with pytest.raises(SourceUnavailableError, match="transfer failed"): + source.search(BookMetadata(provider="hardcover", provider_id="a", title="T"), _plan("T")) + + assert cache_calls == [] + assert closed == [] # the IRC side is fine + + +class _WaitingClient: + """Answers nothing: the wait runs to its timeout. Or, with `sorry`, says no results. + + `sorry_left` delays the "Sorry" until that many seconds of the wait remain. + """ + + is_connected = True + online_servers: set[str] = set() + + def __init__(self, *, sorry: bool = False, sorry_left: float | None = None) -> None: + self.sorry = sorry or sorry_left is not None + self.sorry_left = sorry_left + self.sent: list[str] = [] + self.timeouts: list[float] = [] + self.last_wait_timed_out = False + + def send_message(self, _channel: str, message: str) -> None: + self.sent.append(message) + + def wait_for_dcc(self, *, timeout: float, **_kwargs: object) -> None: + self.timeouts.append(timeout) + self.last_wait_timed_out = not self.sorry + if not self.sorry: + time.sleep(timeout) + elif self.sorry_left is not None: + time.sleep(max(0.0, timeout - self.sorry_left)) + + +def test_the_wait_for_results_stops_at_the_search_deadline_and_is_not_cached(monkeypatch): + from shelfmark.core import search_deadline + + client = _WaitingClient() + with search_deadline.search_deadline(1.5): + cache_calls, error = _search_with(monkeypatch, client) + + assert error is not None + assert "ran out of time" in str(error) + assert client.timeouts and client.timeouts[0] <= 1.5 + assert cache_calls == [] + + +def test_nothing_is_sent_once_the_search_deadline_is_spent(monkeypatch): + from shelfmark.core import search_deadline + + client = _WaitingClient() + with search_deadline.search_deadline(0.5): + cache_calls, error = _search_with(monkeypatch, client) + + assert error is not None + assert client.sent == [] + assert cache_calls == [] + + +def test_a_real_no_results_inside_a_shortened_wait_is_still_cached(monkeypatch): + from shelfmark.core import search_deadline + + client = _WaitingClient(sorry=True) + with search_deadline.search_deadline(30): + cache_calls, error = _search_with(monkeypatch, client) + + assert error is None + assert client.timeouts[0] < 60 + assert len(cache_calls) == 1 + + +def test_a_no_results_reply_just_before_the_deadline_is_cached(monkeypatch): + from shelfmark.core import search_deadline + + client = _WaitingClient(sorry_left=0.3) # under the 1s margin once the wait ends + with search_deadline.search_deadline(1.5): + cache_calls, error = _search_with(monkeypatch, client) + + assert error is None + assert len(cache_calls) == 1