multi fixes (#1738)

- Fix #1737
- Fix #1736
- Fix #1728
- Fix #1730
- Fix #1732


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Improved Hardcover metadata searches by distinguishing series names,
title prefixes, and genre descriptors.
* Login redirects now wait until the logo loads or fails, and respond to
changes in the redirect setting.
* Increased tolerance for slow responses and improved handling of
temporary Hardcover connection failures.
* Fixed WireGuard setup when an environment-provided user ID conflicts
with the actual root ID.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
CaliBrain authored and GitHub committed 2026-11-19 19:28:08 -05:00
1 parent 75b88f55e0
commit 02efb0781b
7 files changed
+179 -8

No files matched your search

+3 -1
View File
@@ -185,7 +185,9 @@ def _apply_cf_bypass(url: str, headers: dict) -> dict:
# Network settings
REQUEST_TIMEOUT = (5, 10) # (connect, read)
# Anna's Archive's slow servers pause well past 10s, mid-file or before the first byte (#1732).
# Keep the read below the orchestrator's 5-minute stall timeout, which ends a stuck download.
REQUEST_TIMEOUT = (5, 60) # (connect, read)
MAX_DOWNLOAD_RETRIES = 2
MAX_RESUME_ATTEMPTS = 3
+10 -1
View File
@@ -13,6 +13,8 @@ from typing import TYPE_CHECKING, Any, ClassVar
from urllib.parse import urlparse
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
from shelfmark.core.cache import cache_key, cacheable, get_metadata_cache
from shelfmark.core.config import config as app_config
@@ -526,6 +528,11 @@ HARDCOVER_RATE_PER_SECOND = 0.8
HARDCOVER_RATE_LIMIT_ATTEMPTS = 3 # the first try plus two retries
HARDCOVER_RETRY_AFTER_CAP_SECONDS = 30.0 # longer than this (spent daily quota): give up
# Over some VPNs the first connection after a couple of idle minutes hangs until the timeout,
# and the search came back empty (#1736). Open a new connection once more when that happens. Safe for mutations too: urllib3 only retries a failed connect, which never reached
# Hardcover, and never resends a POST once the request went out (read=False).
HARDCOVER_CONNECT_RETRY = Retry(total=1, connect=1, read=False, other=0)
class _TokenBucket:
"""Thread-safe token bucket. ``acquire`` blocks until a request may go out.
@@ -1141,6 +1148,7 @@ class HardcoverProvider(MetadataProvider):
raw_key = api_key or app_config.get("HARDCOVER_API_KEY", "")
self.api_key = _normalize_hardcover_api_key(raw_key)
self.session = requests.Session()
self.session.mount(HARDCOVER_API_URL, HTTPAdapter(max_retries=HARDCOVER_CONNECT_RETRY))
if self.api_key:
self.session.headers.update(
{
@@ -2989,10 +2997,11 @@ class HardcoverProvider(MetadataProvider):
# Extract subtitle if available in search results
subtitle = item.get("subtitle")
search_title = _compute_search_title(title, subtitle)
series_id, series_name, series_position, series_count = _featured_series_fields(
item.get("featured_series") or (item.get("document") or {}).get("featured_series")
)
# Without the series, "Jack Reacher: A Novel" would be searched as "Jack Reacher".
search_title = _compute_search_title(title, subtitle, series_name=series_name)
if matched_title and matched_title != title:
# The subtitle belongs to the original title, not to the translation.
+5 -3
View File
@@ -2,7 +2,7 @@ import type { FormEvent, KeyboardEvent } from 'react';
import { useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useMountEffect } from '../hooks/useMountEffect';
import { useDependencyEffect, useMountEffect } from '../hooks/useMountEffect';
import type { LoginCredentials } from '../types';
import { buildOidcLoginUrl } from '../utils/authRedirect';
import { withBasePath } from '../utils/basePath';
@@ -246,11 +246,13 @@ export const LoginForm = ({
}
}
useMountEffect(() => {
// Keyed on oidcAutoRedirect rather than run once at mount: LoginPage holds it
// false until the logo has loaded, so the redirect fires when it turns on.
useDependencyEffect(() => {
if (oidcAutoRedirect && isOidc && !error && !oidcError) {
window.location.href = oidcLoginUrl;
}
});
}, [oidcAutoRedirect]);
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
+14 -2
View File
@@ -1,3 +1,5 @@
import { useState } from 'react';
import { LoginForm } from '../components/LoginForm';
import type { LoginCredentials } from '../types';
import { withBasePath } from '../utils/basePath';
@@ -22,6 +24,10 @@ export const LoginPage = ({
oidcAutoRedirect,
}: LoginPageProps) => {
const logoUrl = withBasePath('/logo.png');
// Navigating away cancels a logo that is still loading, and Firefox then shows
// it as a broken image until the OIDC provider answers. Hold the auto-redirect
// until the logo has loaded or failed; a failure must not block sign-in.
const [logoSettled, setLogoSettled] = useState(false);
return (
<div
@@ -38,7 +44,13 @@ export const LoginPage = ({
}}
>
<div className="mb-5 text-center">
<img src={logoUrl} alt="Logo" className="mx-auto h-12 w-12" />
<img
src={logoUrl}
alt="Logo"
className="mx-auto h-12 w-12"
onLoad={() => setLogoSettled(true)}
onError={() => setLogoSettled(true)}
/>
</div>
<LoginForm
onSubmit={onLogin}
@@ -47,7 +59,7 @@ export const LoginPage = ({
authMode={authMode}
oidcButtonLabel={oidcButtonLabel}
hideLocalAuth={hideLocalAuth}
oidcAutoRedirect={oidcAutoRedirect}
oidcAutoRedirect={oidcAutoRedirect && logoSettled}
/>
</div>
</div>
@@ -0,0 +1,110 @@
"""A Hardcover connection that fails to open is tried once more (#1736), but a request
that reached Hardcover is never sent twice, since some GraphQL calls are mutations."""
import json
import threading
from collections.abc import Iterator
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
import urllib3.util.connection
from shelfmark.metadata_providers import hardcover
from shelfmark.metadata_providers.hardcover import HardcoverProvider, _TokenBucket
PAT = "hc_pat_" + "a" * 32
class FakeHardcover(ThreadingHTTPServer):
def __init__(self) -> None:
super().__init__(("127.0.0.1", 0), _Handler)
self.posts = 0
self.drop = False
class _Handler(BaseHTTPRequestHandler):
server: FakeHardcover
def do_POST(self) -> None:
self.rfile.read(int(self.headers["Content-Length"]))
self.server.posts += 1
if self.server.drop:
self.close_connection = True
return
body = json.dumps({"data": {"me": [{"id": 1}]}}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *_args: object) -> None:
pass
class Connects:
"""Counts connection attempts and times out the first ``failures`` of them."""
def __init__(self) -> None:
self.attempts = 0
self.failures = 0
@pytest.fixture
def server(monkeypatch) -> Iterator[FakeHardcover]:
fake = FakeHardcover()
threading.Thread(target=fake.serve_forever, daemon=True).start()
monkeypatch.setattr(
hardcover, "HARDCOVER_API_URL", f"http://127.0.0.1:{fake.server_port}/v1/graphql"
)
monkeypatch.setattr(hardcover, "_rate_limiter", _TokenBucket(5, 1.0))
monkeypatch.setenv("NO_PROXY", "127.0.0.1")
monkeypatch.setenv("no_proxy", "127.0.0.1")
yield fake
fake.shutdown()
fake.server_close()
@pytest.fixture
def connects(monkeypatch) -> Connects:
real = urllib3.util.connection.create_connection
state = Connects()
def create_connection(address, *args, **kwargs):
state.attempts += 1
if state.attempts <= state.failures:
raise TimeoutError("timed out")
return real(address, *args, **kwargs)
monkeypatch.setattr(urllib3.util.connection, "create_connection", create_connection)
return state
def test_a_connect_that_times_out_is_retried_on_a_new_connection(server, connects):
connects.failures = 1
result = HardcoverProvider(api_key=PAT)._execute_query("query { me { id } }", {})
assert result == {"me": [{"id": 1}]}
assert connects.attempts == 2
assert server.posts == 1
def test_gives_up_after_one_retry(server, connects):
connects.failures = 2
result = HardcoverProvider(api_key=PAT)._execute_query("query { me { id } }", {})
assert result is None
assert connects.attempts == 2
assert server.posts == 0
def test_a_request_that_reached_hardcover_is_not_sent_again(server, connects):
server.drop = True
result = HardcoverProvider(api_key=PAT)._execute_query("mutation { noop }", {})
assert result is None
assert server.posts == 1
assert connects.attempts == 1
+28 -1
View File
@@ -53,13 +53,40 @@ def test_a_search_result_nested_in_a_document_carries_the_series_too():
assert book.series_name == "The Mistborn Saga: The Original Trilogy"
def test_the_search_title_is_unchanged_by_the_series():
def test_a_series_named_unlike_the_title_prefix_leaves_the_search_title():
book = _provider()._parse_search_result(_hit())
assert book is not None
assert book.search_title == "Mistborn"
def _series(name: str) -> dict:
return {"position": 1.0, "series": {"id": 1, "name": name, "primary_books_count": 3}}
def test_a_series_prefix_is_dropped_from_a_search_result_like_from_a_full_record():
book = _provider()._parse_search_result(
_hit(title="Mistborn: The Final Empire", featured_series=_series("Mistborn"))
)
assert book is not None
assert book.search_title == "The Final Empire"
def test_a_series_followed_by_a_genre_descriptor_is_not_searched_as_the_series():
# Without the series, #1728's fix would search "Jack Reacher" and match any volume.
book = _provider()._parse_search_result(
_hit(
title="Jack Reacher: A Novel",
subtitle="A Novel",
featured_series=_series("Jack Reacher"),
)
)
assert book is not None
assert book.search_title is None
def test_a_hit_with_a_null_document_and_no_series_is_still_parsed():
book = _provider()._parse_search_result(_hit(featured_series=None, document=None))
+9
View File
@@ -117,6 +117,15 @@ fi
set +x
set -e
# wg-quick re-runs itself through sudo (absent here) unless bash's $UID is 0, and bash
# takes $UID from the environment when one is set. The legacy UID setting (e.g. Unraid's
# UID=99) is for the app user, read by entrypoint.sh; drop it so wg-quick, here and in
# the supervised healthcheck, sees the real root UID (#1730). Only an imported UID can
# be unset; bash's own is readonly.
if printenv UID >/dev/null 2>&1; then
unset UID
fi
WIREGUARD_CONFIG="${WIREGUARD_CONFIG:-/config/wg0.conf}"
WIREGUARD_INTERFACE="${WIREGUARD_INTERFACE:-wg0}"
WIREGUARD_ENFORCE_DNS_VALUE="${WIREGUARD_ENFORCE_DNS:-true}"