Skip to content

fix(network): close HTTP resources and harden Tor retries - #36

Open
jung233 wants to merge 20 commits into
Rimagination:masterfrom
jung233:codex/network-api
Open

fix(network): close HTTP resources and harden Tor retries#36
jung233 wants to merge 20 commits into
Rimagination:masterfrom
jung233:codex/network-api

Conversation

@jung233

@jung233 jung233 commented Jul 17, 2026

Copy link
Copy Markdown

Summary

  • close HTTP responses and sessions after JSON, publisher, arXiv, and Europe PMC requests
  • apply configured proxies only to Sci-Hub and LibGen when requested
  • correct the Elsevier institutional token header and Sci-Hub diagnostic host
  • stop Tor retry storms, serialize embedded Tor downloads, and reap failed subprocesses
  • propagate cancellation consistently through network and Tor selection

Dependency

This is a stacked PR on #32 because streaming response publication uses the atomic PDF primitives introduced there. The head includes #32 so it is directly runnable. After #32 merges, GitHub will reduce this PR to its seven Network and Tor commits.

Verification

  • rebased onto upstream v1.9.0 through the current fix: reclaim browser, PDF, and institutional resources #32 head; GitHub reports mergeable=true
  • Python 3.11 and Python 3.12 source compilation: passed
  • network, publisher, embedded Tor, and Tor imports: passed
  • ensure_tor and select_proxy_for_url expose matching optional cancel_event parameters

jung233 and others added 20 commits July 17, 2026 15:54
These functions were referenced in sources/__init__.py but never defined
in pdf_utils.py, causing ImportError on every download attempt.

- is_suspicious_pdf: checks if PDF is < 50KB (likely preview/cover)
- suspicious_pdf: returns failure result and cleans up the file

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
…Gen only

- Add proxy_only_scihub option (default false)
- When enabled, network_proxy only applies to Sci-Hub/LibGen domains
- Institutional sources (WebVPN, CARSI, EZProxy) remain unaffected
- Tor proxy bypasses this restriction
- Update README with config and usage docs

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- Add 1-hour cooldown for failed Tor binary downloads (avoids 30s DNS timeout per source)
- Reduce grace period: 120s for CARSI, 60s for browser, 10s for API sources
- Prevents 200s+ wait when all sources fail quickly
@jung233
jung233 force-pushed the codex/network-api branch from 14e2d98 to 002d0ca Compare July 17, 2026 08:38
@jung233
jung233 marked this pull request as ready for review July 17, 2026 09:31
Copilot AI review requested due to automatic review settings July 17, 2026 09:31

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR focuses on hardening network- and Tor-related resource lifecycles and cancellation behavior across the download stack, reducing leaked HTTP resources and preventing runaway Tor retry behavior.

Changes:

  • Add cooperative cancellation (cancel_event) support across Tor startup/selection and multiple networked sources.
  • Close or bind-and-close HTTP sessions/responses more consistently for JSON probes and streamed PDF downloads.
  • Rework publisher batch browser concurrency to respect Playwright sync thread affinity and improve cleanup/retry behavior.

Reviewed changes

Copilot reviewed 32 out of 32 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
src/scansci_pdf/tor.py Propagates cancellation into Tor ensure/start flow.
src/scansci_pdf/sources/scoring.py Updates Sci-Hub diagnostic host used by network diagnosis.
src/scansci_pdf/sources/publishers.py Adds cancel-aware delays, atomic streaming writes, and closes HTTP resources.
src/scansci_pdf/sources/instsci.py Adds cancellation, closes responses/sessions, and improves browser resource cleanup.
src/scansci_pdf/sources/ezproxy.py Adds cancellation hooks and improves browser/resource cleanup for EZProxy flow.
src/scansci_pdf/sources/europepmc.py Adjusts Europe PMC queries and switches PMC PDF URL to render endpoint.
src/scansci_pdf/sources/elsevier_api.py Corrects Elsevier institutional token header casing.
src/scansci_pdf/sources/carsi.py Adds cancel-aware locking/browser flow, atomic writes, and stronger cleanup.
src/scansci_pdf/sources/carsi_source.py Propagates cancellation and closes CARSI client deterministically.
src/scansci_pdf/sources/arxiv.py Ensures arXiv responses are closed after download attempts.
src/scansci_pdf/sources/init.py Adjusts racing grace-period behavior based on remaining futures/source mix.
src/scansci_pdf/server.py Improves Elsevier API setup test routing/cleanup; ensures CARSI clients are closed.
src/scansci_pdf/publisher_batch.py Reworks parallelism to avoid sharing Playwright contexts across threads; adds resilience.
src/scansci_pdf/pdf_utils.py Adds cancellation-safe atomic publish/write helpers; adds pdf=render URL heuristic.
src/scansci_pdf/network.py Adds session-pool locking, proxy-only-for-grey routing option, stream-slot release binding, and response close in JSON fetch.
src/scansci_pdf/main.py Updates CLI paths to use load_config()/new fetcher APIs and ensures close() in finally blocks.
src/scansci_pdf/fetcher.py Ensures HTTP responses are closed; improves browser response-capture listener cleanup.
src/scansci_pdf/extractors/pdf_extractor.py Makes PyMuPDF optional at import-time; closes documents reliably.
src/scansci_pdf/embedded_tor.py Adds cancellation support, cooldown after failed downloads, and improved lock acquisition.
src/scansci_pdf/deps.py Registers PyMuPDF as a core dependency description.
src/scansci_pdf/config.py Adds proxy_only_scihub configuration flag.
src/scansci_pdf/cloakbrowser_compat.py Adds launch wrapper to stop Playwright when CloakBrowser launch fails mid-flight.
src/scansci_pdf/cli.py Ensures fetcher/browser contexts are closed; adds broker helper handling invalidated contexts.
src/scansci_pdf/cache.py Uses collision-resistant temp filenames for cache writes.
src/scansci_pdf/browser_login.py Adds owner-thread lifecycle enforcement and safer slot/resource cleanup.
src/scansci_pdf/browser_engine.py Adds global browser slot limiting/retention, thread-owned tab handling, and cancel-aware PDF browser download.
src/scansci_pdf/browser_cookies.py Uses leased browser + confirms closure; prepares CloakBrowser runtime before launch.
src/scansci_pdf/auth.py Improves browser lifecycle confirmation/lease management and closes validation responses.
README.md Documents proxy_only_scihub configuration.
pyproject.toml Adds PyMuPDF dependency.
Dockerfile Installs cloakbrowser extra, required system libs, sets cache env, uses tini, and bounds allocator arenas.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 202 to 206
if active_proxy:
try:
import requests
resp = requests.get("https://sci-hub.mksa.top", timeout=10,
resp = requests.get("https://sci-hub.ru", timeout=10,
proxies={"https": active_proxy, "http": active_proxy},
Comment on lines +211 to +215
request_headers = {"Accept": "application/json", **(headers or {})}
resp = None
try:
resp = fetch(url, config, headers={"Accept": "application/json", **(headers or {})}, use_tor=use_tor)
resp = fetch(
url,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants